#!/bin/bash

# Commit message validation script
# Validates that commit messages follow the Gitmoji convention

set -e

# Check if commit message file is provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 <commit-message-file>"
    echo "Example: $0 .git/COMMIT_EDITMSG"
    exit 1
fi

COMMIT_MSG_FILE="$1"

# Check if file exists
if [ ! -f "$COMMIT_MSG_FILE" ]; then
    echo "Error: File $COMMIT_MSG_FILE not found"
    exit 1
fi

# Read first line of commit message
FIRST_LINE=$(head -n 1 "$COMMIT_MSG_FILE")

# Gitmoji pattern - check for any gitmoji at the start
GITMOJI_PATTERN='^[[:space:]]*[🎨✨🐛📝🔧♻️🚀🔒📦🔥🐧🍎🪟🤖🧪📈🌐⚡]'

# Simpler validation - check for emoji followed by type:description
# This avoids complex regex issues with emoji characters

echo "Validating commit message: $FIRST_LINE"

# Check for gitmoji (any emoji character at start)
if ! echo "$FIRST_LINE" | grep -q '^[[:space:]]*[^[:alnum:]]'; then
    echo "❌ Error: Missing gitmoji at start of commit message"
    echo "   Expected: ✨ 🐛 📝 ♻️ 🧪 🔧 etc."
    echo "   Got: $FIRST_LINE"
    exit 1
fi

# Check for type:description format (emoji followed by word and colon)
if ! echo "$FIRST_LINE" | grep -qE '^[[:space:]]*[^[:alnum:]][[:space:]]+[a-z_]+:'; then
    echo "❌ Error: Invalid commit message format"
    echo "   Expected: <gitmoji> <type>: <description>"
    echo "   Example: ✨ feat: add new feature"
    echo "   Got: $FIRST_LINE"
    exit 1
fi

# Check first line length (should be < 50 chars)
FIRST_LINE_LENGTH=${#FIRST_LINE}
if [ $FIRST_LINE_LENGTH -gt 50 ]; then
    echo "⚠️  Warning: First line is $FIRST_LINE_LENGTH characters (recommended max: 50)"
    echo "   Consider: '$FIRST_LINE'"
fi

# Extract gitmoji and type (simplified to avoid emoji regex issues)
GITMOJI=$(echo "$FIRST_LINE" | grep -o "^[^[:alnum:]]")
TYPE=$(echo "$FIRST_LINE" | sed -E 's/^[^[:alnum:]][[:space:]]*([a-z_]+):.*/\1/')

echo "✅ Valid commit message format"
echo "   Gitmoji: $GITMOJI"
echo "   Type: $TYPE"
echo "   Description: $(echo "$FIRST_LINE" | sed 's/^[^[:alnum:]][[:space:]]*[a-z_]+: //')"

exit 0