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

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)

# ---------------------------------------------------------------------------------------------
# Цели решения (lab4). Публичные цели выше не изменены.
# ---------------------------------------------------------------------------------------------
COMPOSE ?= docker compose --env-file .env

.PHONY: secrets up down ps logs destroy-data restore s3-check reconcile reconcile-apply test-student \
        test-attachments test-storage-failures test-reconcile test-api test-idempotency test-expiry \
        test-cache-race test-failures upload-memory reconcile-cost evidence

secrets:
	./scripts/init-secrets.sh

# Единая команда запуска: LB + 2 реплики API + migrate + s3-init (one-shot) + PostgreSQL + Redis + S3.
up: secrets
	$(COMPOSE) --profile ttl up -d --build --wait

ps:
	$(COMPOSE) --profile ttl --profile fault ps -a

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

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

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

# Вернуть реплики после make test-failover ACTION_SCRIPT=scripts/stop-one.sh
restore:
	./scripts/start-replicas.sh

# Проверка приватности bucket вне API (анонимные запросы, права ключа API).
s3-check:
	$(COMPOSE) exec -T api python -m messenger s3-check

# Трек 2: reconciler. По умолчанию dry-run (код 2 = есть расхождения); исправление — reconcile-apply.
reconcile:
	-$(COMPOSE) exec -T api python -m messenger reconcile

reconcile-apply:
	$(COMPOSE) exec -T api python -m messenger reconcile --apply

test-attachments:
	$(PYTHON) student-tests/test_attachments.py

# Останавливает/запускает s3, поднимает профиль fault (api-fault, :8082). Volumes не трогает.
test-storage-failures:
	$(PYTHON) student-tests/test_storage_failures.py

test-reconcile:
	$(PYTHON) student-tests/test_reconcile.py

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

test-idempotency:
	$(PYTHON) student-tests/test_idempotency.py

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

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

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

test-student: test-attachments test-api test-idempotency test-expiry test-cache-race test-storage-failures test-failures test-reconcile

# Уровень 4: ≥10 одновременных загрузок с измерением пика памяти API и S3.
upload-memory:
	$(PYTHON) research/upload_memory.py --output evidence/upload-memory.json

# Трек 2: стоимость обхода reconciler (1k/5k/20k объектов).
reconcile-cost:
	$(PYTHON) research/reconcile_cost.py --sizes 1000,5000,20000 --output evidence/reconcile-cost.json

evidence:
	./scripts/collect-evidence.sh
