/**
 * Test Readiness Helper - Waits for all modules to be properly loaded
 */

window.waitForAllModulesReady = async function(timeout = 30000) {
    const startTime = Date.now();

    console.log('⏳ Waiting for all modules to be ready...');

    while (Date.now() - startTime < timeout) {
        // Check if all critical modules are available
        const modules = {
            app: window.app && window.app.getStatus && window.app.getStatus().isRunning,
            contentLoader: !!window.contentLoader,
            unifiedDRS: !!window.unifiedDRS,
            iaEngine: !!window.iaEngine,
            llmValidator: !!window.llmValidator,
            prerequisiteEngine: !!window.prerequisiteEngine
        };

        const allReady = Object.values(modules).every(ready => ready);

        if (allReady) {
            console.log('✅ All modules ready!', modules);
            return true;
        }

        const missing = Object.entries(modules)
            .filter(([name, ready]) => !ready)
            .map(([name]) => name);

        console.log(`⏳ Still waiting for: ${missing.join(', ')} (${Date.now() - startTime}ms)`);

        await new Promise(resolve => setTimeout(resolve, 200));
    }

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

window.ensureModulesReady = async function() {
    const isReady = await window.waitForAllModulesReady();

    if (!isReady) {
        throw new Error('Modules not ready for testing - please check system status');
    }

    return true;
};

console.log('⏳ Module readiness helper loaded. Use: waitForAllModulesReady() or ensureModulesReady()');