#!/usr/bin/env node

/**
 * Test Script for Enhanced Humor and Emotional Handling
 * Tests the improved humor detection and emotional response handling
 */

const testCases = [
    {
        name: "Humor Test - Per Fax",
        question: "Wie können Vögel über weite Entfernungen miteinander kommunizieren?",
        answer: "per fax",
        originalTopic: "Wie kommunizieren Vögel?",
        language: "de",
        expectedBehavior: "Should acknowledge humor playfully and redirect to learning"
    },
    {
        name: "Humor Test - Magic",
        question: "How do birds communicate over long distances?",
        answer: "magic and telepathy",
        originalTopic: "How do birds communicate?",
        language: "en",
        expectedBehavior: "Should acknowledge creativity and redirect to learning"
    },
    {
        name: "Emotional Test - Frustration German",
        question: "Was ist UV-Strahlung?",
        answer: "Das ist doof und verstehe ich nicht",
        originalTopic: "Warum bekommt man Sonnenbrand?",
        language: "de",
        expectedBehavior: "Should validate feelings and simplify approach"
    },
    {
        name: "Emotional Test - Frustration English",
        question: "What is UV radiation?",
        answer: "This is stupid and I don't understand",
        originalTopic: "Why do people get sunburned?",
        language: "en",
        expectedBehavior: "Should validate feelings and simplify approach"
    },
    {
        name: "Creative Answer Test",
        question: "Wie könnte man einem Freund eine Nachricht senden?",
        answer: "mit einer brieftaube oder rauchzeichen",
        originalTopic: "Kommunikation",
        language: "de",
        expectedBehavior: "Should acknowledge creativity and connect to real communication"
    },
    {
        name: "Overwhelmed Child Test",
        question: "Was passiert in den Hautzellen bei Sonnenbrand?",
        answer: "Das ist zu kompliziert und macht keinen sinn",
        originalTopic: "Warum bekommt man Sonnenbrand?",
        language: "de",
        expectedBehavior: "Should offer emotional support and simplify"
    }
];

async function testHumorAndEmotionalHandling() {
    console.log('🎭 Testing Enhanced Humor and Emotional Handling\n');
    
    let passedTests = 0;
    let totalTests = testCases.length;
    
    for (let i = 0; i < testCases.length; i++) {
        const testCase = testCases[i];
        console.log(`\n${'='.repeat(60)}`);
        console.log(`TEST ${i + 1}: ${testCase.name}`);
        console.log(`${'='.repeat(60)}`);
        console.log(`Question: "${testCase.question}"`);
        console.log(`Answer: "${testCase.answer}"`);
        console.log(`Expected: ${testCase.expectedBehavior}`);
        console.log(`\nSending request...`);
        
        try {
            const response = await fetch('http://localhost:3002/api/respond-to-answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    answer: testCase.answer,
                    question: testCase.question,
                    originalTopic: testCase.originalTopic,
                    language: testCase.language,
                    sessionId: `test_humor_emotional_${i}`
                })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            if (data.success) {
                console.log(`\n✅ Response received:`);
                console.log(`"${data.response}"`);
                
                // Analyze response for expected behavior
                const aiResponse = data.response.toLowerCase();
                let testPassed = false;
                
                if (testCase.name.includes("Humor")) {
                    // Check if humor is acknowledged
                    const humorAcknowledgment = testCase.language === 'de' 
                        ? ['lustig', 'kreativ', 'witzig', 'haha', 'interessant']
                        : ['funny', 'creative', 'interesting', 'haha', 'clever'];
                    
                    testPassed = humorAcknowledgment.some(word => aiResponse.includes(word));
                    
                    if (testPassed) {
                        console.log(`✅ PASSED: Humor acknowledged appropriately`);
                        passedTests++;
                    } else {
                        console.log(`❌ FAILED: Humor not acknowledged properly`);
                    }
                } else if (testCase.name.includes("Emotional")) {
                    // Check if emotions are validated
                    const emotionalValidation = testCase.language === 'de' 
                        ? ['verstehen', 'okay', 'verständlich', 'empathie', 'unterstützung', 'anders versuchen']
                        : ['understand', 'okay', 'support', 'help', 'try differently', 'completely okay'];
                    
                    testPassed = emotionalValidation.some(phrase => aiResponse.includes(phrase));
                    
                    if (testPassed) {
                        console.log(`✅ PASSED: Emotional validation provided`);
                        passedTests++;
                    } else {
                        console.log(`❌ FAILED: Emotional validation missing`);
                    }
                } else {
                    // General check for appropriate handling
                    testPassed = aiResponse.length > 20; // Basic response check
                    if (testPassed) {
                        console.log(`✅ PASSED: Appropriate response generated`);
                        passedTests++;
                    } else {
                        console.log(`❌ FAILED: Inappropriate or too short response`);
                    }
                }
            } else {
                console.log(`❌ FAILED: ${data.error || 'Unknown error'}`);
            }
        } catch (error) {
            console.log(`❌ FAILED: ${error.message}`);
        }
        
        // Wait between requests
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
    
    console.log(`\n${'='.repeat(60)}`);
    console.log(`🎯 FINAL RESULTS: ${passedTests}/${totalTests} tests passed`);
    console.log(`${'='.repeat(60)}`);
    
    if (passedTests === totalTests) {
        console.log(`🎉 All tests passed! Humor and emotional handling working correctly.`);
    } else {
        console.log(`⚠️  ${totalTests - passedTests} tests failed. Review the implementation.`);
    }
    
    return passedTests === totalTests;
}

// Run tests if this script is executed directly
if (require.main === module) {
    testHumorAndEmotionalHandling().catch(console.error);
}

module.exports = { testHumorAndEmotionalHandling };
