// Comprehensive test script to verify all KidsAI improvements
const fetch = require('node-fetch');

const BASE_URL = 'http://localhost:3002';

async function runAllTests() {
    console.log('🧪 Running comprehensive KidsAI tests...\n');
    
    let passedTests = 0;
    let totalTests = 0;
    
    // Test 1: Original "nein" bug fix
    console.log('🔍 TEST 1: "Nein" response handling');
    totalTests++;
    try {
        const response = await fetch(`${BASE_URL}/api/respond-to-answer`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                answer: "nein",
                question: "Weißt du, wie das Magnetfeld der Erde entsteht?",
                originalTopic: "Wie entstehen Polarlichter?",
                language: "de",
                sessionId: "test-nein-" + Date.now()
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        const isAppropriate = !aiResponse.includes('interessante Frage') && 
                             (aiResponse.includes('in Ordnung') || 
                              aiResponse.includes('ehrlich') || 
                              aiResponse.includes('verstehen'));
        
        if (isAppropriate) {
            console.log('✅ PASS: AI responds appropriately to "nein"');
            passedTests++;
        } else {
            console.log('❌ FAIL: AI still gives inappropriate response to "nein"');
            console.log('   Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAIL: Error testing "nein" response:', error.message);
    }
    
    // Test 2: Humor acknowledgment
    console.log('\n🔍 TEST 2: Humor acknowledgment');
    totalTests++;
    try {
        const response = await fetch(`${BASE_URL}/api/respond-to-answer`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                answer: "per fax",
                question: "Wie kommunizieren Hormone im Körper?",
                originalTopic: "Warum wächst Männern ein Bart?",
                language: "de",
                sessionId: "test-humor-" + Date.now()
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        const acknowledgesHumor = aiResponse.includes('witzig') || 
                                aiResponse.includes('lustig') || 
                                aiResponse.includes('Humor') ||
                                aiResponse.includes('Schmunzeln') ||
                                aiResponse.includes('lächeln');
        
        if (acknowledgesHumor) {
            console.log('✅ PASS: AI acknowledges humor appropriately');
            passedTests++;
        } else {
            console.log('❌ FAIL: AI doesn\'t acknowledge humor');
            console.log('   Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAIL: Error testing humor response:', error.message);
    }
    
    // Test 3: Next fundamental functionality
    console.log('\n🔍 TEST 3: Next fundamental endpoint');
    totalTests++;
    try {
        const response = await fetch(`${BASE_URL}/api/next-fundamental`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                context: 'next_fundamental',
                language: 'de',
                sessionId: 'test-fundamental-' + Date.now()
            })
        });
        
        const data = await response.json();
        const hasValidResponse = data.nextFundamental && 
                               data.nextFundamental.summary && 
                               data.nextFundamental.question;
        
        if (hasValidResponse) {
            console.log('✅ PASS: Next fundamental endpoint works correctly');
            passedTests++;
        } else {
            console.log('❌ FAIL: Next fundamental endpoint doesn\'t return valid response');
            console.log('   Response:', JSON.stringify(data, null, 2));
        }
    } catch (error) {
        console.log('❌ FAIL: Error testing next fundamental:', error.message);
    }
    
    // Test 4: Button text update (client-side)
    console.log('\n🔍 TEST 4: Button text updated to "Nächste Grundlage"');
    totalTests++;
    try {
        // This would require checking the actual HTML/JS files
        // For now, we'll just verify the file exists and contains the updated text
        const fs = require('fs');
        const scriptContent = fs.readFileSync('/var/www/html/kidsai/script-new.js', 'utf8');
        
        if (scriptContent.includes('Nächste Grundlage') && 
            scriptContent.includes('continueToNextFundamental')) {
            console.log('✅ PASS: Button text updated to "Nächste Grundlage"');
            passedTests++;
        } else {
            console.log('❌ FAIL: Button text not properly updated');
        }
    } catch (error) {
        console.log('❌ FAIL: Error checking button text:', error.message);
    }
    
    // Summary
    console.log(`\n📊 TEST SUMMARY:`);
    console.log(`✅ Passed: ${passedTests}/${totalTests} tests`);
    console.log(`❌ Failed: ${totalTests - passedTests}/${totalTests} tests`);
    
    if (passedTests === totalTests) {
        console.log('\n🎉 ALL TESTS PASSED! KidsAI improvements are working correctly!');
        console.log('\n✨ Key improvements implemented:');
        console.log('   • Fixed "nein" response bug - AI now responds encouragingly');
        console.log('   • Added humor acknowledgment - AI recognizes creative answers');
        console.log('   • Added next fundamental functionality - moves to new concepts');
        console.log('   • Updated UI text from "Nächste Frage" to "Nächste Grundlage"');
    } else {
        console.log('\n⚠️  Some tests failed. Review the issues above.');
    }
}

// Run all tests
runAllTests();
