import { extractJsonFromText } from './src/vl/workflow-executor.js';

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

console.log('\n── Workflow Executor JSON Repair ──');

const raw = `\`\`\`json
{
  "section": {
    "id": "AnalyticsOverview",
    "interactiveElements": [],
  },
  "components": [],
  "updatedMeta": {
    "sections": [
      {
        "sectionId": "AnalyticsOverview",
        "internalMethods": [
          { "kind": "METHOD", "name": "loadAnalytics", "returns": "{success:BOOL}" }
        ],
`;

const repaired = extractJsonFromText(raw);
assert(repaired, 'extractJsonFromText should recover truncated fenced JSON');

const parsed = JSON.parse(repaired);
assert(parsed.section.id === 'AnalyticsOverview', 'recovered JSON should preserve section.id');
assert(Array.isArray(parsed.updatedMeta.sections), 'recovered JSON should preserve updatedMeta.sections');

const truncatedStringRaw = `\`\`\`json
{
  "updatedMeta": {
    "sections": [
      {
        "globalVars": [
          {"name": "gradeOptions", "type": "[{value:STRING,label:STRING}]", "default": "[{value:\\"大一\\",label:\\"大一\\"},{value:\\"大二\\",label:\\"大二\\"},{value:\\"大三\\",label:\\""}
`;

const repairedTruncatedString = extractJsonFromText(truncatedStringRaw);
assert(repairedTruncatedString, 'extractJsonFromText should recover truncated unterminated strings');

const parsedTruncatedString = JSON.parse(repairedTruncatedString);
assert(
  parsedTruncatedString.updatedMeta.sections[0].globalVars[0].name === 'gradeOptions',
  'recovered truncated string JSON should preserve nested fields'
);

console.log('PASS test-workflow-executor-json-repair.js');
