#!/bin/bash

# Comprehensive AI Commit Setup Tester
# Tests all components of the AI commit system
# Usage: ./scripts/test-ai-setup.sh [--create-test-file|--help]

# Don't exit on errors - we want to continue testing and report all issues
set +e

# Print help and exit if --help is passed
if [[ "$1" == "--help" ]]; then
    echo "Comprehensive AI Commit Setup Tester"
    echo "Usage: ai-commit-test [--create-test-file|--help]"
    echo "  --create-test-file   Create a test file and run commit generation test"
    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"
    echo "ℹ️  This is expected if testing the toolkit itself (config will be installed during setup)"
    # Use fallback values for testing
    OPENAI_MODEL="gpt-4o-mini"
    OPENAI_MAX_TOKENS=100
    OPENAI_TEMPERATURE=0.3
    OPENAI_API_URL="https://api.openai.com/v1/chat/completions"
    MAX_COMMIT_LENGTH=100
    AI_COMMIT_PROMPT="Generate a conventional commit message for these changes.

# Example mappings:
- Change: Bump version to 1.2.3 or update package-lock.json
  Commit: chore(release): bump version to 1.2.3
- Change: Add new feature for user login
  Commit: feat(auth): add user login functionality
- Change: Fix broken navbar link
  Commit: fix(navbar): correct broken link

Rules:
- Use the 'chore' type for version bumps, release process changes, or package manager lockfile updates.
- Maximum 100 characters for header (including type, scope, and subject)
- Maximum 72 characters for subject
- Format: type(scope): description
- Include a body only if the primary purpose is not clear from the header
- Body should be wrapped at 72 characters
- Include a footer if there are breaking changes or issues
- Type and scope should be lowercase
- Allowed types: feat, fix, docs, style, refactor, perf, test, chore, build, ci, revert
- Be concise and specific
- Focus on WHAT changed, not HOW

Files changed: \$FILES

Changes:
\$DIFF

Respond with ONLY the commit message, no explanation."
fi

echo "🧪 AI Commit Setup Comprehensive Test"
echo "====================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Test results tracking
TESTS_PASSED=0
TESTS_FAILED=0

# Helper functions
pass_test() {
    echo -e "${GREEN}✅ $1${NC}"
    TESTS_PASSED=$((TESTS_PASSED + 1))
}

fail_test() {
    echo -e "${RED}❌ $1${NC}"
    TESTS_FAILED=$((TESTS_FAILED + 1))
}

warn_test() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

info_test() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

# Test 1: Check dependencies
echo -e "\n${BLUE}📋 Test 1: Dependencies${NC}"
echo "------------------------"

if command -v jq &> /dev/null; then
    pass_test "jq is installed"
else
    fail_test "jq is required but not installed"
    echo "💡 Install with: sudo apt-get install jq"
fi

if command -v curl &> /dev/null; then
    pass_test "curl is installed"
else
    fail_test "curl is required but not installed"
fi

if command -v git &> /dev/null; then
    pass_test "git is installed"
else
    fail_test "git is required but not installed"
fi

if command -v bc &> /dev/null; then
    pass_test "bc is installed"
else
    fail_test "bc is required but not installed"
    echo "💡 Install with: sudo apt-get install bc"
fi

# Test 2: Environment setup
echo -e "\n${BLUE}📋 Test 2: Environment${NC}"
echo "----------------------"

if [ -n "$OPENAI_API_KEY" ]; then
    pass_test "OPENAI_API_KEY is set (${OPENAI_API_KEY:0:8}...)"
else
    fail_test "OPENAI_API_KEY environment variable not set"
    echo "💡 Set it with: export OPENAI_API_KEY='your-api-key-here'"
fi

if [ -f ".env" ]; then
    pass_test ".env file exists"
    if grep -q "OPENAI_API_KEY" .env; then
        pass_test ".env contains OPENAI_API_KEY"
    else
        warn_test ".env exists but doesn't contain OPENAI_API_KEY"
    fi
else
    warn_test ".env file not found (optional)"
fi

# Test 3: Script files
echo -e "\n${BLUE}📋 Test 3: Script Files${NC}"
echo "------------------------"

SCRIPTS=("ai-commit.sh" "commit-helper-ai.sh")
for script in "${SCRIPTS[@]}"; do
    if [ -f "scripts/$script" ]; then
        if [ -x "scripts/$script" ]; then
            pass_test "$script exists and is executable"
        else
            warn_test "$script exists but is not executable"
            echo "💡 Fix with: chmod +x scripts/$script"
        fi
    else
        fail_test "$script not found"
    fi
done

# Test 4: Git repository
echo -e "\n${BLUE}📋 Test 4: Git Repository${NC}"
echo "-------------------------"

if git rev-parse --git-dir > /dev/null 2>&1; then
    pass_test "Inside a git repository"
    
    # Check for commitlint config
    if [ -f "commitlint.config.js" ]; then
        pass_test "commitlint.config.js found"
    else
        warn_test "commitlint.config.js not found"
    fi
    
    # Check for husky
    if [ -f ".husky/commit-msg" ]; then
        pass_test "husky commit-msg hook found"
    else
        warn_test "husky commit-msg hook not found"
    fi
    
    # Check for prepare-commit-msg hook
    if [ -f ".husky/prepare-commit-msg" ]; then
        if [ -x ".husky/prepare-commit-msg" ]; then
            pass_test "husky prepare-commit-msg hook found and executable"
        else
            warn_test "husky prepare-commit-msg hook found but not executable"
            echo "💡 Fix with: chmod +x .husky/prepare-commit-msg"
        fi
    else
        warn_test "husky prepare-commit-msg hook not found (AI auto-generation disabled)"
    fi
else
    fail_test "Not inside a git repository"
fi

# Test 5: API connectivity (if API key is available)
echo -e "\n${BLUE}📋 Test 5: API Connectivity${NC}"
echo "----------------------------"

if [ -n "$OPENAI_API_KEY" ]; then
    info_test "Testing OpenAI API connection..."
    
    # Simple API test
    TEST_RESPONSE=$(curl -s -X POST "https://api.openai.com/v1/chat/completions" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $OPENAI_API_KEY" \
        -d '{
            "model": "gpt-4o-mini",
            "messages": [{"role": "user", "content": "Say hello"}],
            "max_tokens": 10
        }' 2>/dev/null)
    
    if echo "$TEST_RESPONSE" | jq -e '.choices[0].message.content' >/dev/null 2>&1; then
        pass_test "OpenAI API connection successful"
        API_RESPONSE=$(echo "$TEST_RESPONSE" | jq -r '.choices[0].message.content')
        info_test "API Response: $API_RESPONSE"
    elif echo "$TEST_RESPONSE" | jq -e '.error' >/dev/null 2>&1; then
        fail_test "OpenAI API error"
        echo "$TEST_RESPONSE" | jq -r '.error.message'
    else
        fail_test "Unable to connect to OpenAI API"
    fi
else
    warn_test "Skipping API test (no API key)"
fi

# Test 6: Commit message generation (if we can create test changes)
echo -e "\n${BLUE}📋 Test 6: AI Commit Generation${NC}"
echo "--------------------------------"

if [ "$1" = "--create-test-file" ] && [ -n "$OPENAI_API_KEY" ]; then
    info_test "Creating test file for commit generation..."
    
    # Create a test file
    TEST_FILE="AI_COMMIT_TEST_$(date +%s).txt"
    echo "This is a test file for AI commit generation" > "$TEST_FILE"
    echo "Created at: $(date)" >> "$TEST_FILE"
    
    # Stage it
    git add "$TEST_FILE"
    
    info_test "Testing AI commit generation..."
    
    # Test the AI commit generation function
    DIFF=$(git diff --cached --no-color | head -20)
    FILES=$(git diff --cached --name-only | tr '\n' ', ' | sed 's/,$//')
    
    # Use the centralized prompt from config
    PROMPT=$(eval echo "\"$AI_COMMIT_PROMPT\"")

    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
)

    RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $OPENAI_API_KEY" \
        -d "$JSON_PAYLOAD")
    
    if echo "$RESPONSE" | jq -e '.error' >/dev/null 2>&1; then
        fail_test "AI commit generation failed"
        echo "$RESPONSE" | jq -r '.error.message'
    else
        COMMIT_MSG=$(echo "$RESPONSE" | jq -r '.choices[0].message.content' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        
        if [ -n "$COMMIT_MSG" ] && [ "$COMMIT_MSG" != "null" ]; then
            MSG_LENGTH=${#COMMIT_MSG}
            pass_test "AI commit generation successful"
            info_test "Generated message ($MSG_LENGTH chars): $COMMIT_MSG"
            
            if [ $MSG_LENGTH -le $MAX_COMMIT_LENGTH ]; then
                pass_test "Message length is within $MAX_COMMIT_LENGTH character limit"
            else
                warn_test "Message exceeds $MAX_COMMIT_LENGTH characters"
            fi
        else
            fail_test "AI commit generation returned empty message"
        fi
    fi
    
    # Clean up
    git reset HEAD "$TEST_FILE" >/dev/null 2>&1
    rm -f "$TEST_FILE"
    info_test "Test file cleaned up"
    
elif [ -n "$OPENAI_API_KEY" ]; then
    warn_test "Skipping commit generation test (use --create-test-file to test)"
else
    warn_test "Skipping commit generation test (no API key)"
fi

# Test 7: Validate script syntax
echo -e "\n${BLUE}📋 Test 7: Script Syntax${NC}"
echo "-------------------------"

for script in "${SCRIPTS[@]}"; do
    if [ -f "scripts/$script" ]; then
        if bash -n "scripts/$script" 2>/dev/null; then
            pass_test "$script syntax is valid"
        else
            fail_test "$script has syntax errors"
        fi
    fi
done

# Summary
echo -e "\n${BLUE}📊 Test Summary${NC}"
echo "==============="
echo "Tests passed: $TESTS_PASSED"
echo "Tests failed: $TESTS_FAILED"
echo "Total tests: $((TESTS_PASSED + TESTS_FAILED))"

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "\n${GREEN}🎉 All tests passed! AI commit setup is ready.${NC}"
    exit 0
else
    echo -e "\n${RED}⚠️  Some tests failed. Check the output above for details.${NC}"
    exit 1
fi
