SHELL := /usr/bin/env bash
.PHONY: help test tests tsc lint seed seed-clean start status stop restart install clean

VENV := .venv
PY := $(VENV)/bin/python
PIP := $(VENV)/bin/pip
NPX := npx
FRONTEND_DIR := frontend/asf-web
SCRIPTS_DIR := scripts

default: help

help:
	@echo ""
	@echo "ASF — Makefile"
	@echo "═══════════════════════════════════════════"
	@echo "  test / tests       → pytest tutte le suite (5 packages/services)"
	@echo "  tsc                → TypeScript strict no-emit check (asf-web)"
	@echo "  lint               → alias per: test + tsc (tutto)"
	@echo ""
	@echo "  seed               → demo seed (append idempotente)"
	@echo "  seed-clean         → demo seed PULITO (DELETE artifacts + CANCEL jobs prima)"
	@echo ""
	@echo "  start              → avvia stack (core 8000 + web 3000)"
	@echo "  status             → PID / porte / health / log tail"
	@echo "  stop               → SIGTERM stack (poi SIGKILL se rifiuta)"
	@echo "  restart            → stop + start"
	@echo ""
	@echo "  install            → pip install (asf-domain/asf-core/worker/ai/context) + npm i"
	@echo "  clean              → pytest_cache, __pycache__, node_modules/.cache"
	@echo ""

test tests:
	@set -e; \
	echo "▶ pytest asf-domain"; cd packages/asf-domain   && PYTHONPATH=".:$$PYTHONPATH" ../../$(PY) -m pytest tests -q; cd ../..; \
	echo "▶ pytest asf-core";   cd services/asf-core   && PYTHONPATH=".:$$PYTHONPATH" ../../$(PY) -m pytest tests -q; cd ../..; \
	echo "▶ pytest asf-worker"; cd services/asf-worker && PYTHONPATH=".:$$PYTHONPATH" ../../$(PY) -m pytest tests -q; cd ../..; \
	echo "▶ pytest asf-ai";     cd services/asf-ai     && PYTHONPATH=".:$$PYTHONPATH" ../../$(PY) -m pytest tests -q; cd ../..; \
	echo "▶ pytest asf-context";cd services/asf-context&& PYTHONPATH=".:$$PYTHONPATH" ../../$(PY) -m pytest tests -q; cd ../..; \
	echo "✅ Tutte le suite PASSATE"

tsc:
	cd $(FRONTEND_DIR) && $(NPX) tsc --noEmit
	@echo "✅ tsc 0 errors"

lint: test tsc
	@echo "✅ lint = test + tsc completato"

seed:
	bash $(SCRIPTS_DIR)/seed-demo.sh

seed-clean:
	bash $(SCRIPTS_DIR)/seed-demo.sh --clean --jobs

start:
	bash $(SCRIPTS_DIR)/start-stack.sh --with-worker

status:
	bash $(SCRIPTS_DIR)/status-stack.sh

stop:
	bash $(SCRIPTS_DIR)/stop-stack.sh

restart: stop start

install:
	@echo "▶ pip install -e packages/asf-domain services/asf-core services/asf-worker services/asf-ai services/asf-context"
	@$(PIP) install -e packages/asf-domain -e services/asf-core -e services/asf-worker -e services/asf-ai -e services/asf-context
	@echo "▶ npm install (asf-web)"
	@cd $(FRONTEND_DIR) && npm install

clean:
	find . -type d -name __pycache__ -prune -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name ".pytest_cache" -prune -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name ".next" -prune -exec rm -rf {} + 2>/dev/null || true
	rm -f .coverage .coverage.*
	@echo "🧹 cache puliti"
