.DEFAULT_GOAL := help
SHELL := /bin/bash

UV      := $(shell command -v uv 2>/dev/null)
COMPOSE := docker compose -f deploy/docker-compose.dev.yml

ifdef UV
  RUN := uv run
else
  RUN := .venv/bin/python -m
endif

.PHONY: help install lint fmt typecheck importlint test test-unit migrate makemigration up down dev worker smoke secrets clean

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

install: ## Create the venv and install runtime + dev dependencies
ifdef UV
	uv sync --extra dev
	uv run pre-commit install || true
else
	python3 -m venv .venv
	.venv/bin/pip install --upgrade pip
	.venv/bin/pip install -e ".[dev]"
	.venv/bin/pre-commit install || true
endif

lint: ## ruff check + ruff format --check
	uv run ruff check .
	uv run ruff format --check .

fmt: ## Auto-fix lint issues and format
	uv run ruff check --fix .
	uv run ruff format .

typecheck: ## mypy strict on packages/domain + packages/llm, normal elsewhere (§16.2)
	uv run mypy packages/domain packages/llm
	uv run mypy apps packages/shared packages/identity packages/billing packages/task packages/agent packages/compliance

importlint: ## Enforce the dependency rules of 架构文档 §4.2
	uv run lint-imports

test: lint typecheck importlint test-unit ## Full local quality gate (mirrors CI)

test-unit: ## pytest with coverage
	uv run pytest

secrets: ## Scan the working tree for committed credentials
	uv run detect-secrets scan --baseline .secrets.baseline

migrate: ## Apply Alembic migrations to $$DATABASE_URL
	uv run alembic upgrade head

makemigration: ## Autogenerate a migration: make makemigration m="add xxx"
	uv run alembic revision --autogenerate -m "$(m)"

up: ## Start PostgreSQL(pgvector) + Redis for local development
	$(COMPOSE) up -d postgres redis
	$(COMPOSE) ps

down: ## Stop the local stack (keeps volumes)
	$(COMPOSE) down

dev: ## Run the API with autoreload
	uv run uvicorn apps.api.main:app --host 0.0.0.0 --port 8000 --reload

worker: ## Run a Celery worker consuming the cpu/io queues
	uv run celery -A apps.worker.celery_app.celery_app worker -Q cpu,io -l info

smoke: ## End-to-end proof: compose + migrate + API + real DeepSeek call
	bash scripts/smoke.sh

clean: ## Remove caches and build artefacts
	rm -rf .pytest_cache .mypy_cache .ruff_cache .coverage htmlcov dist build
	find . -type d -name __pycache__ -prune -exec rm -rf {} +
