#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

function analyzeTestResults() {
  const resultsDir = path.join(__dirname, '..', 'test-results');
  const reportDir = path.join(__dirname, '..', 'tests', 'e2e', 'playwright-report');

  console.log('🔍 Analyzing test results...\n');

  // 检查测试结果目录
  if (!fs.existsSync(resultsDir)) {
    console.log('❌ No test results found');
    return;
  }

  // 读取 JUnit 报告
  const junitFile = path.join(resultsDir, 'junit.xml');
  if (fs.existsSync(junitFile)) {
    const junitContent = fs.readFileSync(junitFile, 'utf8');

    // 简单的 XML 解析来获取测试统计
    const testsMatch = junitContent.match(/tests="(\d+)"/);
    const failuresMatch = junitContent.match(/failures="(\d+)"/);
    const errorsMatch = junitContent.match(/errors="(\d+)"/);

    const totalTests = testsMatch ? parseInt(testsMatch[1]) : 0;
    const failures = failuresMatch ? parseInt(failuresMatch[1]) : 0;
    const errors = errorsMatch ? parseInt(errorsMatch[1]) : 0;
    const passed = totalTests - failures - errors;

    console.log('📊 Test Results Summary:');
    console.log(`✅ Passed: ${passed}`);
    console.log(`❌ Failed: ${failures}`);
    console.log(`⚠️  Errors: ${errors}`);
    console.log(`📋 Total: ${totalTests}`);
    console.log(`🎯 Success Rate: ${((passed / totalTests) * 100).toFixed(1)}%\n`);

    if (failures > 0 || errors > 0) {
      console.log('🔴 Test failures detected!');
      process.exit(1);
    } else {
      console.log('🟢 All tests passed!');
    }
  }

  // 检查 HTML 报告
  if (fs.existsSync(reportDir)) {
    console.log('📈 HTML report available at:');
    console.log(`   file://${path.resolve(reportDir, 'index.html')}\n`);
  }
}

// 运行分析
analyzeTestResults();