#!/bin/sh

set -eu

MSG_FILE="$1"
FIRST_LINE="$(sed -n '1p' "$MSG_FILE" | tr -d '\r')"

# Allow Git-generated merge commits and revert commits to pass through.
case "$FIRST_LINE" in
  Merge\ *|Revert\ \"*)
    exit 0
    ;;
esac

PATTERN='^(feat|feat-wip|fix|docs|typo|style|refactor|perf|optimize|test|build|ci|chore|revert)\([a-z][a-z0-9-]*\): .+$'

if printf '%s\n' "$FIRST_LINE" | grep -Eq "$PATTERN"; then
  exit 0
fi

cat <<'EOF' >&2
ERROR: commit message must follow Conventional Commits.

Required format:
  type(scope): 描述

Examples:
  fix(system): 修复组织树查询空指针问题
  refactor(framework): 拆分权限上下文装配逻辑
  docs(other): 补充后端提交规范说明

Allowed types:
  feat, feat-wip, fix, docs, typo, style, refactor, perf,
  optimize, test, build, ci, chore, revert

Tip:
  优先使用贴近模块的 scope，例如 system、gateway、framework、security、sql、deps、other。
EOF

exit 1
