PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
COMPOSE ?= docker compose --env-file .env
VUS ?= 10
DURATION ?= 60s
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence test-failover test-concurrency app-test app-build up down wait k6

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API"
	@echo "test-concurrency: cross-replica idempotency race; test-failover/persistence: explicit hooks"
	@echo "load: synthetic writes via tests/load.py; k6: k6 write load through HAProxy"
	@echo "up/down/wait: compose lifecycle; app-test: Go unit tests"

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)

# ---------------------------
# Custom convenience commands
# ---------------------------

test-concurrency:
	$(PYTHON) tests/custom/idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS)

app-test:
	cd app && go test ./...

app-build:
	cd app && go build ./cmd/server

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

down:
	$(COMPOSE) down

wait:
	@echo "waiting for $(BASE_URL)/health/ready"
	@until curl -fsS "$(BASE_URL)/health/ready" >/dev/null; do sleep 1; done
	@echo "ready"

k6:
	$(COMPOSE) --profile load run --rm k6 run -e VUS=$(VUS) -e DURATION=$(DURATION) --summary-export /results/last.json /scripts/messages.js
