PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
COMPOSE = docker compose --env-file .env
COMPOSE_TEST = $(COMPOSE) -f compose.yaml -f compose.test.yaml
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence test-failover env up down clean restore student-test test-failures explain failover-each failover-hard rolling-update

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)

env:
	./scripts/init-env.sh

up: env
	$(COMPOSE) up -d --build
	BASE_URL="$(BASE_URL)" ./scripts/wait-ready.sh

down:
	$(COMPOSE_TEST) down

# удаляет контейнеры вместе с данными PostgreSQL и Redis
clean:
	$(COMPOSE_TEST) down -v

# возвращает реплики, остановленные scripts/stop-one.sh
restore:
	$(COMPOSE) up -d --no-recreate --no-build api
	BASE_URL="$(BASE_URL)" ./scripts/wait-ready.sh

student-test:
	BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests -v

# останавливает и запускает redis/postgres, поднимает отдельный API на порту 8081
test-failures:
	BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests/failures -v

explain:
	./scripts/explain_history.sh

# по очереди останавливает каждую реплику под нагрузкой
failover-each:
	BASE_URL="$(BASE_URL)" $(PYTHON) scripts/chaos.py stop --output evidence/failover-each.json

# то же с SIGKILL и с зависшей репликой (docker pause)
failover-hard:
	BASE_URL="$(BASE_URL)" $(PYTHON) scripts/chaos.py kill --output evidence/failover-kill.json
	BASE_URL="$(BASE_URL)" $(PYTHON) scripts/chaos.py pause --output evidence/failover-pause.json

# заменяет реплики новым образом под нагрузкой: make rolling-update APP_VERSION=2
rolling-update:
	BASE_URL="$(BASE_URL)" $(PYTHON) scripts/chaos.py rolling --output evidence/rolling-update.json
