#!/bin/sh
# Commit message validation hook
# Place this file in .git/hooks/commit-msg and make it executable:
# chmod +x .git/hooks/commit-msg

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

# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0;m' # No Color

print_error() {
    echo "${RED}❌ $1${NC}"
}

print_warning() {
    echo "${YELLOW}⚠️  $1${NC}"
}

# Conventional Commits format: <type>(<scope>): <subject>
# Example: feat(auth): add Google OAuth login

echo "📝 Validating commit message..."

# Check if message matches Conventional Commits format
PATTERN="^(feat|fix|docs|style|refactor|perf|test|chore|ci|revert)(\(.+\))?: .+"

if ! echo "$COMMIT_MSG" | grep -qE "$PATTERN"; then
    print_error "Commit message does not follow Conventional Commits format"
    echo ""
    echo "Expected format: <type>(<scope>): <subject>"
    echo ""
    echo "Types:"
    echo "  feat:     A new feature"
    echo "  fix:      A bug fix"
    echo "  docs:     Documentation only changes"
    echo "  style:    Code style changes (formatting, etc)"
    echo "  refactor: Code refactoring"
    echo "  perf:     Performance improvements"
    echo "  test:     Adding or updating tests"
    echo "  chore:    Build process or auxiliary tool changes"
    echo "  ci:       CI configuration changes"
    echo ""
    echo "Examples:"
    echo "  feat(auth): add Google OAuth login"
    echo "  fix(ui): resolve layout issue on iPad"
    echo "  docs(readme): update installation steps"
    echo ""
    exit 1
fi

# Extract components
TYPE=$(echo "$COMMIT_MSG" | sed -E 's/^([a-z]+)(\(.+\))?: .+/\1/')
SUBJECT=$(echo "$COMMIT_MSG" | sed -E 's/^[a-z]+(\(.+\))?: (.+)/\2/')

# Check subject length (recommended: 50 chars)
SUBJECT_LENGTH=${#SUBJECT}
if [ "$SUBJECT_LENGTH" -gt 50 ]; then
    print_warning "Subject line is longer than 50 characters ($SUBJECT_LENGTH chars)"
    print_warning "Consider making it more concise"
fi

# Check if subject starts with uppercase (should be lowercase)
if echo "$SUBJECT" | grep -q "^[A-Z]"; then
    print_warning "Subject should start with lowercase letter"
fi

# Check if subject ends with period (should not)
if echo "$SUBJECT" | grep -q "\.$"; then
    print_warning "Subject should not end with a period"
fi

# Check for common mistakes
if echo "$COMMIT_MSG" | grep -qi "WIP\|work in progress\|tmp\|temp"; then
    print_warning "Commit message contains WIP/temp keywords"
    print_warning "Consider completing the work before committing"
fi

# Check for vague messages
VAGUE_PATTERNS="fix|update|change|improve|refactor"
if echo "$SUBJECT" | grep -qiE "^($VAGUE_PATTERNS)$"; then
    print_error "Subject is too vague: '$SUBJECT'"
    print_error "Please provide more specific description"
    echo "Example: Instead of 'fix bug', use 'fix login validation error'"
    exit 1
fi

echo "✅ Commit message is valid"
exit 0
