#!/usr/bin/env bash
# Verifies the commit-msg strip removes AI watermark trailers, keeps everything else,
# and that the dispatcher chains to a repo-local hook.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DISPATCH="$HERE/../hook-dispatch.sh"
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
pass=0; fail=0
ok(){ echo "  PASS: $1"; pass=$((pass+1)); }
no(){ echo "  FAIL: $1"; fail=$((fail+1)); }

# Run the dispatcher as commit-msg against a message file inside a real repo.
git init -q "$WORK/repo"
run_commit_msg(){ # $1=message-file-content -> prints resulting file
  local f="$WORK/msg"; printf '%s' "$1" >"$f"
  ( cd "$WORK/repo" && ln -sf "$DISPATCH" "$WORK/commit-msg" && "$WORK/commit-msg" "$f" )
  cat "$f"
}

got="$(run_commit_msg 'Add feature X

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
')"
[ "$got" = "Add feature X" ] && ok "strips Co-Authored-By Claude + trailing blank" || no "strip claude trailer: got [$got]"

got="$(run_commit_msg 'Fix bug

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
')"
[ "$got" = "Fix bug" ] && ok "strips Generated-with + robot line + coauthor" || no "strip generated block: got [$got]"

got="$(run_commit_msg 'Real change

Co-Authored-By: Alice <alice@example.com>
')"
case "$got" in *"Alice <alice@example.com>"*) ok "keeps a genuine human co-author";; *) no "clobbered human co-author: got [$got]";; esac

got="$(run_commit_msg 'Plain message no trailer')"
[ "$got" = "Plain message no trailer" ] && ok "leaves a plain message untouched" || no "mangled plain msg: got [$got]"

# Chaining: a repo-local commit-msg hook must still run.
mkdir -p "$WORK/repo/.git/hooks"
printf '#!/usr/bin/env bash\necho "LOCAL-RAN" >> "%s/chain-proof"\n' "$WORK" >"$WORK/repo/.git/hooks/commit-msg"
chmod +x "$WORK/repo/.git/hooks/commit-msg"
printf 'msg\nCo-Authored-By: Claude <x@anthropic.com>\n' >"$WORK/cmsg"
( cd "$WORK/repo" && ln -sf "$DISPATCH" "$WORK/commit-msg" && "$WORK/commit-msg" "$WORK/cmsg" )
[ -f "$WORK/chain-proof" ] && grep -q LOCAL-RAN "$WORK/chain-proof" && ok "chains to repo-local commit-msg hook" || no "did not chain to local hook"
grep -q anthropic "$WORK/cmsg" && no "trailer survived before chaining" || ok "trailer stripped before local hook ran"

echo "---- pass=$pass fail=$fail ----"
[ "$fail" -eq 0 ]
