.PHONY: help install dev migrate revision seed test test-unit test-e2e lint fmt up down logs harden dev-up dev-db setup deploy status

help:
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-14s\033[0m %s\n", $$1, $$2}'

install:  ## Install runtime + dev dependencies
	pip install -e ".[dev]"

dev:  ## Run the API with auto-reload
	uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

migrate:  ## Apply all migrations
	alembic upgrade head

revision:  ## Autogenerate a migration:  make revision m="add product table"
	alembic revision --autogenerate -m "$(m)"

seed:  ## Seed the minimum MVP system (1 company, 1 HQ, GM/AM/MR, 15 doctors, 5 chemists)
	python -m scripts.seed

test:  ## Run the whole suite (needs Postgres)
	pytest -q

test-unit:  ## State machine and pure logic only — no database needed
	pytest tests/unit -q

test-e2e:  ## The 13-step acceptance test plus the negative-scope tests
	pytest tests/e2e -q

lint:  ## Check style
	ruff check app tests

fmt:  ## Fix style
	ruff check --fix app tests && ruff format app tests

setup:  ## Create/refresh .env for this machine (secrets, free ports) — safe to re-run
	./scripts/setup.sh

deploy: setup  ## setup + build + start + wait until the API is healthy
	docker compose up -d --build
	@for i in $$(seq 1 30); do \
	  docker compose exec -T api curl -fsS http://localhost:8000/health >/dev/null 2>&1 && \
	    { echo "API healthy"; $(MAKE) --no-print-directory status; exit 0; }; sleep 2; done; \
	  echo "API did not become healthy: docker compose logs api"; exit 1

status:  ## Show containers and the URL the site answers on
	@docker compose ps --format 'table {{.Name}}\t{{.Status}}\t{{.Ports}}'
	@echo "site: http://localhost:$$(grep -E '^HTTP_PORT=' .env 2>/dev/null | cut -d= -f2 | grep . || echo 80)"

up:  ## Start the production stack (needs .env — see .env.example)
	docker compose up -d --build

dev-up:  ## Start the whole stack with DB and API published on localhost
	docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build

dev-db:  ## Start only PostgreSQL on localhost (host-run API and tests)
	docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d db

down:  ## Stop the stack
	docker compose down

logs:  ## Tail API logs
	docker compose logs -f api

harden:  ## Apply the append-only audit-log grants (run once, as superuser)
	psql "$${ADMIN_DATABASE_URL:?set ADMIN_DATABASE_URL}" -f scripts/harden_audit.sql
