#!/usr/bin/env bash
# aTool - hooks/git/commit-msg
# Conventional Commits validation against the REAL commit message file.
# More reliable than command-line parsing: heredoc/editor messages all pass
# through here. Self-contained — no jq / no aTool lib dependencies.
#
# Escape hatch: ATOOL_SKIP_GITHOOKS=1 git commit ...   (or git commit --no-verify)
set -euo pipefail

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

MSG_FILE="${1:-}"
if [[ -z "$MSG_FILE" || ! -f "$MSG_FILE" ]]; then
    exit 0
fi

FIRST_LINE=$(head -n 1 "$MSG_FILE" | tr -d '\r')
if [[ -z "$FIRST_LINE" ]]; then
    exit 0  # empty message is rejected by git itself
fi

# Auto-generated message shapes are exempt
case "$FIRST_LINE" in
    Merge\ *|Revert\ *|fixup!*|squash!*) exit 0 ;;
esac

CONVENTIONAL_PATTERN='^(feat|fix|docs|test|refactor|chore|style|perf|build|ci|revert|release)(\([^)]+\))?!?: .+'
if printf '%s' "$FIRST_LINE" | grep -qE "$CONVENTIONAL_PATTERN"; then
    exit 0
fi

{
    echo "[aTool commit-msg] REJECTED: message does not follow Conventional Commits:"
    echo "  '${FIRST_LINE}'"
    echo ""
    echo "  Expected: <type>[(scope)][!]: <description>"
    echo "  Types:    feat fix docs test refactor chore style perf build ci revert release"
    echo "  Examples: feat(auth): add SSO login"
    echo "            fix: handle empty staged file list"
    echo ""
    echo "  Bypass once with: ATOOL_SKIP_GITHOOKS=1 git commit ..."
} >&2
exit 1
