## PEChub – Developer Commands

.PHONY: dev down build test migrate seed lint format clean logs ps help

# Variabili
COMPOSE = docker compose
BACKEND = $(COMPOSE) exec backend
PYTEST   = $(BACKEND) python -m pytest

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

# ─── Stack locale ────────────────────────────────────────────────────────────

dev:  ## Avvia l'intero stack in background
	$(COMPOSE) up -d --build
	@echo ""
	@echo "  ✅  Stack avviato:"
	@echo "  🌐  Frontend: http://localhost         (interfaccia utente)"
	@echo "  📡  API:      http://localhost/api/v1  (via Nginx)"
	@echo "  📖  Docs:     http://localhost/docs    (Swagger UI)"
	@echo "  🔧  Backend:  http://localhost:8000    (diretto)"
	@echo "  🗄️   MinIO:    http://localhost:9001    (minioadmin/minioadmin)"
	@echo ""

down:  ## Ferma e rimuove i container (preserva i volumi)
	$(COMPOSE) down

down-v:  ## Ferma e rimuove TUTTO inclusi i volumi (reset completo)
	$(COMPOSE) down -v

build:  ## Rebuilda le immagini senza usare la cache
	$(COMPOSE) build --no-cache

logs:  ## Segui i log di tutti i servizi
	$(COMPOSE) logs -f

logs-backend:  ## Segui i log del backend
	$(COMPOSE) logs -f backend

logs-worker:  ## Segui i log del worker IMAP
	$(COMPOSE) logs -f worker

logs-frontend:  ## Segui i log del frontend Vite
	$(COMPOSE) logs -f frontend

# ─── Frontend ─────────────────────────────────────────────────────────────────

FRONTEND = $(COMPOSE) exec frontend

frontend-install:  ## Installa dipendenze npm nel container
	$(FRONTEND) npm install

frontend-build:  ## Build di produzione del frontend
	$(FRONTEND) npm run build

frontend-typecheck:  ## Controlla i tipi TypeScript
	$(FRONTEND) npm run type-check

shell-frontend:  ## Shell nel container frontend
	$(FRONTEND) sh

ps:  ## Stato dei container
	$(COMPOSE) ps

# ─── Database ────────────────────────────────────────────────────────────────

migrate:  ## Esegui le migrazioni Alembic pendenti
	$(BACKEND) alembic upgrade head

migrate-down:  ## Rollback dell'ultima migrazione
	$(BACKEND) alembic downgrade -1

migrate-status:  ## Stato migrazioni
	$(BACKEND) alembic current

makemigration:  ## Genera una nuova migrazione (usa: make makemigration MSG="descrizione")
	$(BACKEND) alembic revision --autogenerate -m "$(MSG)"

seed:  ## Esegui seed dati di sviluppo (tenant demo + admin)
	$(COMPOSE) exec db psql -U pechub -d pechub -f /docker-entrypoint-initdb.d/seeds/dev_tenant.sql
	@echo "  ✅  Seed completato"

reset-db:  ## Reset completo DB (down-v + dev + migrate + seed)
	$(MAKE) down-v
	$(MAKE) dev
	@sleep 5
	$(MAKE) migrate
	$(MAKE) seed

# ─── Test ────────────────────────────────────────────────────────────────────

test:  ## Esegui tutti i test (unit + integration)
	$(PYTEST) -v --tb=short

test-unit:  ## Solo unit test
	$(PYTEST) backend/tests/unit -v

test-integration:  ## Solo integration test
	$(PYTEST) backend/tests/integration -v

test-cov:  ## Test con coverage report
	$(PYTEST) --cov=app --cov-report=term-missing --cov-report=html:/app/htmlcov -v

# ─── Worker ──────────────────────────────────────────────────────────────────

WORKER = $(COMPOSE) exec worker
PYTEST_WORKER = $(WORKER) python -m pytest

test-worker:  ## Esegui tutti i test del worker
	$(PYTEST_WORKER) -v --tb=short

test-worker-unit:  ## Solo unit test del worker (no infra richiesta)
	$(PYTEST_WORKER) tests/unit -v

test-imap:  ## Test integrazione IMAP con GreenMail (avvia GreenMail prima)
	$(PYTEST_WORKER) tests/integration -v

greenmail-up:  ## Avvia GreenMail (server IMAP/SMTP mock per test)
	$(COMPOSE) --profile greenmail up -d greenmail
	@echo "  ✅  GreenMail avviato:"
	@echo "  📬  IMAP: localhost:3143"
	@echo "  📨  SMTP: localhost:3025"
	@echo "  🌐  API:  http://localhost:8080"

greenmail-down:  ## Ferma GreenMail
	$(COMPOSE) --profile greenmail stop greenmail

shell-worker:  ## Shell nel container worker
	$(WORKER) bash

worker-health:  ## Verifica health del worker (tramite arq job)
	$(WORKER) python -c "import asyncio; from arq import create_pool; from arq.connections import RedisSettings; \
	    async def main(): pool = await create_pool(RedisSettings()); r = await pool.enqueue_job('health_check'); print(await r.result(timeout=10)); \
	    asyncio.run(main())"

# ─── Code quality ─────────────────────────────────────────────────────────────

lint:  ## Esegui linting (ruff + mypy)
	$(BACKEND) ruff check app tests
	$(BACKEND) mypy app --ignore-missing-imports

format:  ## Formatta il codice con ruff
	$(BACKEND) ruff format app tests
	$(BACKEND) ruff check --fix app tests

# ─── Utility ─────────────────────────────────────────────────────────────────

shell-backend:  ## Shell nel container backend
	$(BACKEND) bash

shell-db:  ## psql nel container database
	$(COMPOSE) exec db psql -U pechub -d pechub

clean:  ## Rimuovi file temporanei Python
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
	find . -name "*.pyc" -delete 2>/dev/null || true
	find . -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
	find . -name ".mypy_cache" -exec rm -rf {} + 2>/dev/null || true
	find . -name "htmlcov" -exec rm -rf {} + 2>/dev/null || true
