.PHONY: lock sync format format-check lint type typecheck test test-fast coverage docs import-smoke example-smoke benchmark benchmark-smoke experiment-smoke smoke version-check build-package wheel-smoke package-check check

UV ?= uv
UV_RUN ?= $(UV) run --locked
PYTHON ?= $(UV_RUN) python
MYPY_TARGETS ?= src/pyblackwell experiments/article_v2 experiments/article_contract_monitor_v2.py
MYPY_PYTHON_VERSION ?= 3.10
QUALITY_PATHS ?= .
FAST_TEST_MARKERS ?= not slow and not network and not gpu and not benchmark
TEST_ARGS ?=

lock:
	$(UV) lock

sync:
	$(UV) sync --locked

format:
	$(UV_RUN) ruff format $(QUALITY_PATHS)

format-check:
	$(UV_RUN) ruff format --check $(QUALITY_PATHS)

lint:
	$(UV_RUN) ruff check $(QUALITY_PATHS)

type:
	$(UV_RUN) mypy --python-version $(MYPY_PYTHON_VERSION) $(MYPY_TARGETS)

typecheck: type

test:
	$(PYTHON) -m pytest --durations=20 $(TEST_ARGS)

test-fast:
	$(PYTHON) -m pytest -m "$(FAST_TEST_MARKERS)" --durations=20 $(TEST_ARGS)

coverage:
	$(PYTHON) -m pytest -m "$(FAST_TEST_MARKERS)" --cov=pyblackwell --cov-branch --cov-report=term-missing --cov-report=xml:coverage.xml --junitxml=junit.xml --durations=20 $(TEST_ARGS)

docs:
	$(UV_RUN) mkdocs build --strict

import-smoke:
	$(PYTHON) -c "import approachability; import pyblackwell; assert pyblackwell.MatrixGame is approachability.MatrixGame"

example-smoke:
	$(PYTHON) -m pytest tests/test_imports_and_examples.py

benchmark-smoke:
	$(PYTHON) benchmarks/run_benchmarks.py --mode smoke --iterations 20

benchmark:
	$(PYTHON) -m pytest benchmarks -m benchmark --benchmark-json=benchmark.json

experiment-smoke:
	$(PYTHON) -m pytest tests/test_article_v2_smoke.py \
		tests/test_article_v2_blog_box.py::test_complete_bundle_has_real_outputs_and_passes_independent_audit

smoke: import-smoke example-smoke benchmark-smoke experiment-smoke

version-check:
	$(PYTHON) -c "import os; from importlib import metadata; tag = os.environ.get('CI_COMMIT_TAG'); expected = 'v' + metadata.version('pyblackwell'); tag is None or tag == expected or (_ for _ in ()).throw(SystemExit(f'release tag {tag!r} does not match package version {expected!r}'))"

build-package:
	$(UV) build --clear

wheel-smoke:
	@set -eu; \
	tmpdir="$$(mktemp -d)"; \
	trap 'rm -rf "$$tmpdir"' 0; \
	$(UV) venv "$$tmpdir/venv"; \
	$(UV) pip install --python "$$tmpdir/venv/bin/python" dist/*.whl; \
	PYTHONPATH= "$$tmpdir/venv/bin/python" -c "from importlib import metadata; import approachability; import pyblackwell; assert pyblackwell.MatrixGame is approachability.MatrixGame; assert pyblackwell.__version__ == metadata.version('pyblackwell')"

package-check: version-check build-package
	$(UV_RUN) twine check --strict dist/*
	$(MAKE) wheel-smoke

check: lint type import-smoke test docs example-smoke format-check benchmark-smoke experiment-smoke
