/**
 * Console Test Commands for Quick Module Testing
 * Load this in console for rapid testing of specific modules
 */

// Quick test commands for console
window.testCommands = {

    /**
     * Test flashcard retry system
     */
    async testFlashcardRetry() {
        console.log('🧪 Testing flashcard retry system...');

        const flashcard = window.app?.getModule?.('flashcardLearning');
        if (!flashcard) {
            console.error('❌ FlashcardLearning module not found');
            return false;
        }

        console.log('✅ FlashcardLearning module accessible');
        console.log('📊 Current retry cards:', flashcard._retryCards?.length || 0);
        console.log('📋 Session cards:', flashcard._sessionCards?.length || 0);

        return true;
    },

    /**
     * Test vocabulary progress system
     */
    async testVocabularyProgress() {
        console.log('🧪 Testing vocabulary progress system...');

        // Test prerequisite engine
        if (!window.prerequisiteEngine) {
            console.error('❌ PrerequisiteEngine not found');
            return false;
        }

        console.log('✅ PrerequisiteEngine accessible');

        // Test vocabulary modal functions
        const functions = ['showVocabularyKnowledge', 'loadPersistedVocabularyData', 'calculateVocabularyProgress'];
        let allFunctionsExist = true;

        functions.forEach(fn => {
            if (typeof window[fn] === 'function') {
                console.log(`✅ ${fn} available`);
            } else {
                console.error(`❌ ${fn} not found`);
                allFunctionsExist = false;
            }
        });

        // Test progress calculation
        try {
            const progress = window.prerequisiteEngine.getMasteryProgress();
            console.log('📊 Current mastery progress:', progress);
        } catch (error) {
            console.error('❌ Error getting mastery progress:', error);
            allFunctionsExist = false;
        }

        return allFunctionsExist;
    },

    /**
     * Test intelligent sequencer
     */
    async testIntelligentSequencer() {
        console.log('🧪 Testing IntelligentSequencer...');

        const sequencer = window.app?.getCore()?.intelligentSequencer;
        if (!sequencer) {
            console.error('❌ IntelligentSequencer not found');
            return false;
        }

        console.log('✅ IntelligentSequencer accessible');

        // Test session creation
        try {
            const session = sequencer.startGuidedSession({
                bookId: 'sbs',
                chapterId: 'sbs-7-8',
                targetLength: 3
            });
            console.log('✅ Session created:', session.id);

            // Test next exercise recommendation
            const nextExercise = await sequencer.getNextExercise();
            if (nextExercise) {
                console.log('✅ Exercise recommendation:', nextExercise);
            } else {
                console.log('⚠️ No exercise recommendations available');
            }

            // Test performance insights
            const insights = sequencer.getPerformanceInsights();
            console.log('📊 Performance insights:', insights);

            // Stop session
            sequencer.stopGuidedSession();
            console.log('✅ Session stopped');

            return true;

        } catch (error) {
            console.error('❌ Error testing sequencer:', error);
            return false;
        }
    },

    /**
     * Test AI integration
     */
    async testAIIntegration() {
        console.log('🧪 Testing AI integration...');

        if (!window.iaEngine) {
            console.error('❌ IAEngine not found');
            return false;
        }

        console.log('✅ IAEngine accessible');
        console.log('🔧 Available providers:', Object.keys(window.iaEngine.providers));
        console.log('🎯 Current provider:', window.iaEngine.currentProvider);

        if (!window.llmValidator) {
            console.error('❌ LLMValidator not found');
            return false;
        }

        console.log('✅ LLMValidator accessible');

        // Test basic validation (will likely fail without API keys, but tests structure)
        try {
            const result = await window.llmValidator.validateAnswer(
                'What is 2+2?',
                '4',
                { timeout: 5000 }
            );
            console.log('✅ AI validation successful:', result);
            return true;
        } catch (error) {
            console.log('⚠️ AI validation failed (expected without API keys):', error.message);
            // This is expected without API keys configured
            return error.message.includes('provider') || error.message.includes('API');
        }
    },

    /**
     * Test DRS system
     */
    async testDRSSystem() {
        console.log('🧪 Testing DRS system...');

        if (!window.unifiedDRS) {
            console.error('❌ UnifiedDRS not found');
            return false;
        }

        console.log('✅ UnifiedDRS accessible');
        console.log('🎯 Available exercise types:', Object.keys(window.unifiedDRS._exerciseModules || {}));

        // Test content loading
        if (!window.contentLoader) {
            console.error('❌ ContentLoader not found');
            return false;
        }

        console.log('✅ ContentLoader accessible');

        try {
            const content = await window.contentLoader.getChapterContent('sbs', 'sbs-7-8');
            console.log('✅ Content loaded:', {
                vocabulary: Object.keys(content.vocabulary || {}).length,
                phrases: Object.keys(content.phrases || {}).length,
                texts: (content.texts || []).length
            });
            return true;
        } catch (error) {
            console.error('❌ Error loading content:', error);
            return false;
        }
    },

    /**
     * Test word discovery system
     */
    async testWordDiscovery() {
        console.log('🧪 Testing Word Discovery system...');

        if (!window.prerequisiteEngine) {
            console.error('❌ PrerequisiteEngine not found');
            return false;
        }

        // Test word discovery tracking
        const testWord = 'test_word';

        console.log('📝 Testing word discovery tracking...');
        window.prerequisiteEngine.markWordDiscovered(testWord);

        const isDiscovered = window.prerequisiteEngine.isDiscovered(testWord);
        console.log(`✅ Word discovery test: ${isDiscovered ? 'PASSED' : 'FAILED'}`);

        // Test mastery tracking
        console.log('📝 Testing word mastery tracking...');
        window.prerequisiteEngine.markWordMastered(testWord);

        const isMastered = window.prerequisiteEngine.isMastered(testWord);
        console.log(`✅ Word mastery test: ${isMastered ? 'PASSED' : 'FAILED'}`);

        return isDiscovered && isMastered;
    },

    /**
     * Run all quick tests
     */
    async testAll() {
        console.log('🚀 Running all quick tests...');

        const tests = [
            'testFlashcardRetry',
            'testVocabularyProgress',
            'testIntelligentSequencer',
            'testAIIntegration',
            'testDRSSystem',
            'testWordDiscovery'
        ];

        let passed = 0;
        let failed = 0;

        for (const testName of tests) {
            console.log(`\n▶️ Running ${testName}...`);
            try {
                const result = await this[testName]();
                if (result) {
                    passed++;
                    console.log(`✅ ${testName} PASSED`);
                } else {
                    failed++;
                    console.log(`❌ ${testName} FAILED`);
                }
            } catch (error) {
                failed++;
                console.error(`❌ ${testName} ERROR:`, error);
            }
        }

        console.log(`\n📊 QUICK TEST RESULTS:`);
        console.log(`✅ Passed: ${passed}`);
        console.log(`❌ Failed: ${failed}`);
        console.log(`📈 Success rate: ${Math.round((passed / (passed + failed)) * 100)}%`);

        return { passed, failed, total: passed + failed };
    },

    /**
     * Show module status
     */
    showModuleStatus() {
        console.log('📋 MODULE STATUS REPORT');
        console.log('======================');

        const modules = {
            'Application': window.app,
            'ContentLoader': window.contentLoader,
            'UnifiedDRS': window.unifiedDRS,
            'IAEngine': window.iaEngine,
            'LLMValidator': window.llmValidator,
            'PrerequisiteEngine': window.prerequisiteEngine,
            'IntelligentSequencer': window.app?.getCore()?.intelligentSequencer,
            'FlashcardLearning': window.app?.getModule?.('flashcardLearning')
        };

        for (const [name, module] of Object.entries(modules)) {
            const status = module ? '✅ LOADED' : '❌ MISSING';
            console.log(`${status} ${name}`);
        }

        // Show function availability
        console.log('\n📋 FUNCTION AVAILABILITY');
        console.log('========================');

        const functions = [
            'showVocabularyKnowledge',
            'loadPersistedVocabularyData',
            'calculateVocabularyProgress',
            'runDRSTests'
        ];

        functions.forEach(fn => {
            const status = typeof window[fn] === 'function' ? '✅ AVAILABLE' : '❌ MISSING';
            console.log(`${status} ${fn}`);
        });
    },

    /**
     * Test UI/UX interactions
     */
    async testUIInteractions() {
        console.log('🎨 Testing UI interactions...');

        // Test vocabulary modal
        try {
            const vocabButton = document.querySelector('[onclick*="showVocabularyKnowledge"]');
            if (vocabButton) {
                console.log('✅ Vocabulary button found');
                // Test click simulation
                const clickEvent = new MouseEvent('click', { bubbles: true });
                vocabButton.dispatchEvent(clickEvent);
                console.log('✅ Vocabulary button click simulated');
                return true;
            } else {
                console.log('❌ Vocabulary button not found');
                return false;
            }
        } catch (error) {
            console.error('❌ UI interaction test failed:', error);
            return false;
        }
    },

    /**
     * Help command
     */
    help() {
        console.log('🧪 DRS TEST COMMANDS');
        console.log('====================');
        console.log('testCommands.testAll() - Run all quick tests');
        console.log('testCommands.testFlashcardRetry() - Test flashcard retry system');
        console.log('testCommands.testVocabularyProgress() - Test vocabulary progress');
        console.log('testCommands.testIntelligentSequencer() - Test smart sequencer');
        console.log('testCommands.testAIIntegration() - Test AI systems');
        console.log('testCommands.testDRSSystem() - Test DRS core');
        console.log('testCommands.testWordDiscovery() - Test word discovery');
        console.log('testCommands.testUIInteractions() - Test UI interactions');
        console.log('testCommands.showModuleStatus() - Show module status');
        console.log('testCommands.help() - Show this help');
        console.log('\n🧪 INTEGRATION TESTS');
        console.log('runDRSTests() - Run comprehensive integration tests');
        console.log('runUIUXTests() - Run full UI/UX interaction tests');
        console.log('F12 -> Debug Panel -> "Run Integration Tests" button');
        console.log('F12 -> Debug Panel -> "Run UI/UX Tests" button');
    }
};

// Make it easily accessible
window.test = window.testCommands;

console.log('🧪 Console test commands loaded! Type: test.help()');