#!/bin/bash

# Enhanced commit helper with integrated AI
# Usage: ./commit-helper-ai.sh [--help]

set -e

# Print help and exit if --help is passed
if [[ "$1" == "--help" ]]; then
    echo "Enhanced commit helper with integrated AI"
    echo "Usage: ai-commit-helper [--help]"
    echo "  --help            Show this help message and exit"
    exit 0
fi

# Check if inside a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo "❌ Error: Not inside a git repository. Please run 'git init' first."
    exit 1
fi

# Load AI prompts configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$(dirname "$SCRIPT_DIR")/config"
if [ -f "$CONFIG_DIR/ai-prompts.conf" ]; then
    source "$CONFIG_DIR/ai-prompts.conf"
else
    echo "❌ Error: AI prompts configuration not found at $CONFIG_DIR/ai-prompts.conf"
    exit 1
fi

# Function to generate AI commit message
generate_ai_commit() {
    local files="$1"
    local diff_sample="$2"
    
    if [ -z "$OPENAI_API_KEY" ]; then
        echo "❌ OPENAI_API_KEY not set"
        return 1
    fi
    
    # Set variables for prompt template substitution
    FILES="$files"
    DIFF="$diff_sample"
    
    # Use the centralized prompt from config
    local prompt=$(eval echo "\"$AI_COMMIT_PROMPT\"")

    # Prepare JSON payload using the same safe method as ai-commit.sh
    local json_payload=$(cat << EOF
{
    "model": "$OPENAI_MODEL",
    "messages": [
        {
            "role": "user", 
            "content": $(echo "$prompt" | jq -R -s .)
        }
    ],
    "max_tokens": $OPENAI_MAX_TOKENS,
    "temperature": $OPENAI_TEMPERATURE
}
EOF
)

    # Call OpenAI API
    local response=$(curl -s -X POST "$OPENAI_API_URL" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $OPENAI_API_KEY" \
        -d "$json_payload")
    
    # Check for API errors
    if echo "$response" | jq -e '.error' >/dev/null 2>&1; then
        echo "❌ OpenAI API Error:"
        echo "$response" | jq -r '.error.message'
        return 1
    fi
    
    # Extract message
    local message=$(echo "$response" | jq -r '.choices[0].message.content' 2>/dev/null | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
    
    if [ -z "$message" ] || [ "$message" = "null" ]; then
        echo "❌ Failed to extract commit message"
        return 1
    fi
    
    echo "$message"
    return 0
}

echo "🔍 Analyzing staged changes..."

# Check if there are staged changes
if git diff --cached --quiet; then
    echo "❌ No staged changes found. Use 'git add' first."
    exit 1
fi

echo "📝 Staged changes found:"
git diff --cached --name-only | sed 's/^/  - /'
echo ""

# Show the diff summary
echo "📊 Change summary:"
git diff --cached --stat
echo ""

# Get file list and comprehensive diff for AI
FILTERED_FILES=$(git diff --cached --name-only)
FILES=$(echo "$FILTERED_FILES" | tr '\n' ', ' | sed 's/,$//')

# Create comprehensive change summary for AI context
FILE_COUNT=$(echo "$FILTERED_FILES" | wc -l)
NEW_FILES=$(git diff --cached --name-status | grep "^A" | wc -l)
MODIFIED_FILES=$(git diff --cached --name-status | grep "^M" | wc -l) 
DELETED_FILES=$(git diff --cached --name-status | grep "^D" | wc -l)

DIFF_STATS=$(git diff --cached --stat)
DIFF_SAMPLE=$(git diff --cached --no-color | head -200)

# Combine for comprehensive context
DIFF_CONTEXT=$(cat << EOF
File Summary: $FILE_COUNT files changed
- New files: $NEW_FILES
- Modified files: $MODIFIED_FILES
- Deleted files: $DELETED_FILES

Files: $FILES

Change Statistics:
$DIFF_STATS

Representative Changes:
$DIFF_SAMPLE
EOF
)

# Provide examples and options
echo "💡 Conventional commit format: <type>[optional scope]: <description>"
echo ""
echo "🤖 Options:"
echo "   1. Generate with AI (requires OPENAI_API_KEY)"
echo "   2. Enter manually"
echo ""

read -p "Choose option (1/2): " option

if [[ $option == "1" ]]; then
    echo "🤖 Generating commit message with AI..."
    
    if ai_message=$(generate_ai_commit "$FILES" "$DIFF_CONTEXT"); then
        msg_length=${#ai_message}
        echo "🤖 AI suggested ($msg_length chars): $ai_message"
        
        if [ $msg_length -gt $MAX_COMMIT_LENGTH ]; then
            echo "⚠️  Warning: Message exceeds $MAX_COMMIT_LENGTH characters"
        elif [ $msg_length -gt $WARN_COMMIT_LENGTH ]; then
            echo "⚠️  Note: Message is approaching the $MAX_COMMIT_LENGTH character limit"
        fi
        
        echo ""
        read -p "📝 Use this message, edit it, or enter new one: " user_input
        
        if [ -n "$user_input" ]; then
            commit_msg="$user_input"
        else
            commit_msg="$ai_message"
        fi
    else
        echo "❌ AI generation failed. Please enter manually."
        echo ""
        echo "🏷️  Common types:"
        echo "   feat, fix, docs, chore, ci, refactor, perf, test"
        echo ""
        read -p "💬 Enter your conventional commit message: " commit_msg
    fi
else
    echo "🏷️  Common types:"
    echo "   feat:     New feature"
    echo "   fix:      Bug fix" 
    echo "   docs:     Documentation changes"
    echo "   chore:    Maintenance tasks"
    echo "   ci:       CI/CD changes"
    echo "   refactor: Code refactoring"
    echo ""
    echo "📝 Examples:"
    echo "   feat(smtp): add TLS encryption support"
    echo "   fix(config): resolve virtual domain mapping issue"
    echo "   docs: update installation instructions"
    echo ""
    read -p "💬 Enter your conventional commit message: " commit_msg
fi

# Validate and commit
if [ -n "$commit_msg" ]; then
    msg_length=${#commit_msg}
    echo ""
    echo "📋 Final commit message ($msg_length chars): $commit_msg"
    
    if [ $msg_length -gt $MAX_COMMIT_LENGTH ]; then
        echo "⚠️  Warning: Message exceeds $MAX_COMMIT_LENGTH characters"
    elif [ $msg_length -gt $WARN_COMMIT_LENGTH ]; then
        echo "⚠️  Note: Message is approaching the $MAX_COMMIT_LENGTH character limit"
    fi
    
    read -p "🚀 Proceed with commit? (Y/n): " confirm
    
    if [[ $confirm =~ ^[Nn]$ ]]; then
        echo "❌ Commit cancelled"
        echo "💡 You can copy the message: $commit_msg"
    else
        git commit -m "$commit_msg"
        echo "✅ Committed successfully!"
    fi
else
    echo "❌ No commit message provided"
    exit 1
fi
