# mcadb container management. Mode comes from COMPOSE_PROFILES in .env.
SHELL := /bin/bash
-include .env
MCADB_PORT ?= 8475
IMAGE ?= mcadb:$(or $(MCADB_IMAGE_TAG),local)
UV_IMAGE ?= ghcr.io/astral-sh/uv:0.13.9-python3.13-trixie-slim

.PHONY: help env build up down restart logs ps dev health smoke shell \
        mcp-add-http mcp-add-stdio buildx verify-uv test lint

help: ## Show targets
	@grep -hE '^[a-zA-Z_-]+:.*## ' Makefile | awk 'BEGIN{FS=":.*## "}{printf "  %-15s %s\n",$$1,$$2}'

env: ## Create .env from .env.example (with your uid/gid) if missing
	@test -f .env || { cp .env.example .env && \
	  sed -i "s/^MCADB_UID=.*/MCADB_UID=$$(id -u)/; s/^MCADB_GID=.*/MCADB_GID=$$(id -g)/" .env && \
	  echo "created .env"; }

build: env ## Build images for the current profile
	docker compose build

up: env ## Start (profile from .env) and show logs briefly
	docker compose up -d --build
	@sleep 3; docker compose logs --tail=20

down: ## Stop and remove containers
	docker compose down

restart: down up ## Restart

logs: ## Follow logs
	docker compose logs -f

ps: ## Container status (with health)
	docker compose ps

dev: env ## Live-reload dev container: src/ syncs in, restarts on change
	COMPOSE_PROFILES=dev docker compose up --build --watch

health: ## Query the running server's /health
	@curl -fsS http://127.0.0.1:$(MCADB_PORT)/health && echo

smoke: ## Run the runtime image over stdio and complete an MCP initialize
	docker build -q --target runtime -t $(IMAGE) . >/dev/null
	@printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}' \
	  | timeout 30 docker run -i --rm --network host $(IMAGE) 2>/dev/null \
	  | head -c 200 | grep -q '"protocolVersion"' && echo "smoke: OK (stdio initialize answered)"

shell: ## Shell in the running container
	docker compose exec $$(docker compose ps --services | head -1) sh

mcp-add-http: ## Print the claude mcp add command for the HTTP server
	@echo "claude mcp add --transport http mcadb-docker http://127.0.0.1:$(MCADB_PORT)/mcp"

mcp-add-stdio: ## Print the claude mcp add command for a per-session stdio container
	@echo "claude mcp add mcadb-docker -- docker run -i --rm --network host $(IMAGE)"

buildx: ## Multi-platform build (amd64 + arm64), no push
	docker buildx build --platform linux/amd64,linux/arm64 --target runtime -t $(IMAGE) .

verify-uv: ## Verify the pinned uv image's provenance (needs gh auth)
	gh attestation verify oci://$(UV_IMAGE) --owner astral-sh

test: ## Run the test suite on the host
	uv run pytest -q

lint: ## ruff check + format check
	uv run ruff check src tests && uv run ruff format --check src tests
