/**
 * VL AutoTest - Report Generator
 * Generates Markdown and JSON test reports
 */

export class ReportGenerator {
  /**
   * Generate a comprehensive Markdown test report
   */
  static generateMarkdown(testCases, runResults, evaluations, fixResults = [], meta = {}) {
    const now = new Date().toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
    const totalCases = testCases.length;
    const passCount = evaluations.filter(e => e.evaluation.pass).length;
    const failCount = totalCases - passCount;
    const passRate = totalCases > 0 ? ((passCount / totalCases) * 100).toFixed(1) : '0.0';
    const totalDuration = runResults.reduce((sum, r) => sum + (r.durationMs || 0), 0);

    const byPriority = {};
    for (const tc of testCases) {
      const p = tc.priority || 'P2';
      if (!byPriority[p]) byPriority[p] = { total: 0, pass: 0 };
      byPriority[p].total++;
      const eval_ = evaluations.find(e => e.caseId === tc.id);
      if (eval_?.evaluation.pass) byPriority[p].pass++;
    }

    let md = `# VL AutoTest Test Report

**Generated at**: ${now}
**App**: ${meta.appName || 'not specified'}
**Test URL**: ${meta.baseUrl || 'not specified'}

---

## Overview

| Metric | Value |
|--------|-------|
| Total cases | ${totalCases} |
| Passed | ${passCount} ✅ |
| Failed | ${failCount} ❌ |
| Pass rate | ${passRate}% |
| Total duration | ${(totalDuration / 1000).toFixed(1)}s |

### Statistics by Priority

| Priority | Passed/Total | Pass Rate |
|----------|-------------|-----------|
`;
    for (const p of ['P0', 'P1', 'P2', 'P3']) {
      if (byPriority[p]) {
        const rate = ((byPriority[p].pass / byPriority[p].total) * 100).toFixed(0);
        md += `| ${p} | ${byPriority[p].pass}/${byPriority[p].total} | ${rate}% |\n`;
      }
    }

    md += `\n---\n\n## Case Details\n\n`;

    for (const tc of testCases) {
      const result = runResults.find(r => r.caseId === tc.id);
      const eval_ = evaluations.find(e => e.caseId === tc.id);
      const fix = fixResults.find(f => f.caseId === tc.id);
      const status = eval_?.evaluation.pass ? '✅ PASS' : '❌ FAIL';

      md += `### ${tc.id}: ${tc.name} ${status}\n\n`;
      md += `- **Priority**: ${tc.priority || 'P2'}\n`;
      md += `- **Page**: ${tc.page}\n`;
      md += `- **Duration**: ${result ? (result.durationMs / 1000).toFixed(1) + 's' : 'N/A'}\n`;
      md += `- **Expected result**: ${tc.expectedResult}\n\n`;

      if (result?.steps?.length > 0) {
        md += `| Step | Action | Description | Status |\n`;
        md += `|------|--------|-------------|--------|\n`;
        for (const step of result.steps) {
          const sStatus = step.status === 'passed' ? '✅' : '❌';
          md += `| ${step.index + 1} | ${step.action} | ${step.description || ''} | ${sStatus} |\n`;
        }
        md += '\n';
      }

      if (!eval_?.evaluation.pass) {
        md += `**Failure reason**: ${eval_?.evaluation.reason || result?.error || 'unknown'}\n\n`;

        if (fix?.fix?.analysis) {
          md += `**Failure analysis**:\n`;
          md += `- Type: ${fix.fix.analysis.failureType}\n`;
          md += `- Root cause: ${fix.fix.analysis.rootCause}\n\n`;
        }

        if (fix?.fix?.fixes?.length > 0) {
          md += `**Fix suggestions**:\n`;
          for (const f of fix.fix.fixes) {
            md += `- [${f.priority}] ${f.description} (confidence: ${(f.confidence * 100).toFixed(0)}%)\n`;
          }
          md += '\n';
        }
      }

      md += '---\n\n';
    }

    if (failCount > 0 && fixResults.length > 0) {
      md += `## Auto-Fix Summary\n\n`;
      md += `| Case | Failure Type | Root Cause | Fix Suggestions | Retry Advice |\n`;
      md += `|------|-------------|------------|-----------------|-------------|\n`;
      for (const fix of fixResults) {
        md += `| ${fix.caseId} | ${fix.fix.analysis?.failureType || 'N/A'} | ${fix.fix.analysis?.rootCause?.slice(0, 50) || 'N/A'} | ${fix.fix.fixes?.length || 0} | ${fix.fix.retryAdvice || 'N/A'} |\n`;
      }
      md += '\n';
    }

    md += `---\n\n*Report auto-generated by VL AutoTest | ${now}*\n`;

    return md;
  }

  /**
   * Generate a structured JSON report
   */
  static generateJSON(testCases, runResults, evaluations, fixResults = [], meta = {}) {
    const totalCases = testCases.length;
    const passCount = evaluations.filter(e => e.evaluation.pass).length;

    return {
      meta: {
        generatedAt: new Date().toISOString(),
        appName: meta.appName || '',
        baseUrl: meta.baseUrl || '',
        version: '1.0',
      },
      summary: {
        total: totalCases,
        passed: passCount,
        failed: totalCases - passCount,
        passRate: totalCases > 0 ? passCount / totalCases : 0,
        totalDurationMs: runResults.reduce((sum, r) => sum + (r.durationMs || 0), 0),
      },
      cases: testCases.map(tc => {
        const result = runResults.find(r => r.caseId === tc.id);
        const eval_ = evaluations.find(e => e.caseId === tc.id);
        const fix = fixResults.find(f => f.caseId === tc.id);

        return {
          id: tc.id,
          name: tc.name,
          priority: tc.priority,
          page: tc.page,
          pass: eval_?.evaluation.pass ?? false,
          confidence: eval_?.evaluation.confidence ?? 0,
          reason: eval_?.evaluation.reason || '',
          durationMs: result?.durationMs || 0,
          steps: result?.steps || [],
          screenshots: result?.screenshotPaths || [],
          fix: fix?.fix || null,
        };
      }),
    };
  }
}
