.DEFAULT_GOAL := help

UV ?= uv
OSV_SCANNER ?= osv-scanner
TEST_ARGS ?= -q
CIRCE_ARGS ?=

.PHONY: help setup setup-prod lock lock-check deps-check build publish test test-live format format-check check serve workers run clean

help: ## Show available tasks and configuration
	@printf 'Usage: make <target>\n\n'
	@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "  %-16s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
	@printf '\nVariables: UV=uv, OSV_SCANNER=osv-scanner, TEST_ARGS="-q", CIRCE_ARGS=""\n'
	@printf 'Example: make test TEST_ARGS="-v -k polling"\n'

setup: ## Create .venv and install locked runtime and development dependencies
	$(UV) sync --locked

setup-prod: ## Install only locked runtime dependencies in .venv
	$(UV) sync --locked --no-dev

lock: ## Update uv.lock after editing dependencies in pyproject.toml
	$(UV) lock

lock-check: ## Check that uv.lock matches pyproject.toml
	$(UV) lock --check

deps-check: lock-check ## Scan locked dependencies for vulnerabilities with OSV-Scanner v2
	@command -v "$(OSV_SCANNER)" >/dev/null 2>&1 || { \
		printf '%s\n' 'OSV-Scanner v2 is required: https://google.github.io/osv-scanner/installation/' >&2; \
		exit 127; \
	}
	"$(OSV_SCANNER)" scan source --lockfile=uv.lock

build: ## Build the source archive and wheel in dist/
	$(UV) build --clear

publish: build ## Build and upload the source archive and wheel to PyPI
	$(UV) publish

test: ## Run integration tests against an automatically managed temporary server
	$(UV) run --locked python scripts/run_tests.py $(TEST_ARGS)

test-live: ## Run tests against an existing server configured with CIRCE_* variables
	$(UV) run --locked pytest test.py $(TEST_ARGS)

format: ## Format Python sources, tests and scripts with Ruff
	$(UV) run --locked ruff format circe test.py scripts

format-check: ## Check Python formatting without changing files
	$(UV) run --locked ruff format --check circe test.py scripts

check: lock-check format-check test ## Check the lockfile, formatting and integration tests

serve: ## Start the HTTP server (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe serve $(CIRCE_ARGS)

workers: ## Start transformation workers (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe start-workers $(CIRCE_ARGS)

run: ## Start the HTTP server and workers (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe run $(CIRCE_ARGS)

clean: ## Remove distribution artifacts and local pytest and Ruff caches
	rm -rf dist .pytest_cache .ruff_cache
