.PHONY: openapi gen check-gen check-breaking check-contract baseline test lint all dist-bundle publish-check publish-test publish

# Kit self-test fixture (not a consumer example app). Real dogfood: ../ticket-desk-api
OPENAPI_APP ?= tests.fixtures.minimal_api.export_openapi:get_openapi
OPENAPI_OUT ?= docs/api/generated/openapi.json
BASELINE_OUT ?= docs/api/baselines/openapi.json
SETTINGS_TARGET ?= tests.fixtures.minimal_api.settings:Settings
ERRORS_TARGET ?= tests.fixtures.minimal_api.errors:ERROR_CODES
VERSION := $(shell python3 -c "import pathlib,re; t=pathlib.Path('pyproject.toml').read_text(); print(re.search(r'^version\s*=\s*\"([^\"]+)\"', t, re.M).group(1))")

ifeq ($(shell command -v uv >/dev/null 2>&1 && echo yes),yes)
PYTHON = uv run python
SSOT = uv run ssotkit
PYTEST = uv run pytest
RUFF = uv run ruff
else ifneq ($(wildcard .venv/bin/python),)
PYTHON = .venv/bin/python
SSOT = .venv/bin/python -m ssotkit
PYTEST = .venv/bin/pytest
RUFF = .venv/bin/ruff
else
PYTHON = python3
SSOT = python3 -m ssotkit
PYTEST = pytest
RUFF = ruff
endif

openapi:
	$(SSOT) openapi --app $(OPENAPI_APP) --out $(OPENAPI_OUT)

gen: openapi
	$(SSOT) gen --openapi $(OPENAPI_OUT) --settings $(SETTINGS_TARGET) --errors $(ERRORS_TARGET)

check-gen:
	$(SSOT) check-gen --openapi-app $(OPENAPI_APP) --settings $(SETTINGS_TARGET) --errors $(ERRORS_TARGET)

check-breaking:
	$(SSOT) check-breaking --baseline $(BASELINE_OUT) --current $(OPENAPI_OUT)

check-contract:
	$(SSOT) check-contract --current $(OPENAPI_OUT)

baseline: openapi
	mkdir -p $(dir $(BASELINE_OUT))
	cp $(OPENAPI_OUT) $(BASELINE_OUT)
	@echo "wrote $(BASELINE_OUT)"

test:
	$(PYTEST)

lint:
	$(RUFF) check src tests

all: lint test check-gen check-contract check-breaking

dist-bundle:
	rm -rf dist/bundle
	mkdir -p dist/bundle
	$(PYTHON) -m build --wheel -o dist/bundle
	mkdir -p dist/bundle/skills
	cp -a skills/fastapi-ssot dist/bundle/skills/
	printf '%s\n' \
	  '# 接入' \
	  '' \
	  '见 `skills/fastapi-ssot/SKILL.md`（「首次接入」）与 `references/bootstrap-project.md`。' \
	  '' \
	  '```bash' \
	  'pip install ./ssotkit-*.whl' \
	  'cp -a skills/fastapi-ssot <repo>/.cursor/skills/fastapi-ssot' \
	  '```' \
	  > dist/bundle/INSTALL.md
	cd dist/bundle && zip -r ../fastapi-ssot-kit-$(VERSION)-bundle.zip .
	@echo "wrote dist/fastapi-ssot-kit-$(VERSION)-bundle.zip"

# PyPI publish (build + twine). Auth: TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-... or ~/.pypirc
publish-check:
	bash scripts/publish_pypi.sh check

publish-test:
	bash scripts/publish_pypi.sh test

publish:
	bash scripts/publish_pypi.sh prod
