#!/usr/bin/env node
/**
 * Bootstrap script: extracts test cases from the existing report/test-plan.html
 * and generates editor/data/testcases.json with the enriched structure.
 *
 * Run once:  node editor/bootstrap-from-report.js
 */

const fs = require('fs');
const path = require('path');
const { enrichTestCase } = require('./lib/enrich');

const REPORTS_DIR = path.join(__dirname, 'output', 'reports');
const OUTPUT_FILE = path.join(__dirname, 'data', 'testcases.json');

console.log('Looking for latest automation report in output/reports/...');

// Find the latest *_qa_automation.html file
const files = fs.readdirSync(REPORTS_DIR)
  .filter(f => f.endsWith('_qa_automation.html'))
  .map(f => ({
    name: f,
    time: fs.statSync(path.join(REPORTS_DIR, f)).mtime.getTime()
  }))
  .sort((a, b) => b.time - a.time);

if (files.length === 0) {
  console.error('ERROR: No qa_automation.html reports found in editor/output/reports/');
  console.error('Please run the editor and use Export → Full Report at least once.');
  process.exit(1);
}

const latestReport = path.join(REPORTS_DIR, files[0].name);
console.log(`Using latest report: ${latestReport}`);

const html = fs.readFileSync(latestReport, 'utf8');

// Extract the TESTS = [...] array using regex (simple but effective for this case)
const match = html.match(/const TESTS = (\[[\s\S]*?\]);/);

if (!match) {
  console.error('ERROR: Could not find TESTS array in the report file.');
  process.exit(1);
}

let tests;
try {
  // eslint-disable-next-line no-eval
  tests = eval('(' + match[1] + ')');
} catch (e) {
  console.error('Failed to parse TESTS array:', e.message);
  process.exit(1);
}

console.log(`Found ${tests.length} test cases.`);

// Convert + enrich with smart defaults (same logic used in the report modal)
const enriched = tests.map(t => {
  const base = {
    id: t.id,
    group: t.group,
    module: t.module,
    action: t.action,
    description: t.description,
    status: t.status,
    file: t.file,
    manualReason: t.manualReason || undefined,
    partialNotes: t.partialNotes || undefined
  };

  const rich = enrichTestCase(base);
  return {
    ...base,
    steps: rich.steps,
    automatable: rich.automatable,
    notYet: rich.notYet,
    dependencies: rich.dependencies
  };
});

fs.writeFileSync(OUTPUT_FILE, JSON.stringify(enriched, null, 2));

console.log(`✅ Generated ${OUTPUT_FILE} with ${enriched.length} fully enriched test cases.`);
console.log('   All automatable / not-automatable / steps / dependencies are pre-loaded.');
console.log('You can now start the editor: cd editor && npm start');
