#!/bin/bash
################################################################################
# Pre-commit Hook: Security & Workflow Protection
#
# Purpose: Prevent API keys, tokens, and sensitive data from being committed
#
# Phases:
# 1. Security Secrets Detection (CRITICAL) - Blocks if secrets found
# 2. Workflow Protection - Enforces Git branch rules
#
# Exit codes:
# 0 - All checks passed
# 1 - Secrets detected or workflow violation
################################################################################

set -e

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

###############################################################################
# PHASE 1: Security Secrets Detection (CRITICAL)
###############################################################################

echo "🔒 [Phase 1] Running Security Secrets Detection..."

SECRETS_FOUND=false

# Define secret patterns to detect
declare -a PATTERNS=(
    "AIzaSy[A-Za-z0-9_-]{35}"        # Google APIs
    "sk-[A-Za-z0-9]{20,}"             # OpenAI
    "sk_[A-Za-z0-9]{20,}"             # OpenAI variant
    "sk-ant-[A-Za-z0-9]{20,}"        # Anthropic
    "AKIA[0-9A-Z]{16}"                # AWS Access Keys
    "api[_-]?key['\"]?\s*[:=]\s*['\"]?[A-Za-z0-9_-]{20,}['\"]?"
    "bearer[_-]?token['\"]?\s*[:=]\s*['\"]?[A-Za-z0-9._-]{20,}['\"]?"
    "aws_secret_access_key['\"]?\s*[:=]\s*['\"]?[A-Za-z0-9/+=]{40}['\"]?"
    "access[_-]?token['\"]?\s*[:=]\s*['\"]?[A-Za-z0-9._-]{20,}['\"]?"
)

# Get staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

for FILE in $STAGED_FILES; do
    # Skip binary files
    if file "$FILE" 2>/dev/null | grep -q "binary"; then
        continue
    fi

    # Skip certain directories
    if [[ "$FILE" =~ node_modules|venv|\.venv|\.git|\.next|dist ]]; then
        continue
    fi

    # Get the staged content
    STAGED_CONTENT=$(git show :"$FILE" 2>/dev/null)

    # Check against each pattern
    for PATTERN in "${PATTERNS[@]}"; do
        if echo "$STAGED_CONTENT" | grep -qE "$PATTERN"; then
            if [ "$SECRETS_FOUND" = false ]; then
                echo ""
                echo -e "${RED}❌ SECURITY ERROR: Secrets detected!${NC}"
                SECRETS_FOUND=true
            fi

            echo -e "${RED}  File: $FILE${NC}"
            LINE_NUMS=$(echo "$STAGED_CONTENT" | grep -n -E "$PATTERN" | cut -d: -f1 | head -3)
            echo -e "${YELLOW}  Lines: $LINE_NUMS${NC}"
        fi
    done
done

if [ "$SECRETS_FOUND" = true ]; then
    echo ""
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${RED}⛔ COMMIT BLOCKED: Secrets detected in staged files${NC}"
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo "✅ FIX:"
    echo "  1. Replace secret with: 'your_actual_key_here'"
    echo "  2. Store real key in: .env (git-ignored)"
    echo "  3. Stage fixed files: git add <file>"
    echo "  4. Retry commit: git commit"
    echo ""
    exit 1
fi

echo -e "${GREEN}✅ Security check passed${NC}"

###############################################################################
# PHASE 2: Workflow Protection (Branch Rules)
###############################################################################

echo "🔄 [Phase 2] Checking Workflow Rules..."

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Detect direct commits on develop branch
if [ "$CURRENT_BRANCH" = "develop" ]; then
    echo "⚠️  WARNING: You are attempting to commit directly to develop branch."
    echo ""
    echo "📋 Hybrid Personal-Pro Workflow Rules:"
    echo "  - Personal Mode (1-2 people): feature/SPEC-XXX → main"
    echo "  - Team Mode (3+ people): feature/SPEC-XXX → develop → main"
    echo ""
    echo "✓ Current: Personal Mode → Work on main branch"
    echo ""
    echo "💡 Recommended Actions:"
    echo "  1. git reset HEAD (cancel commit)"
    echo "  2. git checkout main"
    echo "  3. git checkout -b feature/SPEC-XXX"
    echo "  4. Continue your work"
    echo ""
    read -p "Continue anyway? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo -e "${GREEN}✅ Workflow check passed${NC}"
echo ""
exit 0
