PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
COMPOSE = docker compose --project-name highload-lab3 --env-file .env -f compose.yml
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help app-up app-down app-logs app-status test-backend test-baseline test-baseline-persistence check validate test load test-persistence test-failover

help:
	@echo "app-up: prepare local environment, migrate, build and start HAProxy, two API replicas, PostgreSQL, Redis and frontend"
	@echo "app-down: stop application; keep database and session volumes"
	@echo "app-logs / app-status: inspect application"
	@echo "app-rolling-update: build, migrate once and replace API replicas one by one; test-grade4: limits, idempotency, failures and rolling load"
	@echo "test-backend: Go race tests against PostgreSQL and Redis"
	@echo "test-baseline / test-baseline-persistence: transferred lab2 API; second target stops and starts lab3"
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"

app-up:
	$(PYTHON) scripts/init_env.py
	chmod +x scripts/restart.sh scripts/stop-one.sh
	$(COMPOSE) up -d --build --wait

app-down:
	$(COMPOSE) down

app-logs:
	$(COMPOSE) logs -f

app-status:
	$(COMPOSE) ps

.PHONY: app-rolling-update test-grade4
app-rolling-update:
	$(COMPOSE) build api migrate
	$(PYTHON) scripts/rolling_update.py

test-grade4:
	$(PYTHON) scripts/check_resources.py
	$(PYTHON) scripts/check_idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS)
	$(PYTHON) scripts/check_failover.py --base-url "$(BASE_URL)" $(TLS_ARGS)
	$(PYTHON) scripts/check_rolling.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-backend:
	$(COMPOSE) --profile test run --build --rm backend-tests

test-baseline:
	$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)"

test-baseline-persistence:
	$(PYTHON) scripts/check_baseline.py --base-url "$(BASE_URL)" --restart

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)
