.PHONY: help serve stop dev scan test lint fix build install clean info

PID_FILE := .tokburn.pid
PORT     := 8391

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

# ── Server ────────────────────────────────────────────────────────────────────

serve: ## Start dashboard server in background (http://localhost:8391)
	@if [ -f $(PID_FILE) ] && kill -0 $$(cat $(PID_FILE)) 2>/dev/null; then \
		echo "  Server already running (PID $$(cat $(PID_FILE))) — use 'make stop' first"; \
	else \
		uv run tokburn serve --no-open & echo $$! > $(PID_FILE); \
		sleep 0.5 && echo "  Server started → http://127.0.0.1:$(PORT)  (PID $$(cat $(PID_FILE)))"; \
	fi

stop: ## Stop the background server
	@if [ -f $(PID_FILE) ]; then \
		kill $$(cat $(PID_FILE)) 2>/dev/null && echo "  Server stopped" || echo "  Process not found"; \
		rm -f $(PID_FILE); \
	else \
		echo "  No PID file — server may not be running"; \
	fi

dev: ## Start server in foreground with verbose logging (Ctrl+C to stop)
	uv run tokburn serve -v

scan: ## Quick CLI scan of sessions without starting the server
	uv run tokburn scan

# ── Quality ───────────────────────────────────────────────────────────────────

test: ## Run the full test suite
	uv run pytest tests/ -v

lint: ## Check code style (ruff)
	uv run ruff check src/ tests/
	uv run ruff format --check src/ tests/

fix: ## Auto-fix lint and format issues
	uv run ruff check --fix src/ tests/
	uv run ruff format src/ tests/

# ── Distribution ─────────────────────────────────────────────────────────────

build: ## Build distribution packages
	uv build

install: ## Install in development mode
	uv sync --dev

clean: ## Remove build artifacts, caches, and PID file
	rm -rf dist/ build/ *.egg-info .pytest_cache __pycache__ $(PID_FILE)
	find . -type d -name __pycache__ -exec rm -rf {} +

# ── Info ──────────────────────────────────────────────────────────────────────

info: ## Display project README in terminal
	@cat README.md
