#!/bin/bash

set -e

COMMIT_MSG_FILE="$1"
if [ -z "$COMMIT_MSG_FILE" ]; then
    echo "Checking for cache files in staged changes..."
    
    CACHE_FILES=$(git diff --cached --name-only | grep -E "__pycache__|\.pyc$|\.pyo$" || true)
    
    if [ -n "$CACHE_FILES" ]; then
        echo "❌ Attempting to commit Python cache files!"
        echo ""
        echo "Files:"
        echo "$CACHE_FILES"
        echo ""
        echo "Run: bash scripts/clean_cache.sh"
        echo "Or: git reset HEAD <files>"
        exit 1
    fi
    
    echo "✓ No cache files in staged changes"
    exit 0
fi

COMMIT_MSG=$(cat "$COMMIT_MSG_FILE")

if ! echo "$COMMIT_MSG" | grep -qE "^(feat|fix|docs|style|refactor|test|chore): [a-z].{0,49}$"; then
    echo "❌ Invalid commit message format!"
    echo ""
    echo "Current message: $COMMIT_MSG"
    echo ""
    echo "Expected format: <type>: <short description>"
    echo ""
    echo "Types:"
    echo "  feat     - New feature"
    echo "  fix      - Bug fix"
    echo "  docs     - Documentation"
    echo "  style    - Code style"
    echo "  refactor - Refactoring"
    echo "  test     - Tests"
    echo "  chore    - Maintenance"
    echo ""
    echo "Rules:"
    echo "  - Max 50 characters"
    echo "  - Lowercase after type"
    echo "  - Imperative mood (add, not added)"
    echo "  - No period at end"
    echo ""
    echo "Good examples:"
    echo "  feat: add user authentication"
    echo "  fix: resolve database timeout"
    echo "  docs: update API docs"
    echo ""
    exit 1
fi

if echo "$COMMIT_MSG" | grep -qE "\.$"; then
    echo "❌ Commit message should not end with a period"
    exit 1
fi

echo "✓ Commit message valid: $COMMIT_MSG"
exit 0
