.DEFAULT_GOAL := help
P ?= 100

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

install: ## Install production dependencies
	uv sync --no-dev

install-dev: ## Install development dependencies
	uv sync --all-extras

lint: ## Run ruff linter
	uv run ruff check .

format: ## Run ruff formatter
	uv run ruff format .

test: test-unit test-compat ## Run all tests (unit + SDK compat)

test-unit: ## Run unit tests (current SDK versions)
	uv run pytest tests/

test-sample: ## Run random P% of unit tests (e.g. make test-sample P=10)
	uv run pytest tests/ --sample-percentage=$(P)

cli-install: ## Install package in editable mode
	uv pip install -e .

# SDK compatibility — versions come from compat.yaml
COMPAT_VERSIONS = uv run python -c "import yaml; print(' '.join(yaml.safe_load(open('compat.yaml'))['$(1)']['versions']))"
COMPAT_TEST_FILE = uv run python -c "import yaml; print(yaml.safe_load(open('compat.yaml'))['$(1)']['test_file'])"

define run-compat
	@VERSIONS=$$($(call COMPAT_VERSIONS,$(1))) && \
	TEST_FILE=$$($(call COMPAT_TEST_FILE,$(1))) && \
	for v in $$VERSIONS; do \
		echo "\n=== $(1) $$v ==="; \
		if [ "$$v" = "latest" ]; then \
			uv pip install --upgrade $(1); \
		else \
			uv pip install "$(1)==$$v"; \
		fi && \
		uv run pytest $$TEST_FILE -v || exit 1; \
	done
	@uv sync --all-extras
endef

COMPAT_PYTHON_VERSIONS = uv run python -c "import yaml; print(' '.join(yaml.safe_load(open('compat.yaml'))['python']['versions']))"

test-compat: test-compat-anthropic test-compat-openai test-compat-boto3 test-compat-python ## Run SDK compatibility tests across versions

test-compat-python: ## Run unit tests across Python versions
	@VERSIONS=$$($(COMPAT_PYTHON_VERSIONS)) && \
	for v in $$VERSIONS; do \
		echo "\n=== python $$v ==="; \
		uv run --python $$v --all-extras pytest tests/ -v || exit 1; \
	done

test-compat-anthropic: ## Run anthropic compat tests across SDK versions
	$(call run-compat,anthropic)

test-compat-openai: ## Run openai compat tests across SDK versions
	$(call run-compat,openai)

test-compat-boto3: ## Run boto3 compat tests across SDK versions
	$(call run-compat,boto3)

release: ## Create a release (e.g. make release V=0.1.0)
	@test -n "$(V)" || (echo "Usage: make release V=x.y.z" && exit 1)
	@git diff --quiet || (echo "Error: working tree is dirty, commit changes first" && exit 1)
	@head -10 CHANGELOG.md | grep -q "## Unreleased" || (echo "Error: no Unreleased section in CHANGELOG.md" && exit 1)
	python3 -c "import pathlib; p = pathlib.Path('CHANGELOG.md'); p.write_text(p.read_text().replace('## Unreleased', '## Unreleased\n\n## v$(V) - $(shell date +%Y-%m-%d)'))"
	git add CHANGELOG.md
	git commit -m "Release v$(V)"
	git tag v$(V)
	@echo "Tagged v$(V). Push with: git push origin main v$(V)"
