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

TEST_DATABASE_URL ?= $(shell sed -e 's|@postgres:|@localhost:|' -e 's|/messenger$$|/messenger_test|' secrets/database_url 2>/dev/null)
export TEST_DATABASE_URL

.PHONY: help check validate test load test-persistence \
        secrets up down logs db-up migrate migration \
        test-own test-limits test-concurrency test-migrations

help:
	@echo "Курс:  check | validate | test (smoke по BASE_URL) | load | test-persistence ACTION_SCRIPT=scripts/restart.sh"
	@echo "Стенд: secrets | up | down | logs | db-up (только PostgreSQL + тестовая БД) | migrate"
	@echo "Свои:  test-own | test-limits | test-concurrency | test-migrations | migration m='описание'"

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)

secrets:
	sh scripts/init-secrets.sh

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

down:
	docker compose down          # без -v: volumes с данными сохраняются

logs:
	docker compose logs -f api

db-up:
	docker compose up -d --wait postgres
	docker compose exec -T postgres sh -c \
	  "psql -U messenger -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='messenger_test'\" | grep -q 1 || createdb -U messenger messenger_test"

migrate:
	docker compose run --rm migrate

migration:
	$(PYTHON) -m alembic revision --autogenerate -m "$(m)"

test-own:
	$(PYTHON) -m pytest tests -q

test-limits:
	$(PYTHON) -m pytest tests/test_limits.py -q

test-concurrency:
	$(PYTHON) -m pytest tests/test_concurrency.py -q

test-migrations:
	$(PYTHON) -m pytest tests/test_migrations.py -q
