/**
 * generate-test-plan.js
 * Generates a self-contained, fully inline-styled HTML Test Plan
 * for manual execution by testers.
 *
 * Output: editor/output/testplans/YYYY-MM-DD_HH-MM-SS_{baseName}.html
 */

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

const OUTPUT_DIR = path.join(__dirname, '..', 'output', 'testplans');

function generateTestPlan(selectedTests, baseName = 'Manual-Test-Plan') {
  if (!Array.isArray(selectedTests) || selectedTests.length === 0) {
    throw new Error('No test cases selected for the Test Plan');
  }

  // 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 safeBase = baseName.replace(/[^a-zA-Z0-9-_]/g, '').slice(0, 60) || 'Manual-Test-Plan';
  const filename = `${timestamp}_${safeBase}.html`;
  const finalPath = path.join(OUTPUT_DIR, filename);

  // Group tests by group
  const grouped = {};
  selectedTests.forEach(test => {
    const g = test.group || 'Other';
    if (!grouped[g]) grouped[g] = [];
    grouped[g].push(test);
  });

  const groups = Object.keys(grouped).sort();

  // Build HTML
  const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manual Test Plan - ${safeBase}</title>
<style>
  body { font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 1.45; color: #222; margin: 20px; background: #fff; }
  h1 { font-size: 22px; margin-bottom: 4px; }
  h2 { font-size: 16px; margin-top: 24px; margin-bottom: 8px; border-bottom: 2px solid #333; padding-bottom: 4px; }
  table { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
  th, td { border: 1px solid #999; padding: 6px 8px; vertical-align: top; }
  th { background: #f0f0f0; text-align: left; font-weight: 600; }
  .meta { margin-bottom: 16px; color: #555; }
  .test-id { font-family: monospace; font-weight: 600; }
  .steps { margin: 4px 0; padding-left: 18px; }
  .field-label { font-weight: 600; font-size: 11px; color: #444; margin-top: 6px; }
  textarea, select { width: 100%; box-sizing: border-box; font-size: 12px; }
  textarea { min-height: 50px; }
  .header { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 12px; }
  .generated { font-size: 11px; color: #666; }
</style>
</head>
<body>

<div class="header">
  <div>
    <h1>Manual Test Plan</h1>
    <div class="meta"><strong>${safeBase}</strong> — Generated on ${now.toLocaleString()}</div>
  </div>
  <div class="generated">Total cases: ${selectedTests.length}</div>
</div>

<table>
  <tr>
    <th style="width: 18%;">Test ID</th>
    <th style="width: 28%;">Description &amp; Expected Result</th>
    <th style="width: 22%;">Steps</th>
    <th style="width: 12%;">Severity</th>
    <th style="width: 20%;">Result / Comments</th>
  </tr>

${groups.map(group => `
  <tr>
    <td colspan="5" style="background:#e8e8e8; font-weight:700; padding:8px 10px;">${group}</td>
  </tr>
  ${grouped[group].map(test => {
    const expected = test.description || '';
    const stepsHtml = (test.steps || []).map((s, i) => `<li>${escapeHtml(s)}</li>`).join('');
    const depsHtml = (test.dependencies || []).map(d => `<div>${escapeHtml(d.label)}: ${escapeHtml(d.value)}</div>`).join('');

    return `
    <tr>
      <td class="test-id">${escapeHtml(test.id)}</td>
      <td>
        <strong>${escapeHtml(test.description || '')}</strong>
        <div class="field-label">Expected Result</div>
        <textarea>${escapeHtml(expected)}</textarea>
      </td>
      <td>
        <ol class="steps">${stepsHtml}</ol>
        ${depsHtml ? `<div class="field-label">Dependencies</div><div style="font-size:11px;">${depsHtml}</div>` : ''}
      </td>
      <td>
        <select>
          <option>Low</option>
          <option>Medium</option>
          <option selected>High</option>
          <option>Critical</option>
        </select>
      </td>
      <td>
        <div class="field-label">Status</div>
        <select>
          <option>Pass</option>
          <option>Fail</option>
          <option>Blocked</option>
          <option selected>N/A</option>
        </select>
        <div class="field-label" style="margin-top:8px;">Actual Result / Comments</div>
        <textarea></textarea>
      </td>
    </tr>`;
  }).join('')}
`).join('')}

</table>

<p style="font-size:11px; color:#666; margin-top:30px;">
  Generated by QA Automation Test Plan Editor • All results and comments should be filled by the tester.
</p>

</body>
</html>`;

  fs.writeFileSync(finalPath, html);
  console.log(`✅ Manual Test Plan generated: ${finalPath}`);
  return finalPath;
}

function escapeHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

module.exports = { generateTestPlan };