#!/usr/bin/env bash
# Block AI signatures and validate the Conventional Commits header.
# Enable with: git config core.hooksPath .githooks
# (zentao install-hooks does this automatically)

msg_file="$1"
msg=$(cat "$msg_file")

# 1) Block AI signatures / auto-generated markers
if echo "$msg" | grep -qiE "(generated with claude|co-authored-by:[[:space:]]*claude|co-authored-by:[[:space:]]*.*noreply@anthropic|🤖|generated by ai|claude assisted|ai assisted)"; then
  echo "ERROR: commit message contains an AI signature, blocked."
  echo
  echo "Matched fragment:"
  echo "$msg" | grep -iE "(generated with claude|co-authored-by|🤖|AI|claude)" | head -3
  echo
  echo "Remove it and re-commit."
  exit 1
fi

# 2) Conventional Commits header: <type>(<scope>)?: <subject>
first_line=$(echo "$msg" | head -n 1)

# Let Merge / Revert pass through
if echo "$first_line" | grep -qE "^(Merge|Revert)"; then
  exit 0
fi

if ! echo "$first_line" | grep -qE "^(feat|fix|docs|style|refactor|test|chore|perf|build|ci)(\([a-z0-9_-]+\))?!?: .+"; then
  echo "ERROR: commit header does not match Conventional Commits."
  echo
  echo "Current: $first_line"
  echo
  echo "Expected: <type>(<scope>): <subject>"
  echo "Allowed types: feat, fix, docs, style, refactor, test, chore, perf, build, ci"
  echo "Example:       fix(auth): handle expired login token"
  exit 1
fi

# 3) Optional: require every commit to carry a ZenTao bug reference [ZT#<id>].
#    Disabled by default; uncomment to enforce.
# if ! echo "$msg" | grep -qE "\[ZT#[0-9]+\]"; then
#   echo "ERROR: commit message is missing the ZenTao bug reference [ZT#<id>]"
#   echo "       Suggested placement: end of subject or in the body, e.g. fix(auth): handle expired login token [ZT#12345]"
#   exit 1
# fi

exit 0
