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

COMPOSE ?= docker compose --env-file .env

.PHONY: help check validate test load test-persistence bootstrap build up down logs ps migrate psql test-custom expiry dependency outages explain track2 evidence

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "bootstrap: local .env and secrets; build/up/down: compose stack; migrate: apply SQL migrations"
	@echo "test-custom: own level-4 checks; expiry: short-TTL instance; dependency: cache and database outages"
	@echo "outages: revocation vs cache restart, hung database; evidence: full run into evidence/"
	@echo "explain: history query plan on 10k rows; track2: grade-5 experiment; test-persistence: restart hook"

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)

bootstrap:
	sh scripts/bootstrap.sh

build:
	$(COMPOSE) build

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

down:
	$(COMPOSE) down

logs:
	$(COMPOSE) logs --tail=100 api

ps:
	$(COMPOSE) ps

migrate:
	$(COMPOSE) run --rm migrate

psql:
	$(COMPOSE) exec postgres psql -U messenger -d messenger

test-custom:
	$(PYTHON) student-tests/test_auth_sessions.py --base-url "$(BASE_URL)"
	$(PYTHON) student-tests/test_storage_rules.py --base-url "$(BASE_URL)"

expiry:
	sh student-tests/expiry.sh

dependency:
	sh student-tests/dependency.sh

outages:
	$(PYTHON) student-tests/test_outages.py --base-url "$(BASE_URL)"

explain:
	sh student-tests/explain.sh

track2:
	TOTAL=$(or $(TOTAL),120000) sh student-tests/track2.sh

evidence:
	sh student-tests/evidence.sh
