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

const root = path.resolve(__dirname, "..");
const candidates = process.platform === "win32" ? ["py", "python"] : ["python3", "python"];
const env = { ...process.env };
env.PYTHONPATH = env.PYTHONPATH ? `${path.join(root, "src")}${path.delimiter}${env.PYTHONPATH}` : path.join(root, "src");
const args = process.argv.slice(2);

if (args[0] === "editor") {
  const editor = path.join(root, "bin", "build-corpus-editor.js");
  const result = spawnSync(process.execPath, [editor, ...args.slice(1)], {
    stdio: "inherit",
    cwd: root,
    env: { ...env, BUILD_CORPUS_ROOT: root },
  });
  process.exit(result.status ?? 1);
}

if (process.platform === "win32" && args.includes("--uninstall-windows")) {
  const result = spawnSync(process.execPath, [path.join(root, "bin", "postinstall.js"), "--uninstall"], {
    stdio: "inherit",
    cwd: root,
    env,
  });
  process.exit(result.status ?? 1);
}

let result = null;
for (const candidate of candidates) {
  const args = candidate === "py"
    ? ["-3", "-m", "build_corpus.exporter", ...process.argv.slice(2)]
    : ["-m", "build_corpus.exporter", ...process.argv.slice(2)];
  result = spawnSync(candidate, args, { stdio: "inherit", cwd: process.cwd(), env });
  if (result.error && result.error.code === "ENOENT") continue;
  process.exit(result.status ?? 1);
}

console.error("Build Corpus requires Python 3.10+ on PATH.");
process.exit(1);
