/**
 * runTests.js - Main test execution entry point
 * Runs all test suites and provides comprehensive reporting
 */

import TestRunner from './TestRunner.js';
import { CoreArchitectureTests } from './tests/CoreArchitectureTests.js';
import { DRSModuleTests } from './tests/DRSModuleTests.js';

/**
 * Main test execution function
 * @param {HTMLElement} reportContainer - Optional container for HTML report
 * @returns {Promise<Object>} - Complete test results
 */
async function runAllTests(reportContainer = null) {
    console.log('🧪 Class Generator 2.0 - Test Suite');
    console.log('Testing architecture and DRS modules...\n');

    // Create test runner
    const testRunner = new TestRunner();

    // Register all test suites
    testRunner.registerSuite('Core Architecture Tests', CoreArchitectureTests);
    testRunner.registerSuite('DRS Module Tests', DRSModuleTests);

    // Run tests with optional HTML report
    const results = await testRunner.runTestsWithReport(reportContainer);

    // Additional validation and recommendations
    await generateRecommendations(results);

    return results;
}

/**
 * Generate recommendations based on test results
 * @param {Object} results - Test results
 */
async function generateRecommendations(results) {
    console.log('\n🎯 RECOMMENDATIONS:');
    console.log('-'.repeat(50));

    const issues = [];
    const improvements = [];

    // Analyze results
    if (results.overall.failedTests > 0) {
        issues.push('❌ Failed tests need immediate attention');
    }

    if (results.overall.duration > 10000) {
        issues.push('⚠️ Test execution is slow - consider optimization');
    }

    const passRate = results.overall.totalTests > 0
        ? (results.overall.passedTests / results.overall.totalTests)
        : 0;

    if (passRate < 0.8) {
        issues.push('❌ Test pass rate below 80% - architecture may need review');
    }

    // Check specific areas
    const coreTests = results.suites.find(s => s.suiteName.includes('Core'));
    const drsTests = results.suites.find(s => s.suiteName.includes('DRS'));

    if (coreTests && !coreTests.success) {
        issues.push('🏗️ Core architecture has issues - this is critical');
        improvements.push('Review Module.js, EventBus.js, and ModuleLoader.js implementation');
    }

    if (drsTests && !drsTests.success) {
        issues.push('🎮 DRS modules have issues - affects user experience');
        improvements.push('Review exercise module implementations and interfaces');
    }

    // Print issues
    if (issues.length > 0) {
        console.log('🚨 ISSUES DETECTED:');
        issues.forEach(issue => console.log(`   ${issue}`));
    } else {
        console.log('✅ No major issues detected!');
    }

    // Print improvements
    if (improvements.length > 0) {
        console.log('\n💡 SUGGESTED IMPROVEMENTS:');
        improvements.forEach(improvement => console.log(`   • ${improvement}`));
    }

    // Next steps based on results
    console.log('\n🚀 NEXT STEPS:');

    if (results.summary.success) {
        console.log('   ✅ All tests pass - ready for PHASE 2.2 (Component Extraction)');
        console.log('   • Extract UI components from DRS modules');
        console.log('   • Create reusable component library');
        console.log('   • Implement component registration system');
    } else if (passRate >= 0.7) {
        console.log('   ⚠️ Address failing tests before proceeding to next phase');
        console.log('   • Fix critical architecture issues first');
        console.log('   • Re-run tests after fixes');
        console.log('   • Consider test-driven development for remaining work');
    } else {
        console.log('   ❌ Major issues detected - extensive review needed');
        console.log('   • Focus on core architecture stability');
        console.log('   • Review module contracts and dependencies');
        console.log('   • Consider architectural refactoring if needed');
    }

    // Performance recommendations
    if (results.overall.duration > 5000) {
        console.log('\n⚡ PERFORMANCE OPTIMIZATION:');
        console.log('   • Consider lazy loading of modules');
        console.log('   • Review EventBus efficiency');
        console.log('   • Optimize module initialization sequences');
    }

    console.log('-'.repeat(50));
}

/**
 * Run tests in browser environment
 * Creates a test page with results
 */
function runTestsInBrowser() {
    // Create test page container
    document.body.innerHTML = `
        <div id="test-page">
            <header>
                <h1>🧪 Class Generator 2.0 - Test Results</h1>
                <p>Comprehensive testing of architecture and modules</p>
            </header>
            <div id="test-progress">
                <div class="progress-indicator">
                    <div class="spinner"></div>
                    <span>Running tests...</span>
                </div>
            </div>
            <div id="test-results" style="display: none;"></div>
        </div>
    `;

    // Add basic styles
    const styles = document.createElement('style');
    styles.textContent = `
        body {
            margin: 0;
            padding: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        #test-page {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            color: white;
            margin-bottom: 40px;
        }

        header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .progress-indicator {
            text-align: center;
            background: white;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #test-results {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
    `;
    document.head.appendChild(styles);

    // Run tests
    const progressDiv = document.getElementById('test-progress');
    const resultsDiv = document.getElementById('test-results');

    setTimeout(async () => {
        try {
            await runAllTests(resultsDiv);
            progressDiv.style.display = 'none';
            resultsDiv.style.display = 'block';
        } catch (error) {
            progressDiv.innerHTML = `
                <div class="progress-indicator" style="background: #ffebee; border: 2px solid #f44336;">
                    <h3 style="color: #c62828;">❌ Test execution failed</h3>
                    <p style="color: #666;">Error: ${error.message}</p>
                    <pre style="text-align: left; background: #f5f5f5; padding: 15px; border-radius: 4px; font-size: 0.85em;">${error.stack}</pre>
                </div>
            `;
        }
    }, 100);
}

/**
 * Auto-run tests if in browser
 */
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    // Browser environment - create test page
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', runTestsInBrowser);
    } else {
        runTestsInBrowser();
    }
} else {
    // Node.js environment - just export the function
    console.log('Test runner loaded - use runAllTests() to execute');
}

// Export for both Node.js and browser environments
export { runAllTests, generateRecommendations };

// Also make available globally in browser
if (typeof window !== 'undefined') {
    window.runAllTests = runAllTests;
}