#!/bin/bash
# PreToolUse hook: block destructive git commands
# Place at: ~/.claude/hooks/git-guard.sh
# Make executable: chmod +x ~/.claude/hooks/git-guard.sh

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(d.get('tool_input', {}).get('command', ''))
except:
    print('')
" 2>/dev/null)

# Skip if not a git command
if ! echo "$COMMAND" | grep -q '\bgit\b'; then
    exit 0
fi

REASON=""

# Force-delete local branch (-D, -df, -fd, --delete --force, --force --delete)
if echo "$COMMAND" | grep -qE '\bgit\s+branch\s+(-[a-zA-Z]*D[a-zA-Z]*|-[a-zA-Z]*d[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*d[a-zA-Z]*|.*--delete.*--force|.*--force.*--delete)'; then
    REASON="force-deletes a local branch (git branch -D / -df)"

# Force push (rewrites remote history)
elif echo "$COMMAND" | grep -qE '\bgit\s+push\b.*(\s-f\b|\s--force\b|\s--force-with-lease\b)'; then
    REASON="force-pushes and could rewrite remote history"

# Delete remote branch
elif echo "$COMMAND" | grep -qE '\bgit\s+push\b.*--delete\b|\bgit\s+push\b\s+\S+\s+:\S'; then
    REASON="deletes a remote branch"

# Hard reset (discards commits)
elif echo "$COMMAND" | grep -qE '\bgit\s+reset\s+--hard\b'; then
    REASON="hard-resets and will discard local commits/changes"

# Amend (rewrites history)
elif echo "$COMMAND" | grep -qE '\bgit\s+commit\b.*--amend\b'; then
    REASON="amends a commit and rewrites history"
fi

if [ -n "$REASON" ]; then
    echo "Blocked: this command $REASON."
    echo "Run it manually in your terminal if you're certain."
    exit 1
fi

exit 0
