#!/bin/sh
# Append Co-Authored-By trailer identifying the AI tool that made the commit.
# Replaces the old [client] prefix pattern (US-INFRA-003).
# Detection order: process tree → env vars → git config → skip

COMMIT_MSG_FILE=$1
FIRST_LINE=$(head -1 "$COMMIT_MSG_FILE")

# Skip merge commits
echo "$FIRST_LINE" | grep -qE "^Merge" && exit 0

# ─── Detect AI client ──────────────────────────────────────────────────────
detect_ai_client() {
  # 1. Walk the process tree — innermost matching process wins
  pid=$$
  depth=0
  while [ "$pid" -gt 1 ] && [ "$depth" -lt 15 ]; do
    cmd=$(ps -p "$pid" -o comm= 2>/dev/null | tr '[:upper:]' '[:lower:]')
    case "$cmd" in
      *claude*) echo "Claude Code <noreply@anthropic.com>"     ; return ;;
      *pi*)     echo "pi <pi@agent>"                           ; return ;;
      *kimi*)   echo "Kimi <kimi@agent>"                       ; return ;;
      *gemini*) echo "Gemini <gemini@agent>"                   ; return ;;
      *codex*)  echo "Codex <codex@agent>"                     ; return ;;
      *cursor*) echo "Cursor <cursor@agent>"                   ; return ;;
    esac
    ppid=$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d ' ')
    [ "$ppid" = "$pid" ] && break
    pid=$ppid
    depth=$((depth + 1))
  done

  # 2. Env var fallback
  [ -n "$CLAUDECODE" ]       && echo "Claude Code <noreply@anthropic.com>" && return
  [ -n "$PI_AGENT" ]         && echo "pi <pi@agent>"                        && return
  [ -n "$KIMI_CLI" ]         && echo "Kimi <kimi@agent>"                    && return
  [ -n "$GEMINI_CLI_TOOL" ]  && echo "Gemini <gemini@agent>"                && return
  [ -n "$CODEX_CLI" ]        && echo "Codex <codex@agent>"                  && return
  [ -n "$CURSOR_TRACE" ]     && echo "Cursor <cursor@agent>"                && return

  # 3. Per-repo or global git config
  git config --get commit.aiClient 2>/dev/null && return

  # 4. Not an AI commit — no trailer
  echo ""
}

COAUTHOR=$(detect_ai_client)

# Append Co-Authored-By trailer if an AI client was detected
# and no Co-Authored-By trailer already exists (idempotent)
if [ -n "$COAUTHOR" ] && ! grep -q "^Co-Authored-By:" "$COMMIT_MSG_FILE"; then
  printf '\nCo-Authored-By: %s\n' "$COAUTHOR" >> "$COMMIT_MSG_FILE"
fi
