PYTHON  ?= python3
ARGS    ?=
# Everything CI tests; `make matrix` runs the lot through uv.
PYTHONS ?= 3.9 3.10 3.11 3.12 3.13 3.14

# src-layout: nothing is importable from the repo root, so running and testing
# straight out of a clone needs src/ on the path.
export PYTHONPATH := src

.DEFAULT_GOAL := help

.PHONY: help
help:  ## show this help
	@grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) \
		| awk -F':.*?## ' '{printf "  \033[1m%-12s\033[0m %s\n", $$1, $$2}'

.PHONY: run
run:  ## run the dashboard from the clone (make run ARGS="--once")
	$(PYTHON) -m aiusage $(ARGS)

.PHONY: test
test:  ## run the unit tests (no network)
	$(PYTHON) -m unittest discover -s tests -v

.PHONY: install
install:  ## install the command into ~/.local/bin (uv tool / pipx / pip --user)
	@if command -v uv >/dev/null 2>&1; then \
		uv tool install --force .; \
	elif command -v pipx >/dev/null 2>&1; then \
		pipx install --force .; \
	else \
		$(PYTHON) -m pip install --user --upgrade .; \
	fi
	@echo "installed — run 'aiusage init', then 'aiusage'"

.PHONY: uninstall
uninstall:  ## remove the installed command (`aiusage uninstall` clears config and cache)
	@if command -v uv >/dev/null 2>&1 && uv tool list 2>/dev/null | grep -q '^aiusage-tui'; then \
		uv tool uninstall aiusage-tui; \
	elif command -v pipx >/dev/null 2>&1 && pipx list --short 2>/dev/null | grep -q '^aiusage-tui'; then \
		pipx uninstall aiusage-tui; \
	else \
		$(PYTHON) -m pip uninstall -y aiusage-tui; \
	fi
	@echo "config and cache are untouched; 'aiusage uninstall' clears those"

.PHONY: zipapp
zipapp: clean-pyc  ## build a single self-contained executable at dist/aiusage
	@mkdir -p dist
	$(PYTHON) -m zipapp src -p "/usr/bin/env python3" -m "aiusage.__main__:main" \
		-o dist/aiusage
	@chmod +x dist/aiusage
	@ls -lh dist/aiusage

.PHONY: matrix
matrix:  ## run the tests on every supported python (needs uv)
	@for v in $(PYTHONS); do \
		printf 'py%-5s ' "$$v"; \
		uv run -q --no-project --python $$v python -m unittest discover -s tests 2>&1 | tail -1; \
	done

.PHONY: build
build:  ## build the wheel and sdist into dist/
	@if command -v uv >/dev/null 2>&1; then uv build; else $(PYTHON) -m build; fi

.PHONY: clean-pyc
clean-pyc:
	@find . -name __pycache__ -type d -not -path './.git/*' -exec rm -rf {} + 2>/dev/null || true
	@find . -name '*.py[co]' -not -path './.git/*' -delete

.PHONY: clean
clean: clean-pyc  ## remove build artefacts
	rm -rf dist build ./*.egg-info src/*.egg-info
