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 secrets up down migrate test-student test-expiry test-storage test-failures test-revocation explain

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"

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)

#Решение
COMPOSE ?= docker compose --env-file .env
EXPIRY_URL ?= http://localhost:8081

secrets:
	$(PYTHON) scripts/init_secrets.py
	@test -f .env || cp .env.example .env

up: secrets
	$(COMPOSE) up -d --build --wait

down:
	$(COMPOSE) --profile ttl down

migrate:
	$(COMPOSE) exec api python -m src.migrate

test-student:
	BASE_URL="$(BASE_URL)" $(PYTHON) student-tests/run_all.py --base-url "$(BASE_URL)"

test-expiry:
	$(COMPOSE) --profile ttl up -d --wait api-short-ttl
	EXPIRY_BASE_URL="$(EXPIRY_URL)" BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests -p test_expiry.py -v

test-storage:
	$(COMPOSE) run --rm --no-deps -v "$(CURDIR)/student-tests:/app/student-tests:ro" api \
		sh -c "python -m unittest discover -s student-tests -p test_storage_rollback.py -v && python -m unittest discover -s student-tests -p test_session_cache.py -v"

test-failures:
	$(PYTHON) student-tests/dependency_failure.py --base-url "$(BASE_URL)" --output evidence/dependency_failure.json

test-revocation:
	$(PYTHON) student-tests/revocation_partition.py --base-url "$(BASE_URL)" | tee evidence/revocation_partition.txt

explain:
	$(COMPOSE) exec -T postgres psql -U messenger -d messenger -v ON_ERROR_STOP=1 < scripts/sql/explain_history.sql > evidence/explain_history.txt
	@echo "saved evidence/explain_history.txt"
