#!/usr/bin/env bash
# Git commit-msg hook: rejects commit messages that don't follow CONVENTIONS.md.
#
# Why: CONVENTIONS.md and CLAUDE.md only describe the format; nothing checked it,
# so older commits ("added node constants", "refactor code") drifted. Git runs
# this hook on every commit, from Claude or from you, and aborts the commit if
# the message is wrong. Your message is kept in .git/COMMIT_EDITMSG to fix up.
#
# Checks:
#   - first line is `<type>(<scope>): <summary>` with a type and optional scope
#     from CONVENTIONS.md, and no period at the end
#   - no AI attribution lines (Co-Authored-By: Claude, "Generated with Claude")
#
# Activate once per clone: git config core.hooksPath .githooks
# Skip in an emergency: git commit --no-verify
#
# Idea taken from the deverenz repo (.githooks/commit-msg).
msg_file="$1"
first_line=$(grep -v '^#' "$msg_file" | head -n1)

# Let git's own merge/revert/fixup messages through.
[[ "$first_line" =~ ^(Merge|Revert|fixup!|squash!) ]] && exit 0

types='feature|bug|enhancement|chore|docs'
scopes='proxmox-infra|k8s-bootstrap|k8s-infra|k8s-apps|monitoring|ci'
pattern="^($types)(\(($scopes)\))?: .*[^.]$"
if ! [[ "$first_line" =~ $pattern ]]; then
  echo "commit-msg: '$first_line'" >&2
  echo "  expected '<type>(<scope>): <summary>' with no trailing period (see CONVENTIONS.md)" >&2
  echo "  types:  ${types//|/ }" >&2
  echo "  scopes: ${scopes//|/ } (optional)" >&2
  exit 1
fi

if grep -qiE '^(Co-Authored-By:.*(claude|anthropic)|.*Generated with \[?Claude)' "$msg_file"; then
  echo "commit-msg: no AI attribution lines (see CLAUDE.md)" >&2
  exit 1
fi
