# Cargar variables desde .env si existe
ifneq (,$(wildcard .env))
include .env
export
endif

# Variables
PROFILE="pak"
DOMAIN="impalah"
AWS_REGION="us-east-1"
REGISTRY_URI="public.ecr.aws/e2b2x4l7"
REPOSITORY_NAME="auth-middleware"
PLATFORM="linux/amd64"
BUILDER_NAME="mybuilder"
PART ?= patch  # can be overwritten with: make bump-version PART=minor

SONAR_HOST_URL ?= http://localhost:9000
SONAR_TOKEN ?=
PY_SRC ?= src


# Delete the virtual environment and force a sync
venv:
	rm -rf .venv && \
	echo "Deleted virtual environment" && \
	uv sync && \
	echo "Created virtual environment" && \
	uvx --from=toml-cli toml get --toml-path=pyproject.toml project.version

# Sync version from pyproject.toml to __init__.py and pages_source/conf.py
sync-version:
	uv run python scripts/update_version.py

# Bump patch/minor/major version and sync across all files
bump-version:
	uv run python scripts/bump_version.py $(PART)

# Build python package (run 'make bump-version' first if needed)
build:
	uv build

# Clean build artifacts
clean-artifacts:
	rm -rf dist *.egg-info build && \
	echo "Cleaned build artifacts"

clean: clean-artifacts ## Clean temporary files
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name .pytest_cache -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name "*.pyc" -delete
	find . -type d -name ".mypy_cache" -exec rm -rf {} + 2>/dev/null || true
	find . -type d -name ".ruff_cache" -exec rm -rf {} + 2>/dev/null || true

# Publish package on PyPI (use UV_PYPI_TOKEN or .pypirc for authentication)
publish: build
	uv publish

# Publish on TestPyPI
publish-test: build
	uv publish --repository testpypi

# Build docker image
docker-build: bump-version
	@BASE_VERSION=$$(uvx --from=toml-cli toml get --toml-path=pyproject.toml project.version) && \
	echo "Bumped version to $$BASE_VERSION" && \
	if docker buildx inspect $(BUILDER_NAME) >/dev/null 2>&1; then \
		echo "Builder '$(BUILDER_NAME)' exists. Activating..."; \
		docker buildx use $(BUILDER_NAME); \
	else \
		echo "Creating new builder '$(BUILDER_NAME)'..."; \
		docker buildx create --name $(BUILDER_NAME) --use; \
	fi && \
	echo "Building Docker image with buildx..." && \
	docker buildx build \
		--platform $(PLATFORM) \
		--push \
		-t $(REGISTRY_URI)/$(DOMAIN)/$(REPOSITORY_NAME):$$BASE_VERSION \
		-t $(REGISTRY_URI)/$(DOMAIN)/$(REPOSITORY_NAME):latest \
		. && \
	echo "Docker image built and pushed successfully"

# Release to docker registry with version tags
docker-release: docker-build
	@BASE_VERSION=$$(uvx --from=toml-cli toml get --toml-path=pyproject.toml project.version) && \
	echo "Released Docker image: $(REGISTRY_URI)/$(DOMAIN)/$(REPOSITORY_NAME):$$BASE_VERSION"

# Run linting with ruff
lint:
	uv run ruff check src/ tests/

format: ## Format code
	uv run ruff format .

# Run type checking with mypy
type-check:
	uv run mypy src/

# Run security checks with bandit
security-check:
	uv run bandit -r src/ --exclude src/auth_middleware/authz/testing

# Run all quality checks
check: lint format type-check security-check
	echo "All checks completed"

test: ## Run tests
	uv run pytest -v

test-cov: ## Run tests with coverage report
	uv run pytest --cov --cov-report=xml --cov-report=term --cov-report=html

# # Run tests with pytest
# test:
# 	uv run pytest tests/ --cov=src/ --cov-report=term --cov-report=html --cov-report=xml --junitxml=junit.xml -v

# Install project in development mode
install:
	uv sync

# Install project with all optional dependencies
install-all:
	uv sync --all-extras

# Run the application
run:
	uv run python -m auth_middleware

# Open Python REPL with project environment
shell:
	uv run python

# Show project info
info:
	@echo "Project: auth-middleware"
	@echo "Version: $$(uvx --from=toml-cli toml get --toml-path=pyproject.toml project.version)"
	@echo "Python: $$(uv run python --version)"
	@echo "Virtual env: $$(if [ -d .venv ]; then echo ".venv exists"; else echo ".venv not found"; fi)"

# Build documentation
# Stores against DynamoDB, PostgreSQL and MySQL emulated by Floci (needs Docker)
test-floci:
	uv run pytest -m floci tests/authz/integration -v

# Mutation testing of the access-decision code (slow: run it by hand or nightly, not on every push).
# Override the scope with: make mutation MUTATION_MODULES="auth_middleware.authz.engine*"
MUTATION_MODULES ?= auth_middleware.authz.abac.conditions* auth_middleware.authz.abac.pdp* auth_middleware.authz.abac.validation* auth_middleware.authz.abac.cache* auth_middleware.authz.abac.types* auth_middleware.authz.engine*
MUTATION_MIN ?= 90
mutation:
	uv run --with mutmut mutmut run --max-children 6 $(MUTATION_MODULES)
	uv run python scripts/mutation_summary.py --min $(MUTATION_MIN)

mutation-report:
	uv run python scripts/mutation_summary.py --survivors

docs:
	uv run sphinx-build -W --keep-going pages_source docs

# Serve documentation locally
docs-serve: docs
	uv run python -m http.server 8000 --directory docs

# Help target
help:
	@echo "Available targets:"
	@echo "  venv          - Delete and recreate virtual environment"
	@echo "  install       - Install project dependencies"
	@echo "  install-all   - Install with all optional dependencies"
	@echo "  bump-version  - Bump version (PART=patch|minor|major) + sync"
	@echo "  sync-version  - Sync version from pyproject.toml to all files"
	@echo "  build         - Build package"
	@echo "  publish       - Publish to PyPI"
	@echo "  publish-test  - Publish to TestPyPI"
	@echo "  test          - Run tests with coverage"
	@echo "  lint          - Run linting"
	@echo "  format        - Format code"
	@echo "  type-check    - Run type checking"
	@echo "  security-check- Run security checks"
	@echo "  check         - Run all quality checks"
	@echo "  docker-build  - Build and push Docker image"
	@echo "  docker-release- Release Docker image"
	@echo "  test-floci    - Run the store tests on Floci (Docker, testcontainers)"
	@echo "  deps-check    - Check declared vs imported dependencies (deptry)"
	@echo "  mutation      - Mutation testing of the access-decision code (slow; MUTATION_MODULES, MUTATION_MIN)"
	@echo "  mutation-report - List the surviving mutants of the last run"
	@echo "  docs          - Build the Sphinx site (pages_source) into docs/"
	@echo "  docs-serve    - Serve the built site locally"
	@echo "  run           - Run the application"
	@echo "  shell         - Open Python REPL"
	@echo "  clean         - Clean build artifacts"
	@echo "  info          - Show project information"
	@echo "  help          - Show this help"

sonar: ## Run SonarQube analysis with pysonar
	@test -n "$(SONAR_TOKEN)" || (echo "ERROR: define SONAR_TOKEN"; exit 1)
	SONAR_HOST_URL=$(SONAR_HOST_URL) SONAR_TOKEN=$(SONAR_TOKEN) uv run pysonar

sonar-check: test-cov sonar ## Run coverage and SonarQube analysis

.PHONY: venv bump-version sync-version build clean-artifacts clean publish publish-test docker-build docker-release lint format type-check security-check check test test-cov install install-all run shell info test-floci docs docs-serve deps-check mutation mutation-report help sonar sonar-check

# Dependency hygiene (undeclared / unused / misplaced dependencies)
deps-check:
	uvx deptry src
