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

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)

# ---------------------------------------------------------------------------------------------
# Цели решения (lab2). Публичные цели выше не изменены.
# ---------------------------------------------------------------------------------------------
COMPOSE ?= docker compose --env-file .env
TTL_BASE_URL ?= http://localhost:8081

.PHONY: secrets up up-ttl down ps logs destroy-data test-student test-api test-expiry test-failures test-cache-race \
        research-track2 research-up evidence

secrets:
	./scripts/init-secrets.sh

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

up-ttl:
	$(COMPOSE) --profile ttl up -d --build --wait api-ttl

ps:
	$(COMPOSE) --profile ttl --profile research ps

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

# Безопасная остановка: контейнеры удаляются, именованные volumes (данные) сохраняются.
down:
	$(COMPOSE) --profile ttl --profile research down

# НАМЕРЕННОЕ удаление учебных данных (volumes pgdata/pgrestore). Необратимо.
destroy-data:
	@echo "This deletes ALL lab2 data volumes. Type 'yes' to continue:"; read ans; [ "$$ans" = yes ]
	$(COMPOSE) --profile ttl --profile research down -v

test-api:
	$(PYTHON) student-tests/test_api.py

test-expiry:
	TTL_BASE_URL="$(TTL_BASE_URL)" $(PYTHON) student-tests/test_expiry.py

# Останавливает/запускает контейнеры redis и postgres (volumes не трогает).
test-failures:
	$(PYTHON) student-tests/test_failures.py

# In-process проверка гонки кэш/logout внутри контейнера API (сеть backend, реальный Redis).
test-cache-race:
	$(COMPOSE) run --rm --no-deps -T -v "$(CURDIR)/student-tests:/app/student-tests:ro" --entrypoint python api student-tests/test_cache_race.py

test-student: test-api test-expiry test-cache-race test-failures

research-up:
	$(COMPOSE) --profile research up -d --wait postgres-restore

research-track2: research-up
	$(PYTHON) research/track2.py

evidence:
	./scripts/collect-evidence.sh
