/**
 * load-testcases.js
 *
 * ONE-TIME TRANSITION HELPER
 * Loads all testcases from the new YAML tree (testcases/) and converts them
 * to the legacy JSON shape that the editor frontend currently expects.
 *
 * This allows the UI to keep working unchanged while we migrate.
 *
 * TODO: Once the editor is updated to work natively with YAML, this can be removed.
 */

const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');

const TESTCASES_ROOT = path.join(__dirname, '..', '..', 'testcases');

/**
 * Recursively find all .yaml files under a directory (excluding SCHEMA.md etc.)
 */
function findYamlFiles(dir) {
  const results = [];
  const entries = fs.readdirSync(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      results.push(...findYamlFiles(fullPath));
    } else if (entry.name.endsWith('.yaml') && !entry.name.startsWith('SCHEMA')) {
      results.push(fullPath);
    }
  }
  return results;
}

/**
 * Convert a single YAML testcase object back to the legacy editor shape.
 */
function yamlToLegacy(yamlTest) {
  const cf = yamlTest.custom_fields || {};

  const legacy = {
    id: yamlTest.id,
    group: yamlTest.group,
    module: yamlTest.module,
    action: cf.original_action || 'check',
    description: yamlTest.description || yamlTest.title || '',
    status: yamlTest.automation_status || 'manual',
    file: yamlTest.file || '',
    steps: (yamlTest.steps || []).map(s => s.action || s),
    automatable: cf.original_automatable || [],
    notYet: cf.original_notYet || [],
    dependencies: cf.original_dependencies || [],
  };

  // Preserve extra fields that the old data sometimes had
  if (cf.manualReason) legacy.manualReason = cf.manualReason;
  if (cf.partialNotes) legacy.partialNotes = cf.partialNotes;

  return legacy;
}

/**
 * Main loader. Returns array of testcases in the old JSON format.
 */
function loadTestcases() {
  if (!fs.existsSync(TESTCASES_ROOT)) {
    return [];
  }

  const yamlFiles = findYamlFiles(TESTCASES_ROOT);
  const testcases = [];

  for (const filePath of yamlFiles) {
    try {
      const content = fs.readFileSync(filePath, 'utf8');
      const doc = yaml.load(content);
      if (doc && doc.id) {
        testcases.push(yamlToLegacy(doc));
      }
    } catch (err) {
      console.error('Failed to load YAML:', filePath, err.message);
    }
  }

  // Sort for stable output (same order every time)
  testcases.sort((a, b) => a.id.localeCompare(b.id));

  return testcases;
}

module.exports = { loadTestcases };
