#!/usr/bin/env node

/**
 * Final Verification Test for KidsAI Explorer
 * Tests all major improvements implemented
 */

const fetch = require('node-fetch');

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

async function runFinalVerification() {
    console.log('🎯 FINAL VERIFICATION TEST FOR KIDSAI EXPLORER\n');
    console.log('Testing all major improvements...\n');
    
    let passedTests = 0;
    let totalTests = 6;
    
    // Test 1: "Nein" Response Bug Fix
    console.log('TEST 1: "Nein" Response Bug Fix');
    console.log('=' .repeat(40));
    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: "final-test-1"
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        
        if (aiResponse.includes('Das ist') && (aiResponse.includes('in Ordnung') || aiResponse.includes('okay'))) {
            console.log('✅ PASSED: AI responds appropriately to "nein"');
            passedTests++;
        } else {
            console.log('❌ FAILED: AI still has "nein" response bug');
            console.log('Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing "nein" response:', error.message);
    }
    
    // Test 2: Next Fundamental Endpoint
    console.log('\nTEST 2: Next Fundamental Endpoint');
    console.log('=' .repeat(40));
    try {
        const response = await fetch(`${BASE_URL}/api/next-fundamental`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                currentTopic: "Wie entstehen Polarlichter?",
                language: "de",
                sessionId: "final-test-2"
            })
        });
        
        const data = await response.json();
        
        if (data.success && data.guidance && data.guidance.steps) {
            console.log('✅ PASSED: Next fundamental endpoint works');
            passedTests++;
        } else {
            console.log('❌ FAILED: Next fundamental endpoint not working');
            console.log('Response:', data);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing next fundamental:', error.message);
    }
    
    // Test 3: Humor Acknowledgment
    console.log('\nTEST 3: Humor Acknowledgment');
    console.log('=' .repeat(40));
    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 können Vögel miteinander kommunizieren?",
                originalTopic: "Wie fliegen Vögel?",
                language: "de",
                sessionId: "final-test-3"
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        
        if (aiResponse.includes('lustig') || aiResponse.includes('kreativ') || aiResponse.includes('Haha')) {
            console.log('✅ PASSED: AI acknowledges humor appropriately');
            passedTests++;
        } else {
            console.log('❌ FAILED: AI does not acknowledge humor');
            console.log('Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing humor:', error.message);
    }
    
    // Test 4: Emotional Support
    console.log('\nTEST 4: Emotional Support');
    console.log('=' .repeat(40));
    try {
        const response = await fetch(`${BASE_URL}/api/respond-to-answer`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                answer: "Das ist doof und verstehe ich nicht",
                question: "Was ist UV-Strahlung?",
                originalTopic: "Warum bekommt man Sonnenbrand?",
                language: "de",
                sessionId: "final-test-4"
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        
        if (aiResponse.includes('verstehen') || aiResponse.includes('okay') || aiResponse.includes('anders')) {
            console.log('✅ PASSED: AI provides emotional support');
            passedTests++;
        } else {
            console.log('❌ FAILED: AI does not provide emotional support');
            console.log('Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing emotional support:', error.message);
    }
    
    // Test 5: Repetition Handling
    console.log('\nTEST 5: Repetition Handling');
    console.log('=' .repeat(40));
    try {
        const response = await fetch(`${BASE_URL}/api/respond-to-answer`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                answer: "Hab ich schon gesagt - das ist Licht von der Sonne",
                question: "Was ist UV-Strahlung?",
                originalTopic: "Warum bekommt man Sonnenbrand?",
                language: "de",
                sessionId: "final-test-5"
            })
        });
        
        const data = await response.json();
        const aiResponse = data.response || '';
        
        if (aiResponse.includes('recht') || aiResponse.includes('schon gesagt') || aiResponse.includes('Danke')) {
            console.log('✅ PASSED: AI handles repetition appropriately');
            passedTests++;
        } else {
            console.log('❌ FAILED: AI does not handle repetition');
            console.log('Response:', aiResponse);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing repetition:', error.message);
    }
    
    // Test 6: Basic Conversation Flow
    console.log('\nTEST 6: Basic Conversation Flow');
    console.log('=' .repeat(40));
    try {
        const response = await fetch(`${BASE_URL}/api/ask`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                question: "Wie entstehen Polarlichter?",
                language: "de",
                sessionId: "final-test-6"
            })
        });
        
        const data = await response.json();
        
        if (data.success && data.guidance && data.guidance.steps && data.guidance.steps.length > 0) {
            console.log('✅ PASSED: Basic conversation flow works');
            passedTests++;
        } else {
            console.log('❌ FAILED: Basic conversation flow broken');
            console.log('Response:', data);
        }
    } catch (error) {
        console.log('❌ FAILED: Error testing basic conversation:', error.message);
    }
    
    // Final Results
    console.log('\n' + '='.repeat(60));
    console.log('🎯 FINAL VERIFICATION RESULTS');
    console.log('='.repeat(60));
    console.log(`✅ Passed: ${passedTests}/${totalTests} tests`);
    console.log(`❌ Failed: ${totalTests - passedTests}/${totalTests} tests`);
    
    const successRate = (passedTests / totalTests) * 100;
    console.log(`📊 Success Rate: ${successRate.toFixed(1)}%`);
    
    if (successRate >= 80) {
        console.log('\n🎉 EXCELLENT! KidsAI Explorer improvements are working successfully!');
        console.log('🚀 The application is ready for use.');
    } else if (successRate >= 60) {
        console.log('\n⚠️  GOOD PROGRESS! Most improvements are working.');
        console.log('🔧 Some minor issues remain to be addressed.');
    } else {
        console.log('\n❌ NEEDS ATTENTION! Several improvements are not working properly.');
        console.log('🛠️  Further debugging and fixes required.');
    }
    
    console.log('\n💡 Key Improvements Implemented:');
    console.log('   • Fixed "nein" response bug');
    console.log('   • Added next fundamental functionality');
    console.log('   • Implemented humor acknowledgment');
    console.log('   • Added emotional support handling');
    console.log('   • Improved repetition detection');
    console.log('   • Enhanced educational conversation flow');
    
    return successRate >= 80;
}

// Run the final verification
if (require.main === module) {
    runFinalVerification().catch(console.error);
}

module.exports = { runFinalVerification };
