/**
 * Quick Diagnostic Test - Checks system readiness before running full tests
 */

class QuickDiagnostic {
    constructor() {
        this.results = [];
        this.startTime = Date.now();
    }

    async runDiagnostic() {
        console.log('🔍 Running quick system diagnostic...');

        // Check 1: Application Status
        this.check('Application Status', () => {
            return window.app &&
                   typeof window.app.getStatus === 'function' &&
                   window.app.getStatus().isRunning;
        });

        // Check 2: Core Modules
        this.check('Core Modules', () => {
            const core = window.app?.getCore();
            return core &&
                   core.eventBus &&
                   core.moduleLoader &&
                   core.router;
        });

        // Check 3: Global Modules
        this.check('Global Modules', () => {
            return window.contentLoader &&
                   window.unifiedDRS &&
                   window.prerequisiteEngine;
        });

        // Check 4: AI Integration
        this.check('AI Integration', () => {
            return window.iaEngine && window.llmValidator;
        });

        // Check 5: Content System
        this.check('Content System', async () => {
            try {
                if (!window.contentLoader) return false;

                // Try to load test content
                const content = await window.contentLoader.getChapterContent('sbs', 'sbs-7-8');
                return content && content.vocabulary && Object.keys(content.vocabulary).length > 0;
            } catch {
                return false;
            }
        });

        // Check 6: Module Loading
        this.check('Module Loading', () => {
            const moduleLoader = window.app?.getCore()?.moduleLoader;
            if (!moduleLoader) return false;

            // Check if key modules are loaded
            const modules = ['unifiedDRS', 'smartPreviewOrchestrator', 'iaEngine'];
            return modules.every(name => moduleLoader.getModule(name) !== null);
        });

        // Check 7: Event System
        this.check('Event System', () => {
            const eventBus = window.app?.getCore()?.eventBus;
            if (!eventBus) return false;

            try {
                // Test event emission (should not throw)
                eventBus.emit('diagnostic:test', { test: true }, 'diagnostic');
                return true;
            } catch {
                return false;
            }
        });

        // Generate report
        this.generateReport();

        return this.results;
    }

    check(name, testFn) {
        try {
            const result = testFn();

            if (result instanceof Promise) {
                // Handle async checks
                result.then(asyncResult => {
                    this.addResult(name, asyncResult);
                }).catch(() => {
                    this.addResult(name, false);
                });
            } else {
                this.addResult(name, result);
            }
        } catch (error) {
            console.error(`Diagnostic error for ${name}:`, error);
            this.addResult(name, false, error.message);
        }
    }

    addResult(name, passed, error = null) {
        this.results.push({
            name,
            passed,
            error,
            timestamp: Date.now() - this.startTime
        });

        const status = passed ? '✅' : '❌';
        const errorMsg = error ? ` (${error})` : '';
        console.log(`${status} ${name}${errorMsg}`);
    }

    generateReport() {
        const passed = this.results.filter(r => r.passed).length;
        const failed = this.results.filter(r => !r.passed).length;
        const total = this.results.length;
        const successRate = Math.round((passed / total) * 100);

        console.log('\n🔍 DIAGNOSTIC REPORT');
        console.log('===================');
        console.log(`Total Checks: ${total}`);
        console.log(`Passed: ${passed} ✅`);
        console.log(`Failed: ${failed} ❌`);
        console.log(`Success Rate: ${successRate}%`);
        console.log(`Duration: ${Date.now() - this.startTime}ms`);

        if (successRate >= 85) {
            console.log('🎉 SYSTEM READY - All tests can proceed');
            return 'ready';
        } else if (successRate >= 70) {
            console.log('⚠️ PARTIAL READY - Some tests may fail');
            return 'partial';
        } else {
            console.log('🚨 NOT READY - System has significant issues');
            return 'not_ready';
        }
    }

    /**
     * Wait for system to be ready
     */
    async waitForReady(maxWaitTime = 30000) {
        const startTime = Date.now();

        while (Date.now() - startTime < maxWaitTime) {
            const results = await this.runDiagnostic();
            const passed = results.filter(r => r.passed).length;
            const successRate = passed / results.length;

            if (successRate >= 0.85) {
                console.log('✅ System is ready for testing!');
                return true;
            }

            console.log(`⏳ Waiting for system to be ready... ${Math.round(successRate * 100)}%`);
            await this.wait(1000);
        }

        console.log('⏰ Timeout waiting for system to be ready');
        return false;
    }

    wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// Make diagnostic available globally
window.QuickDiagnostic = QuickDiagnostic;

// Quick diagnostic function
window.runDiagnostic = async () => {
    const diagnostic = new QuickDiagnostic();
    return await diagnostic.runDiagnostic();
};

// Wait for ready function
window.waitForSystemReady = async (maxWaitTime = 30000) => {
    const diagnostic = new QuickDiagnostic();
    return await diagnostic.waitForReady(maxWaitTime);
};

console.log('🔍 Diagnostic tools loaded. Use: runDiagnostic() or waitForSystemReady()');