.DEFAULT_GOAL := build

UV ?= uv
NPM ?= npm
PYTHON_VERSION := $(shell cat .python-version)
UV_DIR := $(CURDIR)/.uv
export UV_CACHE_DIR := $(UV_DIR)/cache
export UV_PYTHON_INSTALL_DIR := $(UV_DIR)/python
export UV_PROJECT_ENVIRONMENT := $(UV_DIR)/dev
export UV_MANAGED_PYTHON := true
export npm_config_cache := $(CURDIR)/.tools/npm-cache
unexport VIRTUAL_ENV

PORT ?= 7081
HOST ?= 0.0.0.0
TEST_HOST ?= 127.0.0.1

.PHONY: python wiki-deps build run test check

python:
	$(UV) python install --no-bin $(PYTHON_VERSION)
	$(UV) python find --managed-python --system $(PYTHON_VERSION) > .uv/python-path
	@case "$$(cat .uv/python-path)" in "$(UV_PYTHON_INSTALL_DIR)"/*) ;; *) echo "Expected a project-local Python under .uv/python" >&2; exit 1 ;; esac

wiki-deps: node_modules/.package-lock.json

node_modules/.package-lock.json: package.json package-lock.json
	$(NPM) ci --no-audit --no-fund

build: python wiki-deps
	$(UV) build --python "$$(cat .uv/python-path)" --out-dir build
	$(UV) export --frozen --no-dev --no-emit-project --output-file build/requirements.txt
	$(UV) venv --allow-existing --python "$$(cat .uv/python-path)" .uv/venv
	$(UV) pip uninstall --python .uv/venv/bin/python agent-mcp
	$(UV) pip install --python .uv/venv/bin/python --reinstall-package agent-host-mcp -r build/requirements.txt $$(ls -t build/agent_host_mcp-*.whl | head -n 1)
	cp scripts/agent-host-mcp build/agent-host-mcp
	chmod +x build/agent-host-mcp
	./.uv/venv/bin/python -m agent_mcp.catalog build/tool-catalog.json

run: build
	./build/agent-host-mcp --port $(PORT) --host $(HOST)

test:
	./.uv/venv/bin/python scripts/test_mcp.py http://$(TEST_HOST):$(PORT)/mcp

check: python wiki-deps
	$(UV) run --frozen --python "$$(cat .uv/python-path)" pytest -q

