SHELL := /bin/sh

UV ?= uv

.PHONY: setup test quality build release

setup:
	$(UV) sync --locked --all-groups

test:
	$(UV) run --frozen pytest

quality:
	$(UV) run --frozen ruff check .
	$(UV) run --frozen ruff format --check src tests
	$(UV) run --frozen ty check
	$(UV) run --frozen agentslint check . --strict
	$(UV) run --frozen pre-commit run --all-files --show-diff-on-failure

build:
	$(UV) build

release:
	@if [ -z "$(VERSION)" ]; then \
		echo "VERSION is required; use make release VERSION=v0.1.0"; \
		exit 2; \
	fi
	@printf '%s\n' "$(VERSION)" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$$' || { \
		echo "VERSION must be a semantic version prefixed with v, such as v0.1.0"; \
		exit 2; \
	}
	@package_version="$$( $(UV) version --short )"; \
	tag_version="$$(printf '%s' "$(VERSION)" | sed 's/^v//')"; \
	if [ "$$package_version" != "$$tag_version" ]; then \
		echo "pyproject.toml version $$package_version does not match $(VERSION)"; \
		echo "Run: uv version $$tag_version"; \
		exit 2; \
	fi; \
	if ! grep -Fq "agentslint==$$tag_version" .github/workflows/check.yml; then \
		echo ".github/workflows/check.yml must pin agentslint==$$tag_version"; \
		exit 2; \
	fi
	@if [ "$$(git branch --show-current)" != "main" ]; then \
		echo "releases must be created from main"; \
		exit 2; \
	fi
	@if [ -n "$$(git status --porcelain)" ]; then \
		echo "the working tree must be clean before creating a release"; \
		exit 2; \
	fi
	@git fetch --quiet origin main --tags
	@if [ "$$(git rev-parse HEAD)" != "$$(git rev-parse origin/main)" ]; then \
		echo "local main must match origin/main before creating a release"; \
		exit 2; \
	fi
	@if git rev-parse --quiet --verify "refs/tags/$(VERSION)" >/dev/null; then \
		echo "tag $(VERSION) already exists"; \
		exit 2; \
	fi
	git tag --annotate "$(VERSION)" --message "Release $(VERSION)"
	git push origin "$(VERSION)"
