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 test-failover secrets up down restore rolling-update test-student test-attachments test-upload-failover test-consistency test-s3-security sweep-dry-run memory chaos

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)

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

secrets:
	sh scripts/init-secrets.sh

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

down:
	docker compose down

restore:
	sh scripts/restore.sh

rolling-update:
	sh scripts/rolling-update.sh

# Own tests (student-tests/); they use the running compose stack, some stop/start containers.
test-attachments:
	$(PYTHON) student-tests/attachments_test.py --base-url "$(BASE_URL)"

test-upload-failover:
	$(PYTHON) student-tests/upload_failover.py --base-url "$(BASE_URL)"

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

test-s3-security:
	$(PYTHON) student-tests/s3_security_test.py --base-url "$(BASE_URL)"

test-student: test-attachments test-s3-security test-upload-failover test-consistency
	$(PYTHON) student-tests/idempotency_test.py --base-url "$(BASE_URL)"

sweep-dry-run:
	docker compose run --rm --no-deps -T sweeper python -m app.sweeper --once --dry-run

memory:
	$(PYTHON) student-tests/upload_memory.py --base-url "$(BASE_URL)" --concurrency 10

chaos:
	@for n in 1 2; do \
	  name=$$(docker compose ps --format '{{.Name}}' api | sed -n "$${n}p"); \
	  $(PYTHON) student-tests/chaos_load.py --base-url "$(BASE_URL)" --action "scripts/stop-container.sh $$name" --output evidence/failover-load/stop-api-$$n.json | $(PYTHON) -c 'import json,sys; d=json.load(sys.stdin); print(json.dumps({k: d[k] for k in ("action_output","requests","errors","successful_rps","latency_ms_success","recovery_s_after_action","integrity")},ensure_ascii=False,indent=1))'; \
	  sh scripts/restore.sh >/dev/null 2>&1; sleep 3; \
	done
