#!/usr/bin/env bash
# core/hooks/commit-msg — PhaseOps core commit-msg hook
#
# Generic structural checks on the commit message. Stays ecosystem-agnostic:
#   - reject empty subject
#   - warn on very long subject (>100 chars) — does not block
#
# Adapter overlays (e.g. WordPress "Phase [LETTER]" suffix enforcement)
# live under adapters/<name>/hooks/commit-msg and are appended by
# `phaseops init`.
#
# Receives the commit message file path as $1.
# Escape hatch: PHASEOPS_NO_COMMITMSG=1 git commit ...

set -euo pipefail

if [ "${PHASEOPS_NO_COMMITMSG:-0}" = "1" ]; then
  exit 0
fi

msg_file="${1:-}"
[ -z "$msg_file" ] && exit 0
[ ! -f "$msg_file" ] && exit 0

subject=$(awk 'BEGIN{found=0} /^[^#]/ && NF>0 && !found {print; found=1}' "$msg_file")

# Merge / Revert always exempt
case "$subject" in
  "Merge "*) exit 0 ;;
  "Revert "*) exit 0 ;;
esac

if [ -z "$subject" ]; then
  echo "ERROR: commit subject is empty." >&2
  exit 1
fi

# Soft warning only — operators may have legitimate long subjects.
subject_len=${#subject}
if [ "$subject_len" -gt 100 ]; then
  echo "WARN: commit subject is ${subject_len} chars (>100). Consider shortening." >&2
fi

# Adapter hooks (if any) are appended below by `phaseops init`.
# ---- ADAPTER HOOKS APPENDED BELOW ----
exit 0
