#!/usr/bin/env bash
# Pre-commit hook: block commits containing secrets
# Installed by: cp scripts/pre-commit-secrets .git/hooks/pre-commit
set -euo pipefail

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

ALLOW_LOCKED_DISPATCH_CONFIG_CHANGES="${ALLOW_LOCKED_DISPATCH_CONFIG_CHANGES:-}"

# --- 1. Block .env files from being committed ---
ENV_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^\.(env|env\..*)$' || true)
if [ -n "$ENV_FILES" ]; then
    echo -e "${RED}🚫 BLOCKED: .env file(s) staged for commit:${NC}"
    echo "$ENV_FILES" | sed 's/^/   /'
    echo -e "${YELLOW}   Run: git rm --cached <file> to untrack${NC}"
    exit 1
fi

# --- 2. Block known secret config files ---
SECRET_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^(webex_config\.json|telegram_config\.json)$' || true)
if [ -n "$SECRET_FILES" ]; then
    echo -e "${RED}🚫 BLOCKED: Secret config file(s) staged for commit:${NC}"
    echo "$SECRET_FILES" | sed 's/^/   /'
    echo -e "${YELLOW}   These files contain tokens and should never be committed.${NC}"
    exit 1
fi

# --- 3. Block protected wee-dev / wee-qa dispatch config edits ---
LOCKED_DIFF=$(git diff --cached -- agents.json 2>/dev/null || true)
if [ -n "$LOCKED_DIFF" ] && echo "$LOCKED_DIFF" | grep -qE '^[+-].*"name": "(wee-dev|wee-qa)"|"runtime":|"model":|"vendor":|"locked_notice":'; then
    python3 - <<'PY'
import subprocess
import sys

result = subprocess.run(
    ["git", "show", ":agents.json"],
    capture_output=True,
    text=True,
    check=False,
)
if result.returncode != 0:
    sys.exit(0)

text = result.stdout
required = (
    '"name": "wee-dev"',
    '"runtime": "claude"',
    '"model": "sonnet"',
    '"name": "wee-qa"',
    '"runtime": "codex"',
    '"model": "gpt-5.4"',
)
if not all(item in text for item in required):
    sys.exit(3)
PY
    rc=$?
    if [ "$rc" -eq 3 ] && [ "$ALLOW_LOCKED_DISPATCH_CONFIG_CHANGES" != "1" ]; then
        echo -e "${RED}🚫 BLOCKED: Protected wee-dev/wee-qa dispatch config changed in agents.json${NC}"
        echo -e "${YELLOW}   Locked values:${NC}"
        echo "   wee-dev  => runtime=claude, model=sonnet"
        echo "   wee-qa   => runtime=codex, model=gpt-5.4"
        echo -e "${YELLOW}   If this change is intentional, re-run with:${NC}"
        echo "   ALLOW_LOCKED_DISPATCH_CONFIG_CHANGES=1 git commit ..."
        exit 1
    fi
fi

# --- 4. Pattern-based secret detection on staged changes ---
STAGED_DIFF=$(git diff --cached --diff-filter=ACM -U0 2>/dev/null || true)
if [ -n "$STAGED_DIFF" ]; then
    ISSUES=""

    # Webex bot tokens (base64-ish format with _PF84_ marker)
    if echo "$STAGED_DIFF" | grep -qP '^\+.*[A-Za-z0-9+/]{20,}_PF84_'; then
        ISSUES="${ISSUES}\n   • Webex bot token detected"
    fi

    # Telegram bot tokens (numeric:alphanumeric)
    if echo "$STAGED_DIFF" | grep -qP '^\+.*\d{8,}:AA[A-Za-z0-9_-]{30,}'; then
        ISSUES="${ISSUES}\n   • Telegram bot token detected"
    fi

    # OpenAI API keys
    if echo "$STAGED_DIFF" | grep -qP '^\+.*sk-[a-zA-Z0-9]{20,}'; then
        ISSUES="${ISSUES}\n   • OpenAI API key detected"
    fi

    # Generic high-entropy secrets (API_KEY=, PASSWORD=, SECRET= with real values)
    if echo "$STAGED_DIFF" | grep -qP '^\+.*(API_KEY|SECRET|PASSWORD|TOKEN)\s*=\s*[^\s"'"'"']{12,}' | grep -vqP '(YOUR_|your-|placeholder|example|REDACTED)' 2>/dev/null; then
        ISSUES="${ISSUES}\n   • Possible hardcoded credential detected"
    fi

    if [ -n "$ISSUES" ]; then
        echo -e "${RED}🚫 BLOCKED: Potential secrets in staged changes:${NC}"
        echo -e "$ISSUES"
        echo -e "${YELLOW}   Review your changes and remove secrets before committing.${NC}"
        echo -e "${YELLOW}   To bypass (emergency only): git commit --no-verify${NC}"
        exit 1
    fi
fi

# --- 5. detect-secrets scan (if available) ---
if command -v detect-secrets &>/dev/null; then
    BASELINE=".secrets.baseline"
    if [ -f "$BASELINE" ]; then
        # Scan only staged files against baseline
        STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)
        if [ -n "$STAGED_FILES" ]; then
            if ! git diff --cached --diff-filter=ACM | detect-secrets-hook --baseline "$BASELINE" 2>/dev/null; then
                echo -e "${RED}🚫 BLOCKED: detect-secrets found new secrets not in baseline${NC}"
                echo -e "${YELLOW}   If these are false positives, update baseline:${NC}"
                echo -e "${YELLOW}   detect-secrets scan > .secrets.baseline${NC}"
                exit 1
            fi
        fi
    fi
fi

echo -e "${GREEN}✅ No secrets detected in staged changes${NC}"
