#!/bin/bash
# ABOUTME: Git commit-msg hook to enforce two-line commit message format
# ABOUTME: Prevents verbose commit messages and AI-generated attribution

set -e

COMMIT_MSG_FILE=$1

# Read the commit message
commit_msg=$(cat "$COMMIT_MSG_FILE")

# Remove comments (lines starting with #)
commit_msg_clean=$(echo "$commit_msg" | grep -v '^#' || true)

# Count non-empty lines
line_count=$(echo "$commit_msg_clean" | grep -v '^$' | wc -l | tr -d ' ')

# Get first line
first_line=$(echo "$commit_msg_clean" | head -1)

# Check for AI-generated signatures
if echo "$commit_msg" | grep -qE "🤖|Generated with \[Claude|Co-Authored-By: Claude|Generated by AI|AI-assisted|Created with Claude|Generated with Claude Code"; then
    echo "❌ ERROR: AI-generated commit message detected!"
    echo ""
    echo "Found AI signature in commit message. Please write a proper commit message without:"
    echo "  - 🤖 emoji"
    echo "  - 'Generated with [Claude Code]' or similar"
    echo "  - 'Co-Authored-By: Claude' or other AI attribution"
    echo ""
    exit 1
fi

# Validate format: must be 1-2 non-empty lines only
if [ "$line_count" -eq 0 ]; then
    echo "❌ ERROR: Empty commit message!"
    echo ""
    echo "Please provide a commit message."
    exit 1
fi

if [ "$line_count" -gt 2 ]; then
    echo "❌ ERROR: Commit message too long!"
    echo ""
    echo "Found $line_count lines. Maximum allowed: 2 lines."
    echo ""
    echo "Correct format:"
    echo "   Line 1: Brief summary (50-72 chars recommended)"
    echo "   Line 2: Optional detailed description (if needed)"
    echo ""
    echo "Your commit message:"
    echo "$commit_msg_clean" | head -5 | sed 's/^/   /'
    if [ "$line_count" -gt 5 ]; then
        echo "   ... ($((line_count - 5)) more lines)"
    fi
    echo ""
    exit 1
fi

# Validate first line length (recommended: 50-72 chars, max: 100)
first_line_length=${#first_line}
if [ "$first_line_length" -gt 100 ]; then
    echo "❌ ERROR: First line too long!"
    echo ""
    echo "First line is $first_line_length characters. Maximum: 100 characters."
    echo ""
    echo "Your first line:"
    echo "   $first_line"
    echo ""
    exit 1
fi

# Validate first line starts with conventional commit type (required)
if ! echo "$first_line" | grep -qE '^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\(.+\))?: '; then
    echo "ERROR: Commit message must use conventional commit format"
    echo ""
    echo "Required format: type(scope): description"
    echo "Examples:"
    echo "  feat: add user authentication"
    echo "  fix: resolve database connection issue"
    echo "  docs: update API documentation"
    echo ""
    echo "Your first line:"
    echo "   $first_line"
    echo ""
    exit 1
fi

echo "Commit message format valid ($line_count line(s))"
exit 0
