#!/bin/bash
# Ggen Pre-Commit Hook: Panic Point Prevention
# Uses ggen's own tools to prevent panic points from being committed

set -euo pipefail

echo "🔍 Ggen Pre-Commit: Checking for panic points..."

# Colors
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m'

# Get list of staged Rust files (excluding tests)
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep "\.rs$" | grep -v "/tests/" | grep -v "_test\.rs" || true)

if [ -z "$STAGED_FILES" ]; then
    echo -e "${GREEN}✅ No Rust files to check${NC}"
    exit 0
fi

echo "Checking files:"
echo "$STAGED_FILES" | sed 's/^/  - /'
echo ""

# Check for panic points in staged files
PANIC_POINTS=0

for file in $STAGED_FILES; do
    # Count .expect() calls (excluding SAFE comments)
    EXPECT_COUNT=$(grep -n "\.expect(" "$file" 2>/dev/null | grep -v "// SAFE:" | grep -v "#\[cfg(test)\]" | wc -l | tr -d ' ')

    # Count .unwrap() calls (excluding SAFE comments and safe variants)
    UNWRAP_COUNT=$(grep -n "\.unwrap()" "$file" 2>/dev/null | grep -v "// SAFE:" | grep -v "#\[cfg(test)\]" | grep -v "unwrap_or" | wc -l | tr -d ' ')

    FILE_PANIC_POINTS=$((EXPECT_COUNT + UNWRAP_COUNT))

    if [ "$FILE_PANIC_POINTS" -gt 0 ]; then
        echo -e "${RED}❌ $file: $FILE_PANIC_POINTS panic point(s)${NC}"

        # Show the offending lines
        if [ "$EXPECT_COUNT" -gt 0 ]; then
            echo "  .expect() calls:"
            grep -n "\.expect(" "$file" 2>/dev/null | grep -v "// SAFE:" | grep -v "#\[cfg(test)\]" | head -3 | sed 's/^/    /'
        fi

        if [ "$UNWRAP_COUNT" -gt 0 ]; then
            echo "  .unwrap() calls:"
            grep -n "\.unwrap()" "$file" 2>/dev/null | grep -v "// SAFE:" | grep -v "#\[cfg(test)\]" | grep -v "unwrap_or" | head -3 | sed 's/^/    /'
        fi

        echo ""
        PANIC_POINTS=$((PANIC_POINTS + FILE_PANIC_POINTS))
    fi
done

if [ "$PANIC_POINTS" -gt 0 ]; then
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${RED}❌ COMMIT BLOCKED: Found $PANIC_POINTS panic point(s)${NC}"
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo "Production code must not contain .expect() or .unwrap() calls."
    echo ""
    echo "To fix:"
    echo -e "  ${YELLOW}1. Use automatic fixer:${NC}"
    echo "     cargo script scripts/fix-panic-points.rs --dry-run"
    echo "     cargo script scripts/fix-panic-points.rs"
    echo ""
    echo -e "  ${YELLOW}2. Manual fix - replace with safe patterns:${NC}"
    echo "     ❌ .expect(\"msg\")  →  ✅ .map_err(|e| anyhow!(\"msg: {}\", e))?"
    echo "     ❌ .unwrap()        →  ✅ .unwrap_or_default()"
    echo "     ❌ .unwrap()        →  ✅ ?"
    echo ""
    echo -e "  ${YELLOW}3. If truly safe, add comment:${NC}"
    echo "     let value = some_value.unwrap(); // SAFE: Guaranteed by invariant X"
    echo ""
    echo "See docs/PRODUCTION_READINESS_8020.md for details."
    echo ""
    exit 1
fi

echo -e "${GREEN}✅ No panic points found - commit allowed${NC}"
exit 0
