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)

.PHONY: secrets up down ps unit worker-stop worker-start ops track1

secrets:
	$(PYTHON) scripts/init_secrets.py

up: secrets
	docker compose --env-file .env up -d --build --wait

down:
	docker compose stop

ps:
	docker compose ps -a

unit:
	docker run --rm -v "$(CURDIR)/src:/src" -w /src golang:1.23.4-alpine3.21 go test ./...

worker-stop:
	docker compose stop worker

worker-start:
	docker compose start worker

ops:
	$(PYTHON) scripts/lab5ops.py worker-down  --output evidence/worker-down.json
	$(PYTHON) scripts/lab5ops.py api-crash    --output evidence/api-crash.json
	$(PYTHON) scripts/lab5ops.py effect-crash --output evidence/effect-crash.json
	$(PYTHON) scripts/lab5ops.py ack-crash    --output evidence/ack-crash.json
	$(PYTHON) scripts/lab5ops.py retry        --output evidence/retry.json
	$(PYTHON) scripts/lab5ops.py replay       --output evidence/replay.json
	$(PYTHON) scripts/lab5ops.py invalid      --output evidence/invalid.json
	$(PYTHON) scripts/lab5ops.py hang         --output evidence/hang.json
	$(PYTHON) scripts/lab5ops.py dlq          --output evidence/dlq.json
	$(PYTHON) scripts/lab5ops.py limits       --output evidence/limits.json

track1:
	$(PYTHON) scripts/track1/run_track1.py matrix       --output evidence/track1/matrix.json
	$(PYTHON) scripts/track1/run_track1.py backpressure --output evidence/track1/backpressure.json
