import path from 'node:path';
import { spawn } from 'node:child_process';

const suite = [
    'scripts/testTradeExecutorLifecycle.ts',
    'scripts/testLifecycleRegressions.ts',
    'scripts/testOrderStatusSyncRegressions.ts',
    'scripts/testSupabaseOrderPersistenceRegressions.ts',
    'scripts/testFailureInjection.ts',
    'src/scripts/verifyWebsocketContract.ts',
    'scripts/testManualTraderCapitalGuard.ts',
    'scripts/testSupabaseTradeHistorySourceFallback.ts',
    'scripts/testStateMergeCoverage.ts',
    'scripts/testBacktestIsolation.ts',
    'scripts/testCoreModuleCoverage.ts',
    'scripts/testConnectorAndAiCoverage.ts'
];

const runScript = (relativePath: string): Promise<number> =>
    new Promise((resolve) => {
        const scriptPath = path.resolve(process.cwd(), relativePath);
        const child = spawn(
            process.execPath,
            ['--loader', 'ts-node/esm', scriptPath],
            {
                stdio: 'inherit',
                shell: false,
                env: {
                    ...process.env,
                    TS_NODE_TRANSPILE_ONLY: '1'
                }
            }
        );

        child.on('close', (code) => resolve(code ?? 1));
        child.on('error', () => resolve(1));
    });

const main = async () => {
    console.log('\n[coverage-suite] Running coverage-friendly regression suite...\n');
    const failed: string[] = [];

    for (const item of suite) {
        console.log(`\n[coverage-suite] ▶ ${item}`);
        const code = await runScript(item);
        if (code === 0) {
            console.log(`[coverage-suite] ✅ ${item} passed`);
        } else {
            failed.push(item);
            console.log(`[coverage-suite] ❌ ${item} failed with exit code ${code}`);
        }
    }

    console.log('\n[coverage-suite] Summary');
    console.log(`[coverage-suite] Passed: ${suite.length - failed.length}`);
    console.log(`[coverage-suite] Failed: ${failed.length}`);
    if (failed.length > 0) {
        console.log('[coverage-suite] Failed scripts:');
        failed.forEach((item) => console.log(`- ${item}`));
        process.exit(1);
    }
};

main().catch((error) => {
    console.error('[coverage-suite] Unhandled error', error);
    process.exit(1);
});
