VENV := .venv/bin
POLICY_AI_DIR := ../policy-ai
POLICYAI_URL ?= https://api.musubilabs.ai/policyai/openapi.json
ORCHESTRATOR_URL ?= https://api.musubilabs.ai/api/openapi.json

.PHONY: specs fetch-policyai fetch-orchestrator extract-spec fetch-spec \
	install test lint format clean

## Refresh both API contracts from the public OpenAPI URLs, then check the
## client still matches them.
##
## There is no code generation. The SDK is hand-written: resources build paths
## and dicts directly (src/musubi/resources/), on top of the hand-rolled
## transport in src/musubi/_http.py. The checked-in *-openapi.json files ARE the
## contract — review their diff when an API moves, and let
## tests/test_spec_conformance.py tell you whether the client broke.
specs: fetch-policyai fetch-orchestrator
	$(VENV)/pytest tests/test_spec_conformance.py -q

fetch-policyai:
	$(MAKE) fetch-spec SPEC=policyai URL=$(POLICYAI_URL)

fetch-orchestrator:
	$(MAKE) fetch-spec SPEC=orchestrator URL=$(ORCHESTRATOR_URL)

## Fetch one spec from its URL into $(SPEC)-openapi.json, pretty-printed.
## The gateway serves minified JSON. Normalising to indent=2 is what keeps the
## checked-in spec diffable — a one-line file makes "review the spec diff when
## the API moves" useless, and that diff is the whole point of committing it.
## --fail matters: without it curl writes a 404/503 error page over the spec and
## exits 0, silently replacing the contract the whole SDK is reviewed against.
## Fetch to a temp file and only move it into place once it parses as JSON.
fetch-spec:
	curl -sSL --fail $(URL) -o $(SPEC)-openapi.json.tmp
	python3 -c "import json; p='$(SPEC)-openapi.json.tmp'; s=json.load(open(p)); assert 'paths' in s, 'not an OpenAPI doc'; json.dump(s, open('$(SPEC)-openapi.json','w'), indent=2); open('$(SPEC)-openapi.json','a').write('\n')"
	rm -f $(SPEC)-openapi.json.tmp
	@echo "$(SPEC) OpenAPI spec version: $$(python3 -c "import json; print(json.load(open('$(SPEC)-openapi.json'))['info']['version'])")"

## Legacy: extract the policyai spec from a sibling policy-ai/ checkout, for
## internal devs who need a spec that isn't deployed yet. The orchestrator is
## URL-only.
extract-spec:
	cd $(POLICY_AI_DIR) && \
		DOCS_VIEW=deployed INCLUDE_OPENAPI_ENDPOINTS=true ENABLE_V2_FUNCTIONALITY=true \
		.venv/bin/python ../sdk/scripts/extract_openapi.py

## Install the SDK in editable mode with dev dependencies
install:
	$(VENV)/pip install -e ".[dev]"

## Run tests
test:
	$(VENV)/pytest tests/ -v

## Run linter
lint:
	$(VENV)/ruff check src/ tests/
	$(VENV)/ruff format --check src/ tests/

## Format code
format:
	$(VENV)/ruff check --fix src/ tests/
	$(VENV)/ruff format src/ tests/

clean:
	rm -f policyai-openapi.json orchestrator-openapi.json
