#!/usr/bin/env bash
# commit-msg hook — optionally append the exact AI co-author identity supplied by
# the invoking environment. The repository must not hard-code or rewrite a model
# identity: doing so produces false attribution whenever tools/providers change.
#
# Usage:
#   OPENRECET_AI_COAUTHOR='Name <email>' git commit ...
#
# Behavior:
#   - unset variable: leave the message untouched;
#   - exact trailer already present: leave it untouched;
#   - other human/AI co-author trailers: preserve them;
#   - invalid/multiline identity: fail rather than corrupt the message.

set -euo pipefail

msg_file="$1"
coauthor="${OPENRECET_AI_COAUTHOR:-}"

if [[ "${SKIP_AI_TRAILER:-0}" == "1" || -z "$coauthor" ]]; then
    exit 0
fi

pattern='^[^<>]+ <[^[:space:]<>]+@[^[:space:]<>]+>$'
if [[ "$coauthor" == *$'\n'* || ! "$coauthor" =~ $pattern ]]; then
    echo "commit-msg: OPENRECET_AI_COAUTHOR must be 'Name <email>' on one line" >&2
    exit 1
fi

trailer="Co-Authored-By: $coauthor"
if grep -Fxiq -- "$trailer" "$msg_file"; then
    exit 0
fi

# Ensure the message ends with a newline, then separate the trailer block.
if [[ -n "$(tail -c1 "$msg_file" 2>/dev/null)" ]]; then
    printf '\n' >> "$msg_file"
fi
last_line="$(grep -v '^#' "$msg_file" | tail -1 || true)"
if [[ -n "$last_line" ]]; then
    printf '\n%s\n' "$trailer" >> "$msg_file"
else
    printf '%s\n' "$trailer" >> "$msg_file"
fi
