# ENV

ifeq (,$(shell which uv))
	ifeq (,$(shell python3 -m uv --help||python3 -m pip install --user uv)) # detect uv install
		UV ?= false
	endif
	UV ?= python3 -m uv
endif

UV ?= uv
RUFF ?= $(UV) run --active ruff
TY ?= $(UV) run --active ty
UNITTEST ?= $(UV) run --active -m unittest
COVERAGE ?= $(UV) run --active coverage
OPEN ?= xdg-open

# DOCS

.PHONY: help
help: ## show this message
	echo "Usage: $(MAKE) [target1] [target2] ..."
	echo ""
	echo "Commands/Targets:"
	cat $(MAKEFILE_LIST) | grep -E '(^[a-zA-Z0-9_%-]+:.*?##.*$$)|(^##)' | awk 'BEGIN {FS = ":.*?## "}{printf "\033[32m%-20s\033[0m %s\n", $$1, $$2}' | sed -e 's/\[32m##/[33m/'
	echo ""
	echo "Environment:"
	cat $(MAKEFILE_LIST) | grep -E '^[a-zA-Z0-9_-]+\s*\??=.*$$' | grep -Eo '^[a-zA-Z0-9_-]+' | xargs -I {} $(MAKE) -s print-{} 2> /dev/null

.PHONY: print-%
print-%:
	echo -e '\033[32m$*\033[0m = $($*)'

# FILES

.venv: uv.lock
	$(MAKE) -s uv-sync

# ACTIONS

.PHONY: install
install: uv-sync ## install project

.PHONY: update
update: uv-upgrade ## update project dependencies

.PHONY: format
format: ruff-fix ruff-format ## format project

.PHONY: lint
lint: ruff ruff-format-check ty ## lint project

.PHONY: build
build: docker-build ## build project

.PHONY: test
test: unittest ## test project

.PHONY: test-%
test-%: ## test project with specific test
	$(MAKE) -s unittest-$*

.PHONY: coverage
coverage: coverage-unittest coverage-xml coverage-report ## test project with coverage

# TOOLS

.PHONY: uv-sync
uv-sync: ## uv sync
	$(UV) sync --active

.PHONY: uv-update
uv-upgrade: ## uv sync upgrade
	$(UV) sync --active --upgrade

.PHONY: ruff
ruff: .venv ## ruff check
	$(RUFF) check

.PHONY: ruff-fix
ruff-fix: .venv ## ruff check (and fix)
	$(RUFF) check --fix --unsafe-fixes

.PHONY: ruff-format
ruff-format: .venv ## ruff format
	$(RUFF) format

.PHONY: ruff-format-check
ruff-format-check: .venv ## ruff format (check only)
	$(RUFF) format --check

.PHONY: ty
ty: .venv ## ty check
	$(TY) check

.PHONY: unittest
unittest: .venv ## unittest
	$(UNITTEST) -v

.PHONY: unittest-%
unittest-%: .venv ## unittest -k [filter]
	$(UNITTEST) -v -k $*

.PHONY: coverage-unittest
coverage-unittest: .venv ## coverage run -m unittest
	$(COVERAGE) run -m unittest -v

.PHONY: coverage-report
coverage-report: .venv ## coverage report
	$(COVERAGE) report

.PHONY: coverage-html
coverage-html: .venv ## coverage html
	$(COVERAGE) html
	$(OPEN) htmlcov/index.html || true

.PHONY: coverage-xml
coverage-xml: .venv ## coverage xml
	$(COVERAGE) xml

.PHONY: release-%
release-%: .venv ## release major/minor/patch
	$(UV) version --bump=$*
	git add pyproject.toml uv.lock
	git commit -m "chore: $$(uv version --short)"
	git tag "release/$$(uv version --short)" -m "$$(uv version)"
	$(UV) build
