SHELL := /bin/bash
.DEFAULT_GOAL := help

PYTHON ?= python3
VENV ?= .venv
VENV_BIN := $(VENV)/bin

.PHONY: help venv install test lint format build check-publish-config publish clean

help: ## Show the available commands
	@awk 'BEGIN {FS = ":.*## "; printf "Usage: make <target>\n\n"} /^[a-zA-Z_-]+:.*?## / {printf "  %-22s %s\n", $$1, $$2}' $(MAKEFILE_LIST)

venv: ## Create a local virtual environment
	$(PYTHON) -m venv $(VENV)

install: venv ## Install the package and development tools
	$(VENV_BIN)/python -m pip install --upgrade pip
	$(VENV_BIN)/python -m pip install -e '.[dev]'

test: ## Run the test suite
	$(VENV_BIN)/pytest

lint: ## Check formatting and lint the code
	$(VENV_BIN)/ruff check .
	$(VENV_BIN)/ruff format --check .

format: ## Format the Python code
	$(VENV_BIN)/ruff check --fix .
	$(VENV_BIN)/ruff format .

build: ## Build wheel and source distributions
	rm -rf build dist
	$(VENV_BIN)/python -m build

check-publish-config: ## Validate the Gitea package registry settings
	@set -a; source .env 2>/dev/null || { echo "Missing .env (copy .env.example to .env)"; exit 1; }; set +a; \
	for variable in GITEA_URL GITEA_OWNER GITEA_USERNAME GITEA_TOKEN; do \
		if [[ -z "$${!variable}" ]]; then echo "Missing $$variable in .env"; exit 1; fi; \
	done

publish: check-publish-config build ## Upload the package to the Gitea PyPI registry
	@set -a; source .env; set +a; \
	TWINE_USERNAME="$$GITEA_USERNAME" \
	TWINE_PASSWORD="$$GITEA_TOKEN" \
	$(VENV_BIN)/python -m twine upload \
		--repository-url "$${GITEA_URL%/}/api/packages/$$GITEA_OWNER/pypi" \
		dist/*

clean: ## Remove generated files
	rm -rf .pytest_cache .ruff_cache build dist *.egg-info src/*.egg-info
	find . -type d -name __pycache__ -prune -exec rm -rf {} +
	find . -type f -name '*.py[co]' -delete

