# =============================================================================
# CrystFlux Makefile - CI-first design with script integration
# =============================================================================

# Environment variables (CI=1 for automated pipelines)
CI ?= 0
CI_COLOR = $(if $(filter 0,$(CI)),1,0)
MYPY_STRICT ?= 0
MYPY_OPTS = $(if $(filter 1,$(MYPY_STRICT)),--warn-unused-ignores --warn-return-any --check-untyped-defs,)

.PHONY: help check check-examples lint typecheck test install docs clean deps-gate \
		ruff pyright mypy mypy-stubs ruff-examples pyright-examples mypy-examples

# =============================================================================
# Directory configuration
# =============================================================================
# Core directories (always checked)
CORE_DIRS   = src tests

# Extended directories (optional, for examples)
ALL_DIRS    = src tests examples

# =============================================================================
# Cleanup configuration (Strictly tool-generated artifacts)
# =============================================================================
# Tier 1: Internal tool caches (Safe to delete, auto-regenerated)
CLEAN_CACHES   = .mypy_cache .ruff_cache .pytest_cache .pyrightcache .basedpyrightcache

# Tier 2: Test & Coverage reports
CLEAN_REPORTS  = .coverage htmlcov

# Tier 3: Build & Distribution artifacts
CLEAN_BUILD    = build dist *.egg-info

# Tier 4: Generated documentation
CLEAN_DOCS     = .docs

# Note: The following are EXCLUDED from clean to protect developer work:
# - .venv/ (Use 'make distclean' if needed)
# - drafts/, sandbox/, tmp/, src/legacy/ (Developer assets)
# - AGENTS.md, GEMINI.md, etc. (Project context)

# =============================================================================
# Color and output configuration
# =============================================================================
ifeq ($(CI_COLOR),1)
  COLOR_GREEN  := \033[0;32m
  COLOR_YELLOW := \033[0;33m
  COLOR_RED    := \033[0;31m
  COLOR_RESET  := \033[0m
  ECHO_INFO    := @echo -e "$(COLOR_GREEN)[INFO]$(COLOR_RESET)"
  ECHO_DONE    := @echo -e "$(COLOR_GREEN)✓ Done$(COLOR_RESET)"
else
  ECHO_INFO    := @echo "[INFO]"
  ECHO_DONE    := @echo "Done"
endif

# Test verbosity: CI uses quiet mode
TEST_ARGS   = $(if $(filter 1,$(CI)),-q,--tb=short)
COV_ARGS    = --cov=crystflux --cov-report=term-missing

# =============================================================================
# Dependency Gate (triadic structure enforcement)
# =============================================================================
deps-gate:
	$(ECHO_INFO) Checking dependency gate...
	@uv run python scripts/check_deps.py
	@echo ""

# =============================================================================
# Linting
# =============================================================================
lint: ruff

ruff:
	$(ECHO_INFO) Running ruff on core...
	@uv run ruff check $(CORE_DIRS)
	$(ECHO_DONE)

# Examples linting
lint-examples: ruff-examples

ruff-examples:
	$(ECHO_INFO) Running ruff on examples...
	@uv run ruff check $(ALL_DIRS)
	$(ECHO_DONE)

# =============================================================================
# Type Checking
# =============================================================================
typecheck: pyright mypy

pyright:
	$(ECHO_INFO) Running basedpyright on core...
	@uv run basedpyright $(CORE_DIRS)
	$(ECHO_DONE)

mypy:
	$(ECHO_INFO) Running mypy on core...
	@uv run mypy $(MYPY_OPTS) $(CORE_DIRS)
	$(ECHO_DONE)

# Examples type checking
typecheck-examples: pyright-examples mypy-examples

pyright-examples:
	$(ECHO_INFO) Running basedpyright on examples...
	@uv run basedpyright $(ALL_DIRS)
	$(ECHO_DONE)

mypy-examples:
	$(ECHO_INFO) Running mypy on examples...
	@uv run mypy $(MYPY_OPTS) $(ALL_DIRS)
	$(ECHO_DONE)

mypy-stubs:
	$(ECHO_INFO) Checking stub consistency for numpy_chain...
	@uv run mypy --explicit-package-bases --check-untyped-defs -p crystflux.v1
	$(ECHO_DONE)

# =============================================================================
# Main Check Targets
# =============================================================================
# Quick check (src, tests only)
check: deps-gate lint typecheck
	$(ECHO_INFO) All core checks passed!

# Full check including examples
check-examples: deps-gate lint-examples typecheck-examples
	$(ECHO_INFO) All checks including examples passed!

# =============================================================================
# Testing
# =============================================================================
test:
	$(ECHO_INFO) Running pytest...
	@uv run pytest tests $(TEST_ARGS)

coverage:
	$(ECHO_INFO) Running pytest with coverage...
	@uv run pytest tests $(TEST_ARGS) $(COV_ARGS)
	$(ECHO_DONE)

# =============================================================================
# Installation
# =============================================================================
install: install-dev

install-dev:
	$(ECHO_INFO) Installing crystflux with dev dependencies...
	@uv pip install -e ".[dev]"

install-numpy:
	$(ECHO_INFO) Installing with NumPy adapter...
	@uv pip install -e ".[numpy]"

install-pydantic:
	$(ECHO_INFO) Installing with Pydantic adapter...
	@uv pip install -e ".[pydantic]"

install-all:
	$(ECHO_INFO) Installing with all adapters...
	@uv pip install -e ".[all]"

# =============================================================================
# Documentation (interactive mode)
# =============================================================================
docs:
	@echo "=== Documentation Generation ==="
	@echo "Output directory: .docs/"
	@echo "This will generate consolidated documentation files:"
	@echo "  - .docs/core.txt (Core modules)"
	@echo "  - .docs/boundary.txt (Boundary contracts)"
	@echo "  - .docs/adapters.txt (Adapter implementations)"
	@echo ""
	@read -p "Continue? (y/N): " confirm && [ "$$confirm" = "y" ] || exit 1
	@echo ""
	@echo "=== Generating documentation in .docs directory ==="
	@mkdir -p .docs
	@uv run python scripts/consolidate.py --root src/crystflux/v1 --format layered --output-dir .docs
	@echo ""
	@echo "Documentation generated in .docs directory"

# =============================================================================
# Cleanup
# =============================================================================
clean:
	$(ECHO_INFO) Cleaning tool-generated artifacts...
	
	@# 1. Remove static analysis and test caches (Tier 1 & 2)
	@rm -rf $(CLEAN_CACHES) $(CLEAN_REPORTS)
	@echo "  - [Caches] Removed analysis, test, and coverage artifacts"

	@# 2. Remove build and distribution artifacts (Tier 3)
	@rm -rf $(CLEAN_BUILD)
	@echo "  - [Build]  Removed build and distribution artifacts"

	@# 3. Remove documentation if it exists (Tier 4)
	@if [ -d "$(CLEAN_DOCS)" ]; then rm -rf $(CLEAN_DOCS) && echo "  - [Docs]   Removed generated documentation"; fi

	@# 4. Recursive cleanup for Python runtime artifacts (Tier 1 equivalent)
	@find . -name "__pycache__" -type d -exec rm -rf {} +
	@find . -name "*.py[co]" -type f -delete
	@find . -name "*$$py.class" -type f -delete
	@echo "  - [Python] Removed recursive bytecode and runtime caches"

	$(ECHO_DONE)

# =============================================================================
# Help
# =============================================================================
help:
	@echo "=============================================="
	@echo "CrystFlux - Immutable JSON Crystal Library"
	@echo "=============================================="
	@echo ""
	@echo "Usage: make <target> [CI=1]"
	@echo ""
	@echo "Main targets:"
	@echo "  check            Quick check (src, tests) - DEFAULT"
	@echo "  check-examples   Full check including examples/"
	@echo "  test             Run pytest ($(if $(filter 1,$(CI)),quiet,default))"
	@echo "  coverage         Run tests with coverage report"
	@echo ""
	@echo "Individual checks (core):"
	@echo "  deps-gate        Enforce triadic import rules"
	@echo "  lint, ruff       Run ruff on src, tests"
	@echo "  typecheck        Run basedpyright + mypy"
	@echo "  pyright          Run basedpyright on core"
	@echo "  mypy             Run mypy on core"
	@echo "  mypy-stubs       Check stub consistency"
	@echo ""
	@echo "Individual checks (examples):"
	@echo "  lint-examples    Run ruff on src, tests, examples"
	@echo "  typecheck-examples  Run basedpyright + mypy on examples"
	@echo "  pyright-examples Run basedpyright on examples"
	@echo "  mypy-examples    Run mypy on examples"
	@echo ""
	@echo "Installation:"
	@echo "  install          Install with dev dependencies (default)"
	@echo "  install-numpy    Install with NumPy adapter"
	@echo "  install-pydantic Install with Pydantic adapter"
	@echo "  install-all      Install with all adapters"
	@echo ""
	@echo "Utility:"
	@echo "  docs             Generate documentation to .docs/ (interactive)"
	@echo "  clean            Remove generated/cache files"
	@echo "  help             Show this message"
	@echo ""
	@echo "CI mode: CI=1 make check  # Quiet output for pipelines"
	@echo ""
	@echo "Environment variables:"
	@echo "  CI=1           Quiet mode for automated pipelines"
	@echo "  MYPY_STRICT=1  Enable mypy strict options (--warn-unused-ignores, etc.)"
	@echo "=============================================="