SHELL := bash

.ONESHELL:
ENV_PREFIX=$(shell python -c "if __import__('pathlib').Path('.venv/bin/pip').exists(): print('.venv/bin/')")
USING_UV=$(shell grep "tool.uv" pyproject.toml && echo "yes")
USING_POETRY=$(shell grep "tool.poetry" pyproject.toml && echo "yes")
.SHELLFLAGS := -eu -o pipefail -c

# existing VIRTUAL_ENV might mess with poetry, so make sure it is gone
# VIRTUAL_ENV=
# unexport VIRTUAL_ENV

help:
	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9._-]+:.*?## / {printf "\033[1m\033[36m%-38s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)

.PHONY: all
all: show install dev-install test coverage typecheck check lint format build install-local uninstall clean license ## run all targets

.PHONY: show
show: ## show the current environment
	@echo "Current environment:"
	@if [ "$(USING_UV)" ]; then uv version && exit; fi
	@if [ "$(USING_POETRY)" ]; then poetry env info && exit; fi
	@echo "Running using $(ENV_PREFIX)"
	@$(ENV_PREFIX)python3 -V
	@$(ENV_PREFIX)python3 -m site

.PHONY: install
install: ## install runtime dependencies
	@echo "🧩 Installing runtime dependencies..."
	uv sync --frozen --no-dev

.PHONY: dev-install
dev-install: ## install all dependencies (including dev) and set up pre-commit hooks
	@echo "🎨 Installing all dependencies and setting up pre-commit hooks..."
	uv sync
	pre-commit install
	pre-commit run --all-files

.PHONY: test
test: ## run pytest
	@echo "🧪 Running unit tests..."
	uv run -m pytest tests/* -rA -vvs --log-level INFO

.PHONY: coverage
coverage: ## generate test coverage
	@echo "📑 Generating test coverage..."
	uv run pytest --cov=wittrans

.PHONY: typecheck
typecheck: ## run ty to type check code
	@echo "🔎 Running type checker..."
	uv run ty check

.PHONY: check
check: ## run ruff to check code
	@echo "🔍 Checking Python code for errors..."
	uv run ruff check . wittrans tests

.PHONY: lint
lint: ## run ruff to check and fix code
	@echo "⚠️ Fixing errors in Python code..."
	uv run ruff check --fix . wittrans tests

.PHONY: format
format: ## run ruff to format code
	@echo "🧬 Formatting Python code..."
	uv run ruff format . wittrans tests

.PHONY: build
build: ## build distributable package (wheel and sdist)
	@echo "📦 Building package..."
	uv build
	@echo "Package built in dist/ directory"

.PHONY: install-local
install-local: build ## install package locally from built wheel
	@echo "🌱 Installing package locally..."
	uv tool install dist/*.whl --force-reinstall
	@echo "Package installed. Run 'wittrans' to use."

.PHONY: uninstall
uninstall: ## uninstall the package
	@echo "🚨 Uninstalling package..."
	uv tool uninstall wittrans

.PHONY: clean
clean: ## clean python files
	@echo "🗑️ Cleaning temporary Python files..."
	rm -rf dist/ build/ *.egg-info src/*.egg-info docs/_build .mypy_cache .pytest_cache .ruff_cache
	find . -type f -name '*.py[co]' -delete -o -type d -name __pycache__ -delete

.PHONY: license
license: ## run reuse to check license compliance
	@echo "©️ Checking license compliance..."
	reuse lint
