#!/bin/bash
#==============================================================================
# commit-msg hook
# Conventional Commits 형식 검증 (한/영 혼용 지원)
#==============================================================================
export LC_ALL=en_US.UTF-8 2>/dev/null || export LC_ALL=C.UTF-8 2>/dev/null || true

COMMIT_MSG_FILE="$1"
COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

# Merge 커밋은 검증 건너뜀
if echo "$COMMIT_MSG" | head -1 | grep -qE "^Merge "; then
    exit 0
fi

# Revert 커밋은 검증 건너뜀
if echo "$COMMIT_MSG" | head -1 | grep -qE "^Revert "; then
    exit 0
fi

# Conventional Commits 정규식
# type(scope): subject
# - type: feat|fix|docs|style|refactor|test|chore|ci|perf (필수)
# - scope: 영문, 숫자, 한글, 점, 밑줄, 하이픈 허용 (선택)
# - subject: 1~72자, 한/영 혼용 허용 (필수)
PATTERN='^(feat|fix|docs|style|refactor|test|chore|ci|perf)(\([a-zA-Z0-9가-힣._-]+\))?: .{1,72}$'

FIRST_LINE=$(head -1 "$COMMIT_MSG_FILE")

if ! echo "$FIRST_LINE" | grep -qE "$PATTERN"; then
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║  커밋 메시지가 Conventional Commits 형식에 맞지 않습니다   ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    echo "  올바른 형식: type(scope): subject"
    echo ""
    echo "  type (필수):"
    echo "    feat     — 새로운 기능"
    echo "    fix      — 버그 수정"
    echo "    docs     — 문서 변경"
    echo "    style    — 코드 포맷팅"
    echo "    refactor — 리팩토링"
    echo "    test     — 테스트"
    echo "    chore    — 빌드/설정 변경"
    echo "    ci       — CI/CD 변경"
    echo "    perf     — 성능 개선"
    echo ""
    echo "  scope (선택): 한/영 모두 가능"
    echo "  subject (필수): 1~72자, 한/영 모두 가능"
    echo ""
    echo "  예시:"
    echo "    feat(auth): JWT 기반 로그인 구현"
    echo "    fix(배치): 야간 배치 타임아웃 수정"
    echo "    docs: README 업데이트"
    echo "    chore: Gradle 의존성 업데이트"
    echo ""
    echo "  현재 메시지: $FIRST_LINE"
    echo ""
    exit 1
fi
