PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence install up down restart ps logs wait-ready destroy-data student-test concurrency-test test-expiry test-failures test-migrations explain sigterm-check

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "up/down/restart/ps/logs: compose stack; destroy-data: DELETE volumes intentionally"
	@echo "student-test: own tests; test-migrations: from empty volume; test-expiry: short SESSION_TTL; test-failures: stop Valkey/PostgreSQL; explain: EXPLAIN history"

check:
	$(PYTHON) scripts/check_contract.py

validate:
	$(PYTHON) scripts/validate_openapi.py

test:
	$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)

load:
	$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-persistence:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
	$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

install:
	poetry install --no-root

up:
	docker compose up -d --build --wait

down:
	docker compose --profile expiry down

restart:
	./scripts/restart.sh
	@$(MAKE) --no-print-directory wait-ready

ps:
	docker compose ps

logs:
	docker compose logs -f api

wait-ready:
	@for i in $$(seq 1 60); do \
		curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1 && echo "ready: $(BASE_URL)" && exit 0; \
		sleep 1; \
	done; echo "API is not ready after 60s"; exit 1

destroy-data:
	docker compose --profile expiry down -v

student-test:
	BASE_URL="$(BASE_URL)" poetry run pytest

concurrency-test:
	BASE_URL="$(BASE_URL)" poetry run pytest student-tests/test_concurrency.py -s

test-expiry:
	docker compose --profile expiry up -d --build --wait api-short-ttl
	EXPIRY_BASE_URL=http://localhost:8081 poetry run pytest student-tests/test_expiry.py -s; \
		status=$$?; docker compose --profile expiry stop api-short-ttl; exit $$status

test-failures:
	BASE_URL="$(BASE_URL)" RUN_FAILURE_TESTS=1 poetry run pytest student-tests/test_dependency_failures.py -s

test-migrations:
	./scripts/check_migrations.sh

explain:
	docker compose exec -T postgres sh -c 'psql -X -q -v ON_ERROR_STOP=1 -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"' \
		< scripts/explain_history.sql > evidence/explain_history.txt
	@echo "saved: evidence/explain_history.txt"

sigterm-check:
	$(PYTHON) scripts/sigterm_check.py --base-url "$(BASE_URL)"
