const express = require('express');
const router = express.Router();
const pm = require('../services/project-manager');
const path = require('path');
const fs = require('fs');

function resolveProject(req) {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  return projects.find(p => p.id === projectId);
}

function resolveRunId(runId, bridge) {
  if (runId === 'latest') {
    const dirs = bridge.getRunDirs();
    return dirs.length > 0 ? dirs[0].name : null;
  }
  return runId;
}

router.get('/report/:runId', (req, res) => {
  const project = resolveProject(req);
  if (!project) return res.status(404).send('Project not found');

  const bridge = pm.getBridge(project.id);
  const runId = resolveRunId(req.params.runId, bridge);
  if (!runId) return res.status(404).send('No runs found');

  const report = bridge.getFinalReport(runId);
  const result = bridge.getRunResult(runId);
  const healing = bridge.getHealingReport(runId);

  if (!result) return res.status(404).send('Run not found');

  const html = `<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>QA Report - ${runId}</title>
<style>
  body { font-family: Arial, sans-serif; max-width: 800px; margin: 2rem auto; padding: 1rem; color: #333; line-height: 1.5; }
  h1 { color: #6366f1; border-bottom: 2px solid #6366f1; padding-bottom: 0.5rem; }
  .badge { display: inline-block; padding: 6px 14px; border-radius: 20px; font-size: 14px; font-weight: bold; text-transform: uppercase; }
  .pass { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
  .fail { background: #fecaca; color: #991b1b; border: 1px solid #fca5a5; }
  table { width: 100%; border-collapse: collapse; margin: 1.5rem 0; }
  td, th { border: 1px solid #ddd; padding: 10px; text-align: left; }
  th { background: #f4f4f5; font-weight: 600; }
  .section { margin: 2.5rem 0; }
  .stats { display: flex; gap: 1.5rem; flex-wrap: wrap; margin-top: 1rem; }
  .stat-card { border: 1px solid #e4e4e7; border-radius: 8px; padding: 1.25rem; min-width: 140px; text-align: center; background: #fafafa; }
  .stat-num { font-size: 28px; font-weight: bold; color: #6366f1; }
  .stat-label { font-size: 13px; color: #71717a; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
  .footer { margin-top: 3rem; font-size: 12px; color: #999; border-top: 1px solid #eee; padding-top: 1rem; text-align: center; }
  pre { white-space: pre-wrap; word-wrap: break-word; background: #f4f4f5; padding: 1.25rem; border-radius: 8px; font-size: 13px; font-family: monospace; border: 1px solid #e4e4e7; }
  
  /* Print actions style */
  .actions-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; background: #f4f4f5; padding: 1rem; border-radius: 8px; border: 1px solid #e4e4e7; }
  .btn-print { background: #6366f1; color: #fff; border: none; padding: 10px 20px; border-radius: 6px; font-weight: bold; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; transition: background 0.2s; }
  .btn-print:hover { background: #4f46e5; }
  
  @media print {
    .actions-bar { display: none; }
    body { max-width: 100%; margin: 0; padding: 0; }
    .stat-card { background: #fff !important; border: 1px solid #ddd; }
  }
</style></head><body>
  <div class="actions-bar">
    <span style="font-weight: 600; color: #4b5563;">Rapport de Test Automatisé</span>
    <button onclick="window.print()" class="btn-print">
      🖨️ Enregistrer en PDF / Imprimer
    </button>
  </div>

  <h1>AI QA Execution Report</h1>
  <p style="color: #6b7280; font-size: 14px;">Run ID: <strong>${runId}</strong> | Date de génération : ${new Date().toLocaleString()}</p>
  <span class="badge ${result.success ? 'pass' : 'fail'}">${result.success ? 'PASSED' : 'FAILED'}</span>
 
  <div class="section">
    <h2>Summary</h2>
    <div class="stats">
      <div class="stat-card"><div class="stat-num">${result.failedTests ? result.failedTests.length : 0}</div><div class="stat-label">Failures</div></div>
      <div class="stat-card"><div class="stat-num">${healing ? healing.totalHealed || 0 : 0}</div><div class="stat-label">Healed</div></div>
      <div class="stat-card"><div class="stat-num">${healing && healing.defects ? healing.defects.length : 0}</div><div class="stat-label">Defects</div></div>
      <div class="stat-card"><div class="stat-num">${result.duration ? (result.duration / 1000).toFixed(1) + 's' : 'N/A'}</div><div class="stat-label">Duration</div></div>
    </div>
  </div>

  ${healing && healing.defects && healing.defects.length > 0 ? `
  <div class="section">
    <h2>Defects</h2>
    <table><tr><th>Test</th><th>Type</th><th>Verdict</th></tr>
    ${healing.defects.map(d => `<tr><td>${d.test}</td><td>${d.classification}</td><td>${d.verdict}</td></tr>`).join('')}
    </table>
  </div>` : ''}

  <div class="section">
    <h2>Full Report</h2>
    <pre>${report || result.output || 'No detailed report'}</pre>
  </div>

  <div class="footer">
    Generated by AI QA Pipeline | ${new Date().toISOString()}
  </div>
</body></html>`;

  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.setHeader('Content-Disposition', 'inline');
  res.send(html);
});

router.get('/pdf/:runId', (req, res) => {
  const project = resolveProject(req);
  if (!project) return res.status(404).send('Project not found');

  const bridge = pm.getBridge(project.id);
  const runId = resolveRunId(req.params.runId, bridge);
  if (!runId) return res.status(404).send('No runs found');

  const result = bridge.getRunResult(runId);
  if (!result) return res.status(404).send('Run not found');

  const report = bridge.getFinalReport(runId);
  const healing = bridge.getHealingReport(runId);

  const lines = [];
  lines.push('='.repeat(60));
  lines.push('AI QA EXECUTION REPORT');
  lines.push('='.repeat(60));
  lines.push('');
  lines.push(`Run ID: ${runId}`);
  lines.push(`Date: ${new Date().toLocaleDateString()}`);
  lines.push(`Status: ${result.success ? 'PASSED' : 'FAILED'}`);
  lines.push(`Duration: ${result.duration ? (result.duration / 1000).toFixed(1) + 's' : 'N/A'}`);
  lines.push('');
  lines.push('-'.repeat(60));
  lines.push('RESULTS');
  lines.push('-'.repeat(60));
  lines.push(`Failures: ${result.failedTests ? result.failedTests.length : 0}`);
  lines.push(`Healed: ${healing ? healing.totalHealed || 0 : 0}`);
  lines.push(`Defects: ${healing && healing.defects ? healing.defects.length : 0}`);
  lines.push('');

  if (healing && healing.defects && healing.defects.length > 0) {
    lines.push('-'.repeat(60));
    lines.push('DEFECTS');
    lines.push('-'.repeat(60));
    healing.defects.forEach(d => {
      lines.push(`  [${d.verdict}] ${d.test}`);
      lines.push(`  Type: ${d.classification}`);
      lines.push(`  ${d.error ? d.error.substring(0, 150) : ''}`);
      if (d.screenshot) lines.push(`  Screenshot: ${d.screenshot}`);
      lines.push('');
    });
  }

  if (report) {
    lines.push('-'.repeat(60));
    lines.push('FULL REPORT');
    lines.push('-'.repeat(60));
    lines.push(report.substring(0, 3000));
  }

  lines.push('');
  lines.push('='.repeat(60));
  lines.push(`Generated: ${new Date().toISOString()}`);
  lines.push('='.repeat(60));

  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="qa-report-${runId}.txt"`);
  res.setHeader('Content-Description', 'AI QA Test Report');
  res.send(lines.join('\n'));
});

module.exports = router;
