#!/usr/bin/env node
"use strict";

const { spawnSync } = require("node:child_process");
const path = require("node:path");

const DEFAULT_TASKS = [
  "scripts/task451-local-markdown-conflict-resolution-ui-smoke.js",
  "scripts/task503-local-pptx-upload-filetree-open-smoke.js",
  "scripts/task458-local-create-page-no-conflict-smoke.js",
  "scripts/task504-local-md-external-conflict-recovery-smoke.js",
  "scripts/task508-local-md-multitab-conflict-smoke.js",
  "scripts/task509-local-upload-save-409-orphan-smoke.js",
];

function requestedTasks() {
  const raw = String(process.env.MNOTE_CONFLICT_REGRESSION_TASKS || "").trim();
  if (!raw) return DEFAULT_TASKS;
  return raw.split(",").map((item) => item.trim()).filter(Boolean);
}

function runTask(scriptPath) {
  const absolute = path.resolve(process.cwd(), scriptPath);
  const result = spawnSync(process.execPath, [absolute], {
    cwd: process.cwd(),
    env: process.env,
    stdio: "inherit",
  });
  if (result.error) throw result.error;
  if (result.status !== 0) {
    throw new Error(`${scriptPath} failed with status ${result.status}`);
  }
}

function main() {
  const tasks = requestedTasks();
  for (const task of tasks) {
    console.log(`[task510] running ${task}`);
    runTask(task);
  }
  console.log(JSON.stringify({ ok: true, tasks }, null, 2));
}

main();
