#!/usr/bin/env node

// Raise V8's old-space ceiling before the app starts. A long agent turn retains
// the whole turn's state in-heap (messages, tool I/O, the render tree); Node's
// default old-space limit (~2GB on many machines) aborts the process fatally the
// moment it is crossed, losing the session mid-work. We re-exec once with more
// headroom unless the user pinned their own limit via NODE_OPTIONS. Dynamic
// imports + an async IIFE keep this working whether Node loads the file as ESM or
// CJS. If the re-exec cannot run for any reason, we fall through and start
// in-process rather than fail to launch.
(async () => {
  const raised =
    process.env.PERCH_CLI_HEAP_REEXEC === "1" ||
    /--max[-_]old[-_]space[-_]size/.test(process.env.NODE_OPTIONS ?? "");
  if (!raised) {
    const desiredMb = Number(process.env.PERCH_CLI_MAX_OLD_SPACE_MB || 4096);
    if (Number.isFinite(desiredMb) && desiredMb > 0) {
      try {
        const { spawnSync } = await import("node:child_process");
        const result = spawnSync(
          process.execPath,
          [`--max-old-space-size=${desiredMb}`, ...process.argv.slice(1)],
          { stdio: "inherit", env: { ...process.env, PERCH_CLI_HEAP_REEXEC: "1" } },
        );
        if (!result.error) {
          process.exit(result.status == null ? 1 : result.status);
        }
        // spawn failed: fall through and run in this process without the bump.
        console.error(result.error);
      } catch (error) {
        console.error(error);
      }
    }
  }
  await import("../dist/perch.mjs");
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
