#!/usr/bin/env bash
#
# commit-msg: enforce the project's commit subject style.
#
# The subject (first line) MUST be:   VERB - Short description
#   - VERB : an ALL-CAPS verb, >= 3 letters
#            (e.g. ADDED, FIXED, STYLED, DOCUMENTED, CLEANED, REVERTED,
#             CONFIGURED, IMPROVED, POLISHED, REMOVED, RENAMED, REFACTORED)
#   - then " - " (space hyphen space)
#   - then a description (capitalized, imperative, no trailing period).
#
# Good:
#   FIXED - Load .env in drizzle.config so drizzle-kit targets the right DB
#   STYLED - Turn the admin portfolio overview into a professional table
#
# Bad (rejected):
#   Flatten portfolio category routes to /portfolio/[slug]   (no VERB prefix)
#   feat(hero): add ambient backdrop                          (wrong style)
#
# Install once:   git config core.hooksPath .githooks
# Emergency skip: git commit --no-verify
#
set -euo pipefail

msg_file="$1"

# First non-empty, non-comment line = the subject.
subject="$(grep -vE '^[[:space:]]*#' "$msg_file" | grep -vE '^[[:space:]]*$' | head -n1 || true)"

# Let git's own housekeeping commits through untouched.
case "$subject" in
  Merge\ * | Revert\ * | fixup!\ * | squash!\ *) exit 0 ;;
esac

pattern='^[A-Z]{3,} - .+'
if [[ ! "$subject" =~ $pattern ]]; then
  cat >&2 <<EOF

✗ commit rejected: subject does not match the project style.

  Required:  VERB - Short description
  Example:   FIXED - Load .env so drizzle-kit targets the right DB

  Your subject was:
    ${subject:-(empty)}

  VERB must be ALL-CAPS (>= 3 letters), then " - ", then the description.
  (Emergency skip: git commit --no-verify)

EOF
  exit 1
fi
