#!/usr/bin/env bash
set -euo pipefail

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

RED='\033[0;31m'
NC='\033[0m'

# Allow merge commits
if echo "$COMMIT_MSG" | grep -qE '^Merge branch'; then
    exit 0
fi

# Conventional commit format: type(scope): description
# Allowed types
PATTERN='^(feat|fix|chore|docs|refactor|test|style|perf|ci|build|revert)(\([a-zA-Z0-9_-]+\))?!?: .+$'
LENGTH_LIMIT=72

if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
    echo ""
    echo -e "${RED}✗ Invalid commit message format.${NC}"
    echo ""
    echo "Format: type(scope): description"
    echo ""
    echo "Allowed types:"
    echo "  feat     — New feature"
    echo "  fix      — Bug fix"
    echo "  chore    — Maintenance/tooling"
    echo "  docs     — Documentation"
    echo "  refactor — Code change with no behavior change"
    echo "  test     — Adding/updating tests"
    echo "  style    — Formatting (no logic change)"
    echo "  perf     — Performance improvement"
    echo "  ci       — CI/CD changes"
    echo "  build    — Build system changes"
    echo "  revert   — Revert a previous commit"
    echo ""
    echo "Examples:"
    echo "  feat(auth): add OAuth login flow"
    echo "  fix(api): handle null user in profile endpoint"
    echo "  refactor(db): extract query builder to separate module"
    echo "  feat(api)!: breaking change to endpoint structure"
    echo ""
    echo "Your commit message was:"
    echo "  $COMMIT_MSG"
    exit 1
fi

# Check first line length
FIRST_LINE=$(echo "$COMMIT_MSG" | head -n1)
if [ ${#FIRST_LINE} -gt $LENGTH_LIMIT ]; then
    echo ""
    echo -e "${RED}✗ First line exceeds $LENGTH_LIMIT characters (${#FIRST_LINE}).${NC}"
    echo "  Keep the subject line concise."
    exit 1
fi

exit 0
