PYTHON ?= .venv/bin/python
BASE_URL ?= http://localhost:18085
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: setup up down build restore-api stop-worker start-worker replay reconcile
setup:
	python3 -m venv .venv
	.venv/bin/python -m pip install -r requirements-dev.txt -r requirements-student.txt -r requirements-research.txt
	./scripts/init-secrets.sh
up:
	./scripts/init-secrets.sh
	./scripts/compose.sh build api
	./scripts/compose.sh up -d --wait --wait-timeout 150
build:
	dotnet build src/Messenger.Api
restore-api:
	./scripts/compose.sh up -d --wait api lb
stop-worker:
	./scripts/compose.sh stop worker
start-worker:
	./scripts/compose.sh up -d worker
replay:
	@test -n "$(JOB_ID)" || (echo "Set JOB_ID"; exit 2)
	./scripts/compose.sh exec -T dispatcher dotnet Messenger.Api.dll --replay "$(JOB_ID)"
reconcile:
	./scripts/compose.sh exec -T dispatcher dotnet Messenger.Api.dll --reconcile
down:
	./scripts/compose.sh down

.PHONY: student-test
student-test:
	$(PYTHON) student-tests/pipeline_tests.py --base-url "$(BASE_URL)"

.PHONY: research-grade5
research-grade5:
	$(PYTHON) student-tests/overload_research.py --base-url "$(BASE_URL)"
	$(PYTHON) scripts/plot_overload.py

.PHONY: share stop-share operations-test
share:
	python3 scripts/share.py
stop-share:
	python3 scripts/share.py --stop
operations-test:
	$(PYTHON) student-tests/operations_panel.py

.PHONY: operator
operator:
	python3 scripts/configure-operator.py "$(USERNAME)"
