#!/bin/bash
# Commit message validation hook
# Validates conventional commit format
# Install: ./scripts/setup-hooks.sh

set -e

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

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

# Conventional commit pattern:
# type(scope): description
# Types: feat, fix, docs, style, refactor, test, chore, perf, ci, build, revert
PATTERN='^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\([a-z0-9-]+\))?: .{1,100}$'

# Also allow merge commits and WIP commits
if echo "$COMMIT_MSG" | grep -qE "^(Merge|WIP|fixup!|squash!)"; then
    exit 0
fi

# Check first line of commit message
FIRST_LINE=$(echo "$COMMIT_MSG" | head -n1)

if ! echo "$FIRST_LINE" | grep -qE "$PATTERN"; then
    echo -e "${RED}ERROR: Invalid commit message format${NC}"
    echo ""
    echo "Expected format: type(scope): description"
    echo ""
    echo "Valid types:"
    echo "  feat     - A new feature"
    echo "  fix      - A bug fix"
    echo "  docs     - Documentation changes"
    echo "  style    - Code style changes (formatting, etc.)"
    echo "  refactor - Code refactoring"
    echo "  test     - Adding or updating tests"
    echo "  chore    - Maintenance tasks"
    echo "  perf     - Performance improvements"
    echo "  ci       - CI/CD changes"
    echo "  build    - Build system changes"
    echo "  revert   - Reverting changes"
    echo ""
    echo "Examples:"
    echo "  feat(auth): add JWT authentication"
    echo "  fix(api): handle null response"
    echo "  docs: update README"
    echo ""
    echo "Your message: $FIRST_LINE"
    exit 1
fi

echo -e "${GREEN}Commit message format is valid${NC}"
exit 0
