# AI-powered prepare-commit-msg hook
# Automatically generates commit messages using OpenAI API

# Debug: Log that hook is running
echo "🐕 Husky prepare-commit-msg hook starting..." >> /tmp/husky-debug.log
echo "Arguments: $@" >> /tmp/husky-debug.log
echo "Commit file: $1" >> /tmp/husky-debug.log

# Only run for regular commits (not merge, rebase, squash, amend, etc.)
# $2 values: merge=merge commit, squash=squash commit, commit=amend/reuse, 
#           message=user provided message, template=using template
case "$2" in
    merge|squash|message|template) 
        echo "🔄 Skipping AI generation for $2 commit" >> /tmp/husky-debug.log
        exit 0 
        ;;
    commit)
        # This is git commit --amend, skip AI generation
        echo "🔄 Skipping AI generation for amend commit" >> /tmp/husky-debug.log
        exit 0
        ;;
esac

echo "📋 Source: '$2', proceeding with AI generation" >> /tmp/husky-debug.log

# Skip if message file already has actual content (not just template comments)
if [ -s "$1" ]; then
    # Check if there's any non-comment, non-empty line
    if grep -q '^[^#[:space:]]' "$1"; then
        echo "📝 Commit message already exists, skipping AI generation" >> /tmp/husky-debug.log
        exit 0
    fi
fi

# Check if we have staged changes
if git diff --cached --quiet; then
    echo "📝 No staged changes, using manual input" >> /tmp/husky-debug.log
    exit 0
fi

echo "🤖 Generating AI commit message..." >> /tmp/husky-debug.log

# Check if we can use AI (API key available, dependencies present)
if [ -z "$OPENAI_API_KEY" ]; then
    echo "⚠️  OPENAI_API_KEY not set, falling back to manual input" >> /tmp/husky-debug.log
    echo "# Enter conventional commit message" > "$1"
    echo "# Format: type(scope): description" >> "$1"
    echo "#" >> "$1"
    echo "# Types: feat, fix, docs, style, refactor, perf, test, chore, build, ci" >> "$1"
    echo "# Files changed: $(git diff --cached --name-only | tr '\n' ' ')" >> "$1"
    exit 0
fi

if ! command -v jq >/dev/null 2>&1; then
    echo "⚠️  jq not found, falling back to manual input" >> /tmp/husky-debug.log
    echo "# Enter conventional commit message" > "$1"
    echo "# Format: type(scope): description" >> "$1"
    exit 0
fi

# Try to generate AI commit message with timeout
echo "🔄 Calling AI script..." >> /tmp/husky-debug.log
if AI_MSG=$(timeout 15s npx ai-commit --generate-only 2>>/tmp/husky-debug.log); then
    echo "🔄 AI script returned: '$AI_MSG'" >> /tmp/husky-debug.log
    # Validate the message
    if [ -n "$AI_MSG" ] && [ "$AI_MSG" != "null" ]; then
        MSG_LENGTH=${#AI_MSG}
        echo "✅ AI-generated commit message ($MSG_LENGTH chars): $AI_MSG" >> /tmp/husky-debug.log
        
        # Write the AI-generated message to the commit file
        echo "$AI_MSG" > "$1"
        echo "" >> "$1"
        echo "# AI-generated commit message above. Edit as needed." >> "$1"
        echo "# Length: $MSG_LENGTH characters" >> "$1"
        if [ $MSG_LENGTH -gt 72 ]; then
            echo "# ⚠️  Warning: Message exceeds 72 characters" >> "$1"
        fi
        echo "# Files changed: $(git diff --cached --name-only | tr '\n' ' ')" >> "$1"
        echo "# Generated at: $(date)" >> "$1"
        
        exit 0
    else
        echo "❌ AI script returned empty or null result" >> /tmp/husky-debug.log
    fi
else
    echo "❌ AI script failed or timed out" >> /tmp/husky-debug.log
fi

# Fallback if AI generation fails
echo "⚠️  AI generation failed, using manual template" >> /tmp/husky-debug.log
echo "# Enter conventional commit message" > "$1"
echo "# Format: type(scope): description" >> "$1"
echo "#" >> "$1"
echo "# Types: feat, fix, docs, style, refactor, perf, test, chore, build, ci" >> "$1"
echo "# Files changed: $(git diff --cached --name-only | tr '\n' ' ')" >> "$1"
echo "# AI generation failed - please enter manually" >> "$1"
