PYTHON ?= python3
# 127.0.0.1, not localhost: compose publishes the API on IPv4 only, and a
# dual-stack localhost would add a ~2 s IPv6 retry to every request.
BASE_URL ?= http://127.0.0.1:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
STUDENT_DIR = student-tests

.PHONY: help check validate test load test-persistence run bootstrap up down test-student test-ttl test-degradation explain research-history-backup

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "bootstrap/up/down: local Compose stand; run: API without Docker (needs DATABASE_URL/CACHE_URL)"
	@echo "test-student: own functional+race tests; test-ttl: expiry on the short-TTL stand; test-degradation: cache/DB outages"
	@echo "explain: seed 12k messages and capture EXPLAIN (ANALYZE, BUFFERS) into evidence/"
	@echo "research-history-backup: grade-5 100k index comparison and PostgreSQL backup/restore"

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)

# --- lab 2 -----------------------------------------------------------------
run:
	$(PYTHON) -B src/app.py

bootstrap:
	sh scripts/bootstrap-secrets.sh

up: bootstrap
	docker compose --env-file .env up -d --build --wait --wait-timeout 180
	docker compose --env-file .env ps

down:
	docker compose --env-file .env down

test-student:
	cd $(STUDENT_DIR) && BASE_URL="$(BASE_URL)" $(PYTHON) -B -m unittest -v test_api test_race

test-ttl:
	sh scripts/test-ttl.sh

test-degradation:
	cd $(STUDENT_DIR) && BASE_URL="$(BASE_URL)" STUDENT_DOCKER_TESTS=1 $(PYTHON) -B -m unittest -v test_degradation

explain:
	sh scripts/explain-history.sh

research-history-backup:
	sh scripts/research-history-backup.sh
