#!/usr/bin/env node

/**
 * LANCEUR GLOBAL DE TOUS LES TESTS AVEC AUTO-REPORTER
 * Lance tous les TI et TU avec capture automatique des résultats et LLM calls
 */

import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import { AutoReporter } from './reporters/AutoReporter.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.join(__dirname, '..');

// Configuration globale AutoReporter
const globalReporter = new AutoReporter();

console.log('🚀 === LANCEMENT GLOBAL TESTS TI/TU AVEC AUTO-REPORTER ===');

// Categories de tests à exécuter - MASSIVE COVERAGE
const testCategories = [
    {
        name: '🎯 MASSIVE TI - 20 Stacks Applications Partielles',
        patterns: [
            'tests/massive-ti-stacks-only.test.js'
        ],
        timeout: 2400000 // 40 minutes pour les 20 tests complets
    },
    {
        name: 'Integration Tests (Core)',
        patterns: [
            'tests/fast-ti-auto-report.test.js',
            'tests/single-llm-test.test.js'
        ],
        timeout: 180000 // 3 minutes
    },
    {
        name: 'LLM Tests (Selected)',
        patterns: [
            'tests/llm/llmmanager.contract.test.js',
            'tests/llm/pipeline-dryrun.test.js'
        ],
        timeout: 120000 // 2 minutes
    },
    {
        name: 'Content Tests (Key)',
        patterns: [
            'tests/content/selective-enhancement.test.js'
        ],
        timeout: 180000 // 3 minutes
    },
    {
        name: 'Smoke Tests',
        patterns: [
            'tests/smoke/config.test.js'
        ],
        timeout: 30000 // 30 seconds
    }
];

async function runTestCategory(category) {
    console.log(`\n🧪 === ${category.name} ===`);

    for (const pattern of category.patterns) {
        try {
            console.log(`📋 Running: ${pattern}`);

            const testProcess = spawn('node', [
                '--test',
                pattern,
                '--test-timeout',
                category.timeout.toString()
            ], {
                cwd: projectRoot,
                stdio: 'inherit',
                shell: true
            });

            await new Promise((resolve, reject) => {
                testProcess.on('close', (code) => {
                    if (code === 0) {
                        console.log(`✅ ${pattern} completed successfully`);
                        resolve();
                    } else {
                        console.log(`⚠️ ${pattern} completed with warnings/errors (code: ${code})`);
                        resolve(); // Continue même en cas d'erreur
                    }
                });

                testProcess.on('error', (err) => {
                    console.error(`❌ Error running ${pattern}:`, err.message);
                    resolve(); // Continue même en cas d'erreur
                });

                // Timeout de sécurité
                setTimeout(() => {
                    console.log(`⏰ Timeout for ${pattern}, killing process`);
                    testProcess.kill('SIGTERM');
                    resolve();
                }, category.timeout + 10000);
            });

        } catch (error) {
            console.error(`❌ Failed to run ${pattern}:`, error.message);
        }
    }

    console.log(`✅ ${category.name} category completed`);
}

async function main() {
    console.log('🎯 Starting comprehensive test suite with AutoReporter...');

    const startTime = Date.now();

    // Exécuter toutes les catégories séquentiellement
    for (const category of testCategories) {
        await runTestCategory(category);
    }

    const endTime = Date.now();
    const totalDuration = Math.round((endTime - startTime) / 1000);

    console.log(`\n📊 === RÉSUMÉ GLOBAL ===`);
    console.log(`⏱️ Durée totale: ${totalDuration}s`);
    console.log(`🧪 Categories testées: ${testCategories.length}`);
    console.log(`📈 Vérifiez les rapports dans: ./reports/`);

    // Afficher les derniers rapports générés
    console.log('\n📋 === DERNIERS RAPPORTS GÉNÉRÉS ===');
    try {
        const { spawn } = await import('child_process');
        const lsProcess = spawn('ls', ['-la', 'reports/'], {
            cwd: projectRoot,
            stdio: 'inherit'
        });
    } catch (error) {
        console.log('⚠️ Impossible d\'afficher les rapports:', error.message);
    }
}

// Gestion des signaux pour cleanup
process.on('SIGINT', () => {
    console.log('\n🛑 Interruption utilisateur, nettoyage...');
    process.exit(0);
});

process.on('SIGTERM', () => {
    console.log('\n🛑 Terminaison demandée, nettoyage...');
    process.exit(0);
});

// Lancement
main().catch(console.error);