const webHost = process.env.HOST || "0.0.0.0";
const webPort = process.env.PORT || "5173";
const apiHost = process.env.DASHBOARD_DEV_API_HOST || "127.0.0.1";
const apiPort = process.env.DASHBOARD_DEV_API_PORT || "5174";
const apiTarget = `http://${apiHost}:${apiPort}`;
export const apiServerArgs = [
  "--conditions=development",
  "src/server/index.ts",
] as const;

if (import.meta.main) {
  runDevServers();
}

export function runDevServers(): void {
  const children: Array<ReturnType<typeof Bun.spawn>> = [];
  let shuttingDown = false;

  function spawn(
    label: string,
    command: string[],
    env: Record<string, string> = {},
  ): void {
    const child = Bun.spawn(command, {
      env: {
        ...process.env,
        ...env,
      },
      stdin: "inherit",
      stdout: "inherit",
      stderr: "inherit",
    });
    children.push(child);

    void child.exited.then((code) => {
      if (shuttingDown) return;
      console.error(`${label} exited with status ${code}`);
      shutdown(code || 1);
    });
  }

  function shutdown(code = 0): void {
    if (shuttingDown) return;
    shuttingDown = true;

    for (const child of children) {
      child.kill();
    }

    void Promise.allSettled(children.map((child) => child.exited)).then(() => {
      process.exit(code);
    });
  }

  process.on("SIGINT", () => shutdown(0));
  process.on("SIGTERM", () => shutdown(0));

  spawn("api server", [process.execPath, ...apiServerArgs], {
    HOST: apiHost,
    PORT: apiPort,
  });

  spawn("vite dev server", [
    process.execPath,
    "x",
    "vite",
    "--host",
    webHost,
    "--port",
    webPort,
  ], {
    DASHBOARD_DEV_API_TARGET: apiTarget,
  });

  console.info(`Dashboard API proxy target: ${apiTarget}`);
}
