PYTHON ?= python3
GO ?= go
BASE_URL ?= http://localhost:8080
CA_FILE ?=
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
COMPOSE ?= ./scripts/compose.sh
IMAGE ?= mtusi-messenger-lab2-melnikov:1.0.0
COMPOSE_ARGS = --env-file .env

.PHONY: help check validate test load test-persistence env up wait build-image docker-config stop down purge logs \
        test-student test-student-race test-expiry test-failure test-container test-db track5

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
	@echo "env: create ignored .env with random local credentials; up: build+start stack; wait: wait for /health/ready"
	@echo "stop: stop containers (data kept); down: remove containers (volumes kept); purge: DELETE volumes and data"
	@echo "test-student: Go unit tests + black-box suite; test-student-race: Go race detector"
	@echo "test-expiry: short-TTL session + API-restart scenario; test-failure: DB/Valkey outage scenarios"
	@echo "test-container: container/volume/health checks; test-db: SQL constraints, migrations and EXPLAIN; track5: level-5 track 2"

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)

env:
	./scripts/init-env.sh

up:
	$(COMPOSE) $(COMPOSE_ARGS) up -d --build
	./scripts/wait-ready.sh

wait:
	./scripts/wait-ready.sh

build-image:
	$(COMPOSE) $(COMPOSE_ARGS) build api

docker-config:
	$(COMPOSE) $(COMPOSE_ARGS) config --quiet

stop:
	$(COMPOSE) $(COMPOSE_ARGS) stop

down:
	$(COMPOSE) $(COMPOSE_ARGS) down

purge:
	@echo "PURGE removes containers AND named volumes mtusi-lab2-melnikov-*: all synthetic data is lost."
	$(COMPOSE) $(COMPOSE_ARGS) down -v

logs:
	$(COMPOSE) $(COMPOSE_ARGS) logs --tail=100 api

test-student:
	$(GO) test -count=1 ./...
	$(PYTHON) student-tests/blackbox.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-student-race:
	$(GO) test -race -count=1 ./...

test-expiry:
	SESSION_TTL_SECONDS=15 $(COMPOSE) $(COMPOSE_ARGS) up -d --no-deps --force-recreate api
	./scripts/wait-ready.sh
	$(PYTHON) scripts/expiry-check.py --base-url "$(BASE_URL)" $(TLS_ARGS) --restart-api
	$(COMPOSE) $(COMPOSE_ARGS) up -d --no-deps --force-recreate api
	./scripts/wait-ready.sh

test-failure:
	$(PYTHON) scripts/failure-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-container:
	$(PYTHON) scripts/container-checks.py --base-url "$(BASE_URL)" $(TLS_ARGS) --image "$(IMAGE)"

test-db:
	$(PYTHON) scripts/db-checks.py

track5:
	$(PYTHON) scripts/track5.py
