PYTHON ?= python3
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

APP_VERSION ?=

.PHONY: help check validate test load test-persistence test-failover test-idempotency failover-series rolling-update lb-status scale-cost

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "failover-series, rolling-update APP_VERSION=..., lb-status: level 4 experiments (Docker required)"
	@echo "scale-cost: level 5 track 1 (1/2/4 replicas at a fixed CPU/RAM budget, then grow resources)"

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)

test-idempotency:
	$(PYTHON) scripts/check_idempotency.py --base-url "$(BASE_URL)"

# Level 4: stop each API replica in turn under load (restoring the previous one); RPS, errors, recovery.
failover-series:
	$(PYTHON) scripts/failover_series.py --base-url "$(BASE_URL)" --output evidence/failover-series.json

# Level 4: one-at-a-time replacement under load. Usage: make rolling-update APP_VERSION=v3
rolling-update:
	@test -n "$(APP_VERSION)" || (echo "Set APP_VERSION of the new build"; exit 2)
	APP_VERSION="$(APP_VERSION)" $(PYTHON) scripts/failover_series.py --mode action --action scripts/rolling-update.sh --base-url "$(BASE_URL)" --output evidence/rolling-update.json

lb-status:
	sh scripts/lb-status.sh

# Level 5 track 1: 1/2/4 API replicas at a fixed total CPU/RAM budget, then a growing-resource series.
scale-cost:
	$(PYTHON) scripts/scale_cost.py --base-url "$(BASE_URL)"
