/**
 * 运行所有边界条件和异常处理测试
 */

const { spawn } = require('child_process');
const path = require('path');

const testFiles = [
  'boundary-tests.js',
  'network-concurrent-tests.js',
  'state-consistency-tests.js'
];

const results = {
  total: { passed: 0, failed: 0 },
  files: []
};

function runTest(file) {
  return new Promise((resolve) => {
    const testPath = path.join(__dirname, file);
    const child = spawn('node', [testPath], {
      stdio: ['pipe', 'pipe', 'pipe']
    });

    let output = '';
    let errorOutput = '';

    child.stdout.on('data', (data) => {
      output += data.toString();
      process.stdout.write(data);
    });

    child.stderr.on('data', (data) => {
      errorOutput += data.toString();
      process.stderr.write(data);
    });

    child.on('close', (code) => {
      // 解析测试结果
      const passMatch = output.match(/通过:\s*(\d+)/);
      const failMatch = output.match(/失败:\s*(\d+)/);

      const passed = passMatch ? parseInt(passMatch[1]) : 0;
      const failed = failMatch ? parseInt(failMatch[1]) : 0;

      results.files.push({
        file,
        passed,
        failed,
        exitCode: code
      });

      results.total.passed += passed;
      results.total.failed += failed;

      resolve(code);
    });
  });
}

async function runAllTests() {
  console.log('='.repeat(60));
  console.log('运行所有边界条件和异常处理测试');
  console.log('='.repeat(60));
  console.log('');

  for (const file of testFiles) {
    console.log('='.repeat(60));
    console.log(`测试文件: ${file}`);
    console.log('='.repeat(60));

    await runTest(file);

    console.log('');
  }

  // 输出最终汇总
  console.log('='.repeat(60));
  console.log('最终汇总');
  console.log('='.repeat(60));
  console.log('');

  console.log('各测试文件结果:');
  for (const fileResult of results.files) {
    const status = fileResult.failed === 0 ? 'PASS' : 'FAIL';
    console.log(`  [${status}] ${fileResult.file}: 通过 ${fileResult.passed}, 失败 ${fileResult.failed}`);
  }

  console.log('');
  console.log(`总计: 通过 ${results.total.passed}, 失败 ${results.total.failed}`);
  console.log('');

  if (results.total.failed > 0) {
    console.log('存在失败的测试，请检查输出以了解详情。');
    process.exit(1);
  } else {
    console.log('所有测试通过！');
    process.exit(0);
  }
}

runAllTests().catch(err => {
  console.error('运行测试时发生错误:', err);
  process.exit(1);
});
