#!/bin/bash
# PMAT Pre-commit Quality Gates
# Adapted from ruchy's documentation synchronization approach

set -e

echo "🔍 PMAT Quality Gates - Checking documentation synchronization..."

# Documentation files that MUST be updated with code changes
REQUIRED_DOCS=(
    "docs/execution/roadmap.md"
    "docs/execution/quality-gates.md"
    "docs/architecture/decisions/"
    "CHANGELOG.md"
)

# Check if any Rust/source files are being committed
if git diff --cached --name-only | grep -qE '\.(rs|toml|md|yml|yaml)$'; then
    echo "📝 Source changes detected - verifying documentation updates..."
    
    # Ensure at least one documentation file is updated
    DOC_UPDATED=false
    for doc in "${REQUIRED_DOCS[@]}"; do
        if git diff --cached --name-only | grep -q "$doc"; then
            DOC_UPDATED=true
            echo "✓ Found documentation update: $doc"
            break
        fi
    done
    
    if [ "$DOC_UPDATED" = false ]; then
        echo "❌ ERROR: Code changes require documentation updates!"
        echo "📋 Must update at least one of:"
        for doc in "${REQUIRED_DOCS[@]}"; do
            echo "   - $doc"
        done
        echo ""
        echo "💡 Quick fix:"
        echo "   1. Update docs/execution/roadmap.md with task status"
        echo "   2. Add ADR in docs/architecture/decisions/ if architectural decision made"
        echo "   3. Update CHANGELOG.md with feature/fix"
        echo "   4. Update docs/execution/quality-gates.md with quality metrics"
        echo ""
        echo "🎯 Toyota Way: Documentation synchronization ensures quality at source"
        exit 1
    fi
fi

# Verify roadmap.md structure
if git diff --cached --name-only | grep -q "docs/execution/roadmap.md"; then
    # Check for task IDs and completion markers
    ROADMAP=$(git show :docs/execution/roadmap.md 2>/dev/null || cat docs/execution/roadmap.md)
    
    # Ensure task ID format (PMAT-XXXX)
    if ! echo "$ROADMAP" | grep -qE 'PMAT-[0-9]{4}'; then
        echo "⚠️  Warning: roadmap.md should use PMAT-XXXX task ID format"
    fi
    
    # Check for status markers
    if ! echo "$ROADMAP" | grep -qE '\[[ x🚧📋]\]'; then
        echo "⚠️  Warning: roadmap.md should include status markers [x], [🚧], [📋]"
    fi
    
    echo "✓ Roadmap.md structure validated"
fi

# Verify quality-gates.md updates
if git diff --cached --name-only | grep -q "docs/execution/quality-gates.md"; then
    echo "✓ Quality gates documentation updated"
fi

# Run PMAT quality checks on staged files (Toyota Way Jidoka)
echo "🔧 Running PMAT quality analysis (Toyota Way Jidoka)..."

QUALITY_VIOLATIONS=0

for file in $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.rs$'); do
    echo "  Checking $file..."
    
    # Skip target directory and archived files
    if [[ "$file" == target/* ]] || [[ "$file" == archive/* ]]; then
        continue
    fi
    
    # Complexity check using PMAT
    if command -v ./target/debug/pmat &> /dev/null; then
        echo "    Running complexity analysis..."
        if ! ./target/debug/pmat analyze complexity "$file" --max-cyclomatic 20 --max-cognitive 15 --fail-on-violation &>/dev/null; then
            echo "    ❌ Complexity violation in $file (exceeds Toyota Way standards)"
            echo "    🔧 Fix: ./target/debug/pmat refactor auto --file $file"
            QUALITY_VIOLATIONS=$((QUALITY_VIOLATIONS + 1))
        else
            echo "    ✓ Complexity check passed"
        fi
        
        # SATD check (zero tolerance)
        echo "    Running SATD analysis..."
        if ! ./target/debug/pmat analyze satd "$file" --fail-on-violation &>/dev/null; then
            echo "    ❌ SATD violation in $file (zero tolerance policy)"
            echo "    🔧 Fix: Remove all TODO/FIXME/HACK comments"
            QUALITY_VIOLATIONS=$((QUALITY_VIOLATIONS + 1))
        else
            echo "    ✓ SATD check passed"
        fi
    else
        echo "    ⚠️  PMAT binary not found, skipping quality checks"
        echo "    💡 Run 'make build' to enable quality gate validation"
    fi
done

# Check for Rust linting if we have Rust files
if git diff --cached --name-only | grep -qE '\.rs$'; then
    echo "  Running Rust linting..."
    if ! cargo clippy --quiet -- -D warnings &>/dev/null; then
        echo "  ❌ Clippy violations found"
        echo "  🔧 Fix: cargo clippy --fix && cargo fmt"
        QUALITY_VIOLATIONS=$((QUALITY_VIOLATIONS + 1))
    else
        echo "  ✓ Clippy checks passed"
    fi
fi

# Summary
if [ $QUALITY_VIOLATIONS -gt 0 ]; then
    echo ""
    echo "❌ Pre-commit quality gates FAILED!"
    echo "   Found $QUALITY_VIOLATIONS quality violations"
    echo "   🎯 Toyota Way: Stop the line, fix quality at source"
    echo ""
    echo "🔧 Quick fixes:"
    echo "   make fix          # Auto-fix formatting and simple issues"
    echo "   make validate     # Run full validation suite"
    echo "   pmat quality-gate # Run comprehensive quality analysis"
    exit 1
fi

echo ""
echo "✅ All pre-commit quality gates passed!"
echo "   🎯 Toyota Way: Quality built-in, documentation synchronized"
echo "   📝 Documentation updates verified"
echo "   🔧 Code quality standards maintained"
echo "   ✓ Ready for commit"