# ---------------------------------------------------------------------------
# Catan -- dev workflow: venv, setup, tests, lint, run.
#
# Every recipe invokes the venv's binaries by absolute path instead of
# `source .venv/bin/activate`, so the file works under sh, dash and bash
# alike (make defaults to /bin/sh, where `source` does not exist).
# ---------------------------------------------------------------------------
PY ?= python3
VENV := .venv
BIN := $(VENV)/bin
VPY := $(BIN)/python
VPIP := $(BIN)/pip

# Every test target runs muted: no audio device is opened, so a test run never
# grabs the demo's PulseAudio sink or makes noise.  tests/conftest.py sets the
# same defaults; this keeps a bare `make test-functional` honest even if the
# conftest is bypassed or CATAN_MUTE is exported in the calling shell.
TESTENV := CATAN_MUTE=1 QT_QPA_PLATFORM=offscreen

.DEFAULT_GOAL := help
.PHONY: help venv setup install test test-unit test-integration test-functional \
        coverage lint format typecheck check run clean distclean

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \
		| awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-18s\033[0m %s\n", $$1, $$2}'

$(VPY):
	$(PY) -m venv $(VENV)
	@$(VPY) -m pip install --upgrade pip setuptools wheel

venv: $(VPY) ## Create the virtual environment (idempotent)

setup: venv install ## Create venv and install all dev dependencies

install: $(VPY) ## Install runtime + dev requirements
	@$(VPIP) install -r requirements-dev.txt

test: ## Run the whole test suite
	@$(TESTENV) $(VPY) -m pytest

test-unit: ## Unit tests only
	@$(TESTENV) $(VPY) -m pytest tests/unit

test-integration: ## Integration tests only
	@$(TESTENV) $(VPY) -m pytest tests/integration

test-functional: ## Functional / end-to-end tests only
	@$(TESTENV) $(VPY) -m pytest tests/functional

coverage: ## Test suite with a coverage report
	@$(TESTENV) $(VPY) -m pytest --cov=catan --cov-report=term-missing

lint: ## Lint (ruff) and type-check (mypy)
	@$(BIN)/ruff check catan tests
	@$(BIN)/mypy catan

format: ## Auto-format and auto-fix
	@$(BIN)/ruff format catan tests
	@$(BIN)/ruff check --fix catan tests

typecheck: ## Type-check only
	@$(BIN)/mypy catan

check: lint test ## Lint + type-check + tests (the CI gate)

run: venv ## Launch the PySide6 application
	@$(VPY) -m catan

stream: venv ## Live stream: 4 computer seats, auto-deal forever, JSON ledger of every game
	@mkdir -p runs
	@$(VPY) -m catan --players 4 --seats "P1:C:strong,P2:C:strong,P3:C:strong,P4:C:strong" --speed 400 --stream --ledger runs/stream-ledger.json

video: venv ## Record replays/game_101.json to frames/, then encode video/replay.{gif,mp4} (needs ffmpeg)
	@$(VPY) tools/record_video.py

clean: ## Remove caches and build artefacts
	rm -rf .pytest_cache .mypy_cache .ruff_cache .coverage htmlcov
	find . -type d -name __pycache__ -prune -exec rm -rf {} +

distclean: clean ## Also remove the virtual environment
	rm -rf $(VENV)
