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

PYTHON ?= python3
GITEA_URL := https://git.chipperfluff.at
VENV ?= .venv
VENV_BIN := $(VENV)/bin
INSTALL_STAMP := $(VENV)/.installed

.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_BIN)/python:
	$(PYTHON) -m venv $(VENV)

venv: $(VENV_BIN)/python ## Create a local virtual environment

$(INSTALL_STAMP): pyproject.toml | $(VENV_BIN)/python
	$(VENV_BIN)/python -m pip install --upgrade pip
	$(VENV_BIN)/python -m pip install -e '.[dev]'
	@touch $(INSTALL_STAMP)

install: $(INSTALL_STAMP) ## Install the package and development tools

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

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

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

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

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_OWNER GITEA_TOKEN; do \
		value="$${!variable}"; \
		case "$$value" in \
			''|*'###'*|your-username|your-user-or-organization|replace-with-a-gitea-access-token) \
				echo "Set a real $$variable value in .env"; exit 1 ;; \
		esac; \
	done

publish: check-publish-config build ## Upload the package to the Gitea PyPI registry
	@set -a; source .env; set +a; \
	TWINE_USERNAME="$$GITEA_TOKEN" \
	TWINE_PASSWORD=x-oauth-basic \
	TWINE_NON_INTERACTIVE=1 \
	$(VENV_BIN)/python -m twine upload \
		--disable-progress-bar \
		--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
