#!/usr/bin/env bash
#
# commit-msg hook: enforces Conventional Commits v1.0.0
# https://www.conventionalcommits.org/en/v1.0.0/#specification

commit_msg_file="$1"
commit_msg=$(cat "$commit_msg_file")

# Strip lines starting with '#' (comments) and leading/trailing whitespace
msg=$(echo "$commit_msg" | grep -v '^#' | sed '/^$/d' | head -1)

# Conventional Commits pattern:
#   <type>[optional scope][optional !]: <description>
#
# Types from the spec (feat and fix are required; others are conventional)
TYPES="feat|fix|build|chore|ci|docs|perf|refactor|revert|style|test"

PATTERN="^($TYPES)(\([^()]+\))?(!)?: .+"

if ! echo "$msg" | grep -qE "$PATTERN"; then
  echo ""
  echo "ERROR: Commit message does not follow Conventional Commits format."
  echo ""
  echo "  Expected: <type>[(<scope>)][!]: <description>"
  echo ""
  echo "  Types: feat, fix, build, chore, ci, docs, perf, refactor, revert, style, test"
  echo ""
  echo "  Examples:"
  echo "    feat: add new API endpoint"
  echo "    fix(auth): handle token expiry"
  echo "    feat!: drop support for older API versions"
  echo "    chore(deps): update dependencies"
  echo ""
  echo "  Your message: $msg"
  echo ""
  exit 1
fi

exit 0
