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

.PHONY: help install db-up db-down migrate backend-dev web-dev contract check-fast check test build

help: ## List repository commands
	@grep -E '^[a-zA-Z_-]+:.*## ' $(MAKEFILE_LIST) | sort | awk -F ':.*## ' '{printf "%-16s %s\n", $$1, $$2}'

install: ## Sync project-local dependencies from both lockfiles
	uv sync --locked --all-groups
	cd apps/web && bun install --frozen-lockfile

db-up: ## Start only the new local PostgreSQL volume
	docker compose up -d postgres

db-down: ## Stop local services without deleting the database
	docker compose down

migrate: ## Apply migrations to the configured database
	uv run --no-sync alembic upgrade head

backend-dev: ## Run a single backend process bound to localhost
	uv run --no-sync uvicorn ai_platform.main:app --reload --host 127.0.0.1 --port 8000

web-dev: ## Run SvelteKit bound to localhost
	cd apps/web && bun run dev -- --host 127.0.0.1

contract: ## Generate the backend OpenAPI consumed by Admin Web
	uv run --no-sync ai-platform export-openapi contracts/lead-scoring/v2/openapi.json

check-fast: ## Check staged/all tracked source with opt-in pre-commit rules
	uv run --no-sync pre-commit run --all-files

test: ## Run backend tests only on the isolated test database
	@set -a; if [ -f .env.test ] && [ -z "$$CI" ]; then . ./.env.test; fi; set +a; \
	python -c 'from urllib.parse import urlsplit; import os,sys; url=os.environ.get("AI_PLATFORM_DATABASE_URL", ""); sys.exit(urlsplit(url).path.rstrip("/").split("/")[-1] != "ai_platform_test")' || { echo "Test URL must end in /ai_platform_test." >&2; exit 2; }; \
	uv run --no-sync pytest

check: check-fast contract ## Run backend and web checks used by CI
	uv run --no-sync ruff check src tests
	uv run --no-sync ruff format --check src tests
	uv run --no-sync pyright
	uv run --no-sync lint-imports
	$(MAKE) test
	cd apps/web && bun run format:check && bun run check && bun run test && bun run build

build: ## Build both images; does not deploy them
	docker build -f Dockerfile.backend -t ai-platform-backend:local .
	docker build -f apps/web/Dockerfile -t ai-platform-web:local .
