# Makefile for Splunk SecureApp Python Agent Development

VENV_NAME ?= venv
VENV_DIR := $(VENV_NAME)
PYTHON := $(VENV_DIR)/bin/python
PIP := $(VENV_DIR)/bin/pip

# OpenTelemetry packages for version testing
OTEL_PACKAGES := opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp

# Reusable functions
define install_otel_version
	$(PYTHON) -m pip uninstall -y $(OTEL_PACKAGES)
	$(PYTHON) -m pip install $(foreach pkg,$(OTEL_PACKAGES),$(pkg)==$(1))
endef

define restore_deps
	@echo "🔄 Restoring original dependencies..."
	$(PYTHON) -m pip uninstall -y $(OTEL_PACKAGES)
	$(PYTHON) -m pip install -e .
endef

.PHONY: help venv-install test test-matrix tox lint format typecheck \
        check-license build clean all benchmark debug debug-packages debug-performance \
        publish validate-env show-version test-otel-versions quick-test venv-update \
        test-otel-version test-local-otel-matrix

help:
	@echo "SecureApp Python Agent - Development Commands"
	@echo ""
	@echo "🚀 Quick Start:"
	@echo "  make venv-install  # One-time setup: creates venv + installs all dependencies"
	@echo "  make all           # Complete validation pipeline (matches GitLab CI exactly)"
	@echo ""
	@echo "📋 Setup & Environment:"
	@echo "  venv-install       - Setup development environment with all dependencies"
	@echo "  venv-update        - Update existing venv with new dependencies (faster than reinstall)"
	@echo "  validate-env       - Validate Python version and tool availability"
	@echo ""
	@echo "🧪 Testing Commands:"
	@echo "  all               - Complete validation: format → lint → typecheck → test (85% coverage)"
	@echo "  test              - Run tests with 85% coverage requirement"
	@echo "  quick-test        - Run only tests affected by recent changes (fastest for development)"
	@echo ""
	@echo "🔬 Compatibility Testing:"
	@echo "  test-matrix       - Run tests across all Python versions (PARALLEL: faster, uses tox -p auto)"
	@echo "  tox               - Run tests across all Python versions (SEQUENTIAL: slower, clearer output)"
	@echo "  test-otel-versions - Test with different OpenTelemetry versions"
	@echo "  test-otel-version  - Test with a specific OpenTelemetry version (OTEL_VERSION=X.Y.Z)"
	@echo "  test-local-otel-matrix - Run full OTel version matrix tests locally"
	@echo ""
	@echo "🔧 Code Quality:"
	@echo "  format            - Format code with ruff (auto-fixes style issues)"
	@echo "  lint              - Run linting with auto-fix (catches bugs + style violations)"
	@echo "  typecheck         - Run type checking with mypy (ensures type safety)"
	@echo "  check-license     - Verify and add license headers to Python files"
	@echo ""
	@echo "🚀 Performance & Analysis:"
	@echo "  benchmark          - Run complete benchmark suite (startup, memory, CPU impact)"
	@echo "  debug             - Interactive debug analyzer (explore runtime state)"
	@echo ""
	@echo "🔍 Debug & Troubleshooting:"
	@echo "  debug-packages    - Show current runtime package analysis"
	@echo "  debug-performance - Run performance analysis"
	@echo ""
	@echo "📦 Build & Release:"
	@echo "  build             - Build distribution packages (wheel + sdist)"
	@echo "  publish           - Publish package to Artifactory (requires credentials)"
	@echo "  clean             - Clean all build artifacts and caches (preserves venv)"
	@echo "  show-version      - Show current version from setuptools-scm"
	@echo ""
	@echo "💡 Common Workflows:"
	@echo "  • Daily Development: make quick-test → make all"
	@echo "  • Before Committing: make all"
	@echo "  • OpenTelemetry Changes: make test-otel-versions"
	@echo "  • Python Version Testing: make tox (tests Python 3.10-3.14)"
	@echo "  • Performance Validation: make benchmark or tox -e benchmark"
	@echo "  • Environment Update: make venv-update → make validate-env"
	@echo ""
	@echo "📊 Requirements:"
	@echo "  • Performance: <100ms startup, <10MB memory, 85%+ coverage"
	@echo "  • Compatibility: Python 3.10-3.14, OpenTelemetry 1.27.0-1.39.x (tested up to 1.39.1)"

# Setup development environment (one command for new developers)
$(PYTHON):
	@echo "🔍 Creating virtual environment..."
	python3 -m venv $(VENV_DIR)
	$(PIP) install --upgrade pip

venv-install: $(PYTHON)
	$(PIP) install -e .[dev]
	@echo "✅ Development environment ready!"
	@echo "Run 'make all' to validate your setup."

# Update existing venv with new dependencies (faster than reinstall)
venv-update: $(PYTHON)
	@echo "🔄 Updating virtual environment dependencies..."
	$(PIP) install --upgrade pip
	$(PIP) install -e .[dev] --upgrade
	@echo "✅ Dependencies updated!"

# Core development workflow
test:
	$(PYTHON) -m pytest tests --junit-xml=pytest-results.xml

# Run only tests affected by recent changes (fastest for development)
quick-test:
	@echo "🚀 Running only tests affected by recent changes..."
	$(PYTHON) -m pytest tests -xvs --testmon --no-cov

tox:
	tox

lint:
	$(PYTHON) -m ruff check src tests dev --fix

format:
	$(PYTHON) -m ruff format src tests dev

typecheck:
	$(PYTHON) -m mypy src tests

check-license:
	@echo "🔍 Checking license headers..."
	@echo "Files being checked: src/ tests/ dev/ examples/"
	find src tests dev examples -name "*.py" -type f -exec $(PYTHON) dev/scripts/check_license.py {} +
	@echo "✅ License check complete"

# Build distribution packages
build:
	$(PYTHON) -m build

clean:
	@echo "🧹 Cleaning build artifacts and caches..."
	rm -rf build/ dist/ *.egg-info/ src/*.egg-info/ venv/ logs/
	rm -rf .coverage* .testmondata pytest-results.xml htmlcov/ coverage.xml .pytest_cache/ .mypy_cache/ .ruff_cache/ .tox/
	rm -rf tests/htmlcov/ tests/coverage.xml tests/.coverage
	rm -rf dev/benchmarks/results/ dev/benchmarks/.pytest_cache/
	rm -f src/splunk_secureapp_opentelemetry_extension/_version.py
	rm -f o11y_test_application/otel-collector/otelcol_darwin_amd64
	rm -f o11y_test_application/otel-collector/out.txt
	find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
	find . -type f -name "*.pyc" -delete 2>/dev/null || true
	find . -type f -name "*.pyo" -delete 2>/dev/null || true
	find . -type f -name "*.orig" -delete 2>/dev/null || true
	find . -type f -name "*.rej" -delete 2>/dev/null || true
	find . -type f -name ".DS_Store" -delete 2>/dev/null || true
	@echo "✅ Clean complete"

# Complete validation pipeline - enforces 85% coverage
all: format lint typecheck test
	@echo "✅ All checks passed! (format → lint → typecheck → test with 85% coverage)"

# Performance benchmarks
benchmark:
	@echo "🚀 Running benchmark suite..."
	$(PYTHON) dev/benchmarks/benchmark_suite.py

# Debug and analysis tools
debug:
	@echo "🔍 Starting debug analyzer..."
	$(PYTHON) dev/debug/debug_analyzer.py --analyze

debug-packages:
	@echo "📦 Analyzing runtime packages..."
	$(PYTHON) dev/debug/debug_analyzer.py

debug-performance:
	@echo "⚡ Running performance analysis..."
	$(PYTHON) dev/debug/debug_analyzer.py --performance

# CI/CD Publishing target - called from gitlab - do we still need this?  Check this -check this3 -checkthis5
publish:
	@echo "📦 Publishing package to repository: $(if $(REPOSITORY),$(REPOSITORY),local)..."
	$(PYTHON) -m twine upload dist/* $(if $(REPOSITORY),--repository $(REPOSITORY),--repository local)

# CI/CD Publishing target - added to go to real test pypi - config set in .pypirc - called by buildPublish.sh testpypi
publish_testpypi:
	@echo "📦 Publishing package to repository: testpypi..."
	$(PYTHON) -m twine upload dist/* --repository testpypi

# Matrix testing across Python versions (for advanced CI)
test-matrix:
	@echo "🔬 Running matrix tests..."
	tox -p auto

# Test with different OpenTelemetry versions
test-otel-versions:
	@echo "🔬 Testing across OpenTelemetry versions (1.27.0 to 1.35.0)..."
	$(call install_otel_version,1.27.0)
	@echo "✅ Testing with OpenTelemetry 1.27.0..."
	$(PYTHON) -m pytest tests --no-cov
	$(call install_otel_version,1.35.0)
	@echo "✅ Testing with OpenTelemetry 1.35.0..."
	$(PYTHON) -m pytest tests --no-cov
	$(call restore_deps)
	@echo "✅ OpenTelemetry compatibility testing completed successfully!"

# Test with a specific OpenTelemetry version
test-otel-version:
	@test -n "$(OTEL_VERSION)" || (echo "❌ Error: OTEL_VERSION not specified" && echo "Usage: make test-otel-version OTEL_VERSION=X.Y.Z" && exit 1)
	@echo "🔬 Testing with OpenTelemetry $(OTEL_VERSION)..."
	$(call install_otel_version,$(OTEL_VERSION))
	@$(PYTHON) -c "from importlib.metadata import distributions; pkgs=sorted('{}=={}'.format(name, d.version) for d in distributions() for name in [d.metadata.get('Name') or ''] if 'opentelemetry' in name.lower()); print('✅ Installed:', ', '.join(pkgs))"
	$(PYTHON) -m pytest tests
	$(call restore_deps)
	@echo "✅ OpenTelemetry compatibility testing completed successfully!"

# Run local OpenTelemetry matrix testing
test-local-otel-matrix:
	@echo "🔬 Running full OpenTelemetry version matrix tests locally..."
	@for version in 1.27.0 1.30.0 1.35.0 1.38.0 1.39.0 1.39.1; do \
		echo "🔬 Testing with OpenTelemetry $$version..."; \
		$(PYTHON) -m pip uninstall -y $(OTEL_PACKAGES); \
		$(PYTHON) -m pip install $(foreach pkg,$(OTEL_PACKAGES),$(pkg)==$$version); \
		$(PYTHON) -m pytest tests --no-cov || exit 1; \
	done
	$(call restore_deps)
	@echo "✅ OpenTelemetry matrix testing completed successfully!"

# Validate environment and dependencies
validate-env:
	@echo "✅ Validating environment..."
	@$(PYTHON) --version
	@$(PYTHON) -c "import sys; print(f'Python: {sys.version}')"
	@$(PYTHON) -c "import pytest, ruff, mypy; print('✅ All dev tools available')"

# Release Management Commands (Git Tag-Based Versioning)
show-version:
	@echo "📅 Current version from setuptools-scm:"
	@$(PYTHON) -m setuptools_scm || echo "Unable to determine version (no git tags yet)"
