#!/bin/bash
# Ruchy Pre-commit Quality Gates

set -e

echo "🔍 Ruchy 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|ruchy)$'; 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
            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 if architectural decision made"
        echo "   3. Update CHANGELOG.md with feature/fix"
        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 (RUCHY-XXXX)
    if ! echo "$ROADMAP" | grep -qE 'RUCHY-[0-9]{4}'; then
        echo "⚠️  Warning: roadmap.md should use RUCHY-XXXX task ID format"
    fi
    
    # Check for status markers
    if ! echo "$ROADMAP" | grep -qE '\[[ x]\]'; then
        echo "⚠️  Warning: roadmap.md should include [x] completion markers"
    fi
fi

# Run PMAT quality checks on staged files
echo "🔧 Running PMAT quality analysis..."

for file in $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(rs|ruchy)$'); do
    echo "  Checking $file..."
    
    # Complexity check
    if command -v pmat &> /dev/null; then
        pmat analyze complexity "$file" \
            --max-cyclomatic 10 \
            --max-cognitive 10 \
            --fail-on-violation || {
            echo "❌ Complexity violation in $file"
            echo "Run: pmat refactor $file"
            exit 1
        }
    fi
done

echo "✅ All quality gates passed!"