/**
 * generate-report.js
 * Generates the automation analysis report (qa_automation.html) with timestamp.
 * Output location: editor/output/reports/
 */

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

const DATA_FILE = path.join(__dirname, '..', '..', 'legacy', 'data', 'testcases.json'); // legacy JSON (for export scripts)
const OUTPUT_DIR = path.join(__dirname, '..', '..', 'output', 'reports');

function generateReport() {
  const tests = JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));

  // Calculate statistics
  const total = tests.length;
  const automated = tests.filter(t => t.status === 'automated').length;
  const partial = tests.filter(t => t.status === 'partial').length;
  const manual = tests.filter(t => t.status === 'manual').length;

  const autoPct = total > 0 ? ((automated / total) * 100).toFixed(1) : 0;
  const partialPct = total > 0 ? ((partial / total) * 100).toFixed(1) : 0;
  const manualPct = total > 0 ? ((manual / total) * 100).toFixed(1) : 0;

  // Group counts for the bar chart
  const groups = [...new Set(tests.map(t => t.group))].sort();
  const groupStats = {};
  groups.forEach(g => {
    groupStats[g] = {
      automated: tests.filter(t => t.group === g && t.status === 'automated').length,
      partial: tests.filter(t => t.group === g && t.status === 'partial').length,
      manual: tests.filter(t => t.group === g && t.status === 'manual').length
    };
  });

  // Embed data
  const embeddedData = JSON.stringify(tests);

  const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>QA Automation Test Plan Report</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <style>
    body { background: #0b1120; color: #e2e8f0; font-family: system-ui, -apple-system, sans-serif; }
    .card { background: #1e2937; border: 1px solid #334155; }
    .status-automated { background:#052e16; color:#4ade80; }
    .status-partial { background:#451a03; color:#fbbf24; }
    .status-manual { background:#450a0a; color:#f87171; }
  </style>
</head>
<body class="text-sm">
  <div class="max-w-[1500px] mx-auto p-8">
    <div class="flex justify-between items-end mb-8">
      <div>
        <h1 class="text-3xl font-bold">QA Automation Test Plan Report</h1>
        <p class="text-[#64748b]">Generated from Test Case Editor • ${new Date().toISOString().slice(0,10)}</p>
      </div>
      <div class="text-right text-xs text-[#64748b]">
        ${total} test cases • ${autoPct}% automated
      </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-4 gap-4 mb-8">
      <div class="card p-5 rounded-2xl">
        <div class="text-[#64748b] text-xs">TOTAL TESTS</div>
        <div class="text-5xl font-bold mt-1">${total}</div>
      </div>
      <div class="card p-5 rounded-2xl border-l-4 border-emerald-500">
        <div class="text-emerald-400 text-xs">AUTOMATED</div>
        <div class="text-5xl font-bold text-emerald-400 mt-1">${automated}</div>
        <div class="text-xs mt-1">${autoPct}%</div>
      </div>
      <div class="card p-5 rounded-2xl border-l-4 border-amber-500">
        <div class="text-amber-400 text-xs">PARTIAL</div>
        <div class="text-5xl font-bold text-amber-400 mt-1">${partial}</div>
        <div class="text-xs mt-1">${partialPct}%</div>
      </div>
      <div class="card p-5 rounded-2xl border-l-4 border-red-500">
        <div class="text-red-400 text-xs">MANUAL</div>
        <div class="text-5xl font-bold text-red-400 mt-1">${manual}</div>
        <div class="text-xs mt-1">${manualPct}%</div>
      </div>
    </div>

    <div class="mb-4 text-[#64748b] text-xs font-semibold">TEST CASES</div>
    
    <div class="card rounded-2xl overflow-hidden">
      <table class="w-full">
        <thead class="bg-[#0f172a] text-[#64748b] text-xs">
          <tr>
            <th class="px-4 py-3 text-left">#</th>
            <th class="px-4 py-3 text-left">ID</th>
            <th class="px-4 py-3 text-left">Group</th>
            <th class="px-4 py-3">Status</th>
            <th class="px-4 py-3 text-left">Description</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-[#334155]">
          ${tests.map((t, i) => `
            <tr class="hover:bg-[#162032]">
              <td class="px-4 py-3 text-[#64748b]">${i+1}</td>
              <td class="px-4 py-3 font-mono text-xs">${t.id}</td>
              <td class="px-4 py-3">${t.group}</td>
              <td class="px-4 py-3">
                <span class="px-3 py-0.5 rounded-full text-xs font-semibold status-${t.status}">${t.status}</span>
              </td>
              <td class="px-4 py-3 text-[#cbd5e1]">${t.description}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>

    <div class="mt-8 text-center text-xs text-[#64748b]">
      Generated by Autotest • Data source: YAML under testcases/ (legacy JSON during transition)
    </div>
  </div>
</body>
</html>`;

  // Ensure output directory exists
  if (!fs.existsSync(OUTPUT_DIR)) {
    fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  }

  // Generate timestamped filename
  const now = new Date();
  const timestamp = now.toISOString().slice(0, 19).replace(/:/g, '-').replace('T', '_');
  const finalFilename = `${timestamp}_qa_automation.html`;
  const finalPath = path.join(OUTPUT_DIR, finalFilename);

  fs.writeFileSync(finalPath, html);

  console.log(`✅ Automation report generated: ${finalPath}`);
  console.log(`   ${total} tests | ${automated} automated (${autoPct}%)`);

  return finalPath;
}

if (require.main === module) {
  generateReport();
}

module.exports = { generateReport };
