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

# Parse only the shared port; importing .env as Make syntax would misread secrets and JSON.
BACKEND_PORT ?= $(shell uv run --no-sync python -c 'from dotenv import dotenv_values; print(dotenv_values(".env").get("BACKEND_PORT") or "8000")')

.PHONY: help install dev 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

dev: ## Start PostgreSQL and run the native backend and web together
	$(MAKE) --jobs=2 backend-dev web-dev BACKEND_PORT=$(BACKEND_PORT)

db-up: ## Start local PostgreSQL and wait until ready
	docker compose up -d --wait 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: db-up ## Ensure PostgreSQL is ready, then run backend on the shared port
	uv run --no-sync uvicorn ai_platform.main:app --reload --host 127.0.0.1 --port $(BACKEND_PORT)

web-dev: ## Run SvelteKit with the shared backend address
	cd apps/web && BACKEND_INTERNAL_URL=http://127.0.0.1:$(BACKEND_PORT) 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/openapi.json
	uv run --no-sync python scripts/export_contract_fixtures.py

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 .
