#!/usr/bin/env node
const path = require("node:path");
const { spawn } = require("node:child_process");
const fs = require("node:fs");

const root = path.resolve(__dirname, "..");
const callerCwd = process.cwd();
const candidates = [
  path.join(root, "BuildCorpusEditor.exe"),
  path.join(root, "dist", "windows-editor", "BuildCorpusEditor.exe"),
  path.join(root, "desktop", "BuildCorpusEditor", "bin", "Release", "net8.0-windows", "win-x64", "BuildCorpusEditor.exe"),
];
const exe = candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0];
const args = process.argv.slice(2);

if (args.includes("--help") || args.includes("-h")) {
  console.log(`regen-mde

Usage:
  regen-mde [document.md|document.docx] [options]
  mdeditor [document.md|document.docx] [options]
  regen-mdeditor [document.md|document.docx] [options]
  regen-mdeditor [document.md|document.docx] [options]
  build-corpus-editor [document.md|document.docx] [options]

Options:
  --foreground, --visible       Show the editor as an attached foreground process.
  --background                  Launch hidden/offscreen for smoke checks.
  --self-test                   Verify the editor bridge can open the document.
  --document-self-test          Open, edit, save Markdown, export Word, and reconvert.
  --smoke-ui                    Run the hidden UI smoke test.
  --out <dir>                   Output directory for document self-test.
  --help, -h                    Show this help.
`);
  process.exit(0);
}

const visible = args.includes("--foreground") || args.includes("--visible");
const background = args.includes("--background") || args.includes("--smoke-ui");
const launchArgs = normalizeLaunchArgs(args.filter((arg) => arg !== "--foreground" && arg !== "--visible"));

const child = spawn(exe, launchArgs, {
  cwd: root,
  stdio: "inherit",
  windowsHide: background,
  detached: background && !visible,
  env: {
    ...process.env,
    BUILD_CORPUS_ROOT: root,
  },
});

child.on("error", (error) => {
  console.error(`Build Corpus Editor executable not found: ${exe}`);
  console.error("Build it with: npm run editor:windows");
  console.error(error.message);
  process.exit(1);
});

child.on("exit", (code) => process.exit(code ?? 0));

function normalizeLaunchArgs(rawArgs) {
  const normalized = [];
  for (let index = 0; index < rawArgs.length; index += 1) {
    const arg = rawArgs[index];
    if (arg === "--out" && index < rawArgs.length - 1) {
      normalized.push(arg, resolveFromCaller(rawArgs[index + 1]));
      index += 1;
      continue;
    }
    if (index === 0 && !arg.startsWith("--")) {
      normalized.push(resolveFromCaller(arg));
      continue;
    }
    normalized.push(arg);
  }
  return normalized;
}

function resolveFromCaller(value) {
  if (!value || path.isAbsolute(value)) return value;
  return path.resolve(callerCwd, value);
}
