#!/bin/bash
# Strip Claude Attribution Hook
#
# This hook automatically removes Claude attribution from commit messages.
# It is designed to be used with lefthook and runs by default.
#
# To disable (opt-out):
#   export PERSUADE_KEEP_ATTRIBUTION=1
#   git commit ...
#
# Or use --no-verify:
#   git commit --no-verify
#
# Attribution removed:
#   - Co-Authored-By: Claude <...>
#   - Co-Authored-By: *@anthropic.com
#   - Generated with [Claude Code]...
#   - Generated with [Claude]...

COMMIT_MSG_FILE=$1

# Check for opt-out
if [ "${PERSUADE_KEEP_ATTRIBUTION:-0}" = "1" ]; then
    exit 0
fi

# Skip merge commits
if grep -qE "^Merge " "$COMMIT_MSG_FILE"; then
    exit 0
fi

# Create temp file for modified message
TEMP_FILE=$(mktemp)
trap 'rm -f "$TEMP_FILE" "$TEMP_FILE.bak"' EXIT

# Remove Claude attribution patterns
# 1. Co-Authored-By: Claude <...> (with whitespace boundaries)
# 2. Co-Authored-By: Claude Code <...>
# 3. Co-Authored-By: *@anthropic.com
# 4. Generated with Claude lines
sed '/Co-[Aa]uthored-[Bb]y:[ 	]*Claude[ 	]*</d' < "$COMMIT_MSG_FILE" | \
    sed '/Co-[Aa]uthored-[Bb]y:[ 	]*Claude[ 	]*Code[ 	]*</d' | \
    sed '/Co-[Aa]uthored-[Bb]y:.*<.*@anthropic\.com>/d' | \
    sed '/Generated with.*[Cc]laude/d' | \
    sed '/^[[:space:]]*$/N;/^\n$/d' \
    > "$TEMP_FILE"

# Remove trailing blank lines
sed -i.bak -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$TEMP_FILE" 2>/dev/null || \
    sed -i '' -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$TEMP_FILE"

# Replace original file
mv "$TEMP_FILE" "$COMMIT_MSG_FILE"

exit 0
