#!/bin/sh
# Defence-in-depth: reject pushes containing AI attribution trailers,
# generation footers, or AI author emails. Catches commits that bypassed
# `commit-msg` (--no-verify, imported history, commits made from other
# machines). Installed via `just install-hooks`.

zero='0000000000000000000000000000000000000000'
ai_coauthor='^[[:space:]]*Co-authored-by:[[:space:]]*(Copilot|Claude|Gemini|ChatGPT|GPT-|Codex|Cursor|Windsurf|Devin|aider|Bard|Llama)'
ai_noreply='^[[:space:]]*Co-authored-by:.*<[^>]*(anthropic\.com|openai\.com)'
ai_footer='(Generated (with|by) (\[?Claude|Copilot|Cursor|aider)|Co-generated with)'
ai_author_email='(copilot@|noreply@anthropic\.com|Copilot@users\.noreply\.github\.com)'

fail=0
while read -r local_ref local_sha remote_ref remote_sha; do
    [ "$local_sha" = "$zero" ] && continue
    if [ "$remote_sha" = "$zero" ]; then
        range=$(git rev-list "$local_sha" --not --remotes)
    else
        range=$(git rev-list "$remote_sha..$local_sha")
    fi
    for sha in $range; do
        msg=$(git log -1 --format='%B' "$sha")
        email=$(git log -1 --format='%ae' "$sha")
        if printf '%s\n' "$msg" | grep -Eqi "$ai_coauthor" \
        || printf '%s\n' "$msg" | grep -Eqi "$ai_noreply"  \
        || printf '%s\n' "$msg" | grep -Eqi "$ai_footer"; then
            echo "pre-push: $sha has an AI attribution trailer"
            fail=1
        fi
        if printf '%s\n' "$email" | grep -Eqi "$ai_author_email"; then
            echo "pre-push: $sha has an AI author email: $email"
            fail=1
        fi
    done
done

if [ "$fail" -ne 0 ]; then
    echo "pre-push blocked. Rewrite the offending commits before pushing."
    exit 1
fi
exit 0
