#!/usr/bin/env node

import tls from "node:tls";
if (tls.getCACertificates && tls.setDefaultCACertificates) {
  try {
    tls.setDefaultCACertificates([
      ...tls.getCACertificates("default"),
      ...tls.getCACertificates("system"),
    ]);
  } catch {
    // System cert store may be inaccessible (e.g. sandboxed, containerized);
    // fall back to Node.js defaults.
  }
}

// Memory optimization: bypass oclif for parent process to avoid loading SDK (saves ~2GB)
const args = process.argv.slice(2);
const isDevCommand = args.includes("dev");
const isChildProcess = args.includes("--child");

const isWarmStandby = isDevCommand && args.includes("--warm");

if (isDevCommand && !isChildProcess && !isWarmStandby) {
  const { runAsLightweightParent } =
    await import("../dist/commands/dev-parent.js");

  const getFlag = (name) => args.includes(`--${name}`);
  const getFlagValue = (name) => {
    const prefix = `--${name}=`;
    const found = args.find((a) => a.startsWith(prefix));
    if (found) return found.slice(prefix.length);
    const idx = args.indexOf(`--${name}`);
    if (idx !== -1 && args[idx + 1] && !args[idx + 1].startsWith("--")) {
      return args[idx + 1];
    }
    return undefined;
  };

  await runAsLightweightParent({
    port: getFlagValue("port") ? parseInt(getFlagValue("port"), 10) : undefined,
    uploadFirst: getFlag("upload-first") || getFlag("u"),
    downloadFirst: getFlag("download-first") || getFlag("d"),
    forceTakeover: getFlag("force-takeover"),
    skipAutoUpgrade: getFlag("skip-auto-upgrade"),
    forceAutoUpgrade: getFlag("force-auto-upgrade"),
  });
} else {
  const { execute } = await import("@oclif/core");
  await execute({ dir: import.meta.url });
}
