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

ENV_FILE ?= .env
-include $(ENV_FILE)
IMAGE ?= mtusi-messenger:lab2
CONTAINER ?= mtusi-messenger-lab2
PUBLISH ?= 127.0.0.1:$(APP_PORT):$(APP_PORT)
READY_TIMEOUT_SEC ?= 30
POETRY ?= poetry

.PHONY: help check validate test load test-persistence install build run wait-ready stop restart logs student-test concurrency-test sigterm-check up_local down_local

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "install: dev venv; build/run/stop/restart/logs: container; up_local/down_local: docker compose; student-test: own tests; concurrency-test, sigterm-check: evidence"

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)

install:
	$(POETRY) install --no-root

build:
	docker build -t $(IMAGE) .

run:
	docker run --rm -d --name $(CONTAINER) -p $(PUBLISH) --env-file $(ENV_FILE) $(IMAGE)
	@$(MAKE) --no-print-directory wait-ready

wait-ready:
	@for i in $$(seq 1 $(READY_TIMEOUT_SEC)); do \
		curl -fsS "$(BASE_URL)/health/ready" >/dev/null 2>&1 && echo "ready: $(BASE_URL)" && exit 0; \
		sleep 1; \
	done; echo "API is not ready after $(READY_TIMEOUT_SEC)s"; exit 1

stop:
	docker stop $(CONTAINER)

restart:
	docker restart $(CONTAINER)
	@$(MAKE) --no-print-directory wait-ready

logs:
	docker logs -f $(CONTAINER)

student-test:
	BASE_URL="$(BASE_URL)" $(POETRY) run pytest

concurrency-test:
	BASE_URL="$(BASE_URL)" $(POETRY) run pytest student-tests/test_concurrency.py -s

sigterm-check:
	CONTAINER="$(CONTAINER)" $(PYTHON) scripts/sigterm_check.py --base-url "$(BASE_URL)"

up_local:
	docker compose -f docker-compose-local.yaml up --build -d

down_local:
	docker compose -f docker-compose-local.yaml down
