#!/usr/bin/env bash
# commit-msg — enforces the mechanically decidable half of commits.md §1.1–1.3.
#
# Install:  ./scripts/setup-hooks.sh, once in every clone.
#
# It checks SHAPE, never meaning. "One concern per commit" and "explain why,
# not what" are not in here and cannot be — commits.md's What-checks-this
# table records them as uncaught on purpose.
#
# Roadmap-aware by design (commits.md §1.2): a repo carrying a ROADMAP.md or
# a .roadmap-counter must use an ID or a category prefix; a repo with neither
# uses `<component>: `, because §1.1's ID mandate has nothing to bind to.

set -u
msg_file="$1"
# git's subject is the whole first paragraph, lines joined by a space, not
# line 1 (commits.md, What checks this, the 1.3 row).
subject=$(awk '/^#/ {next} /^[[:space:]]*$/ {exit} {printf "%s%s", sep, $0; sep=" "}' "$msg_file")

# Ignore merges, reverts, fixups and comment-only aborts.
case "$subject" in
    Merge\ *|Revert\ *|fixup!\ *|squash!\ *|\#*|"") exit 0 ;;
esac

is_num() {
    case "$1" in
        ''|*[!0-9]*) return 1 ;;
    esac
    return 0
}

# The id shape is roadmap-format.md 3.5.1's, not a narrower guess at it. That
# section defines the prefix as [A-Za-z0-9_-] containing at least one ASCII
# letter, admits `Sh-`, `Phase-` and the digit-led `3D_E` by name, and says
# outright that `CL-9` and `PASS-3-1` are well-formed and "a checker built
# from this bullet must not reject them". An earlier `[A-Z][A-Z0-9]*-[0-9]+`
# refused all four, telling a conforming project its own ids were not ids.
id_one='[A-Za-z0-9_-]*[A-Za-z][A-Za-z0-9_-]*-S?[0-9]+(-[0-9]+)*'

# Print a corrected subject, but only a mechanical fix this hook has itself
# run and accepted (CFG-0792: each refusal cost a commit cycle). A fix that
# needs meaning — a missing ID, a long subject, a repeated ID — prints none.
suggest() {
    [ "${ANTS_COMMIT_MSG_NO_SUGGEST:-}" = 1 ] && return 0
    local s try
    # One rewrite per wrong shape: a trailing period; an id written `[ID] -`,
    # `ID —` or `ID:` with odd spacing, rewritten `ID: `; a category with a
    # scope or `!`, `fix(ui)!: `, rewritten `fix: `.
    s=$(printf '%s' "$subject" | sed -E \
        -e 's/\.+$//' \
        -e "s/^\\[?(${id_one})\\]?( +[-—]| *:)? +/\\1: /" \
        -e 's/^(chore|docs|fix)\([^)]*\)!?: /\1: /')
    case "$s" in
        *:\ *) _c=${s%%: *}
            case "$_c" in *[A-Z_.]*)
                # A prefix that is not an ID is a component name, which
                # commits.md § 1.2 writes in lowercase.
                if ! printf '%s' "$_c" | grep -qE "^${id_one}"; then
                    _c=$(printf '%s' "$_c" | tr 'A-Z_' 'a-z-' | sed 's/^\.*//')
                    s="$_c: ${s#*: }"
                fi ;;
            esac ;;
    esac
    [ "$s" = "$subject" ] && return 0
    try=$(mktemp) || return 0
    printf '%s\n' "$s" > "$try"
    ANTS_COMMIT_MSG_NO_SUGGEST=1 bash "$0" "$try" >/dev/null 2>&1 &&
        echo "  accepted: $s" >&2
    rm -f "$try"
}

fail() {
    echo "commit-msg: $1" >&2
    echo "  subject: $subject" >&2
    echo "  rule:    ~/.claude/standards/commits.md §$2" >&2
    suggest
    exit 1
}

# --- §1.3 subject line constraints -------------------------------------
# Length is counted in characters, not bytes — an em dash is one character
# and three bytes, and counting bytes would reject conforming subjects.
#
# NOT `wc -m`, which counts characters only where the LOCALE says so and
# counts bytes under LC_ALL=C (CFG-0142). Hooks inherit the environment of
# whatever invoked git — a CI runner, a cron job, a sudo shell with a reset
# environment — so the C locale is not hypothetical. Measured: the standard's
# own release example measured 29 here and 31 under LC_ALL=C.
#
# Deleting UTF-8 continuation bytes (0x80-0xBF) leaves one byte per character,
# so `wc -c` then counts characters in ANY locale. `LC_ALL=C` on the tr is what
# keeps the byte range meaning bytes.
len=$(printf '%s' "$subject" | LC_ALL=C tr -d '\200-\277' | LC_ALL=C wc -c)
[ "$len" -le 72 ] || fail "subject is $len characters; the limit is 72" "1.3"

case "$subject" in
    *.) fail "subject ends with a period" "1.3" ;;
esac

# --- §1.1 / §1.2 prefix ------------------------------------------------
# Written long-hand on purpose: `[ a ] || [ b ] && c` parses as
# `([ a ] || [ b ]) && c`, which is right here and right by accident.
has_roadmap=no
if [ -f ROADMAP.md ] || [ -f .roadmap-counter ]; then
    has_roadmap=yes
fi

# One id, or a group: a comma-separated list, or a range. A group is for the
# commit that closes several items at once and cannot be split without
# breaking the build (commits.md 1.1). Everything else stays one id.
# id_one is defined above fail(), whose suggestion uses it.
id_form="^${id_one}((, ${id_one})*|\\.\\.[0-9]+): ."
release_form='^[0-9]+\.[0-9]+\.[0-9]+: .'
category_form='^(chore|docs|fix): .'
# `?` and not `*` on the join: commits.md §1.2 caps the ` + ` list at two
# parts.
#
# Both parts take the same segment shape, and a segment may lead with a
# digit: `3d:` is a name §1.2 permits.
_seg='[a-z0-9]+(-[a-z0-9]+)*'
component_form="^${_seg}( \\+ ${_seg})?: ."

if printf '%s' "$subject" | grep -qE "$id_form"; then
    # §1.3 — don't repeat the ID in the description.
    #
    # Whole-token, not substring: `ANTS-2: unrelated to ANTS-21` names a
    # different item and must pass.
    # Check each id of a group separately. Matching the whole prefix would
    # search for "CFG-1, CFG-2" as one string, which never appears; and a
    # range's dots are regex metacharacters, so "CFG-1..5" would match
    # "CFG-1xx5". Every id extracted here is a bare PREFIX-N with none.
    rest=${subject#*: }
    group=${subject%%:*}
    # A range names its members by number alone -- `PROJ-12..14` carries one
    # prefix -- so extracting ids would find only the first. Enumerate every
    # member, so `PROJ-12..14: PROJ-13 retires it` is caught.
    #
    # 10# forces base 10. Zero-padded ids are the common spelling here, and
    # $((0597 + 1)) is an OCTAL parse -- fatal on any digit 8 or 9. The width
    # of the low end is kept, so `CFG-0597..0599` rebuilds zero-padded.
    case "$group" in
        *..*)
            _low_id=${group%%..*}
            _high_num=${group##*..}
            _pre=${_low_id%-*}
            _low_num=${_low_id##*-}
            # A synthesised id (`RETR-S0068`, roadmap-format.md 3.5.1) keeps
            # its `S` on every member the range rebuilds.
            _s=""; case "$_low_num" in S*) _s=S; _low_num=${_low_num#S} ;; esac
            # A range runs between two SINGLE-NUMBER ids. `PASS-3-1..5` names
            # no unambiguous prefix, so refuse the form instead of guessing.
            if [ "$_pre" != "${_pre##*-}" ] && is_num "${_pre##*-}"; then
                fail "a range runs between two single-number ids; a multi-segment scheme uses the comma list" "1.1"
            fi
            group="$group, $_pre-$_s$_high_num"
            if is_num "$_low_num" && is_num "$_high_num"; then
                _i=$((10#$_low_num)); _end=$((10#$_high_num)); _w=${#_low_num}
                # The cap guards against a typo, not a rule: enumerating
                # hundreds would hang the commit. Past it, only the ends.
                [ $((_end - _i)) -le 200 ] && while [ "$_i" -le "$_end" ]; do
                    group="$group, $_pre-$_s$(printf "%0${_w}d" "$_i")"
                    _i=$((_i + 1))
                done
            fi
            ;;
    esac
    for id in $(printf '%s' "$group" | grep -oE "$id_one"); do
        if printf '%s' "$rest" | grep -qE "(^|[^A-Za-z0-9-])$id([^A-Za-z0-9-]|\$)"; then
            fail "the ID is repeated in the description" "1.3"
        fi
    done
elif printf '%s' "$subject" | grep -qE "$release_form|$category_form"; then
    :
elif [ "$has_roadmap" = no ] && printf '%s' "$subject" | grep -qE "$component_form"; then
    :
elif [ "$has_roadmap" = yes ]; then
    fail "no ID or category prefix; this repo has a roadmap, so use '<ID>: ' or one of chore:/docs:/fix:/X.Y.Z:" "1.1"
else
    fail "no prefix; this repo has no roadmap, so use '<component>: '" "1.2"
fi

exit 0
