import { spawn } from "node:child_process";

const npm = process.platform === "win32" ? "npm.cmd" : "npm";
const children = new Set();
let stopping = false;

function start(label, script) {
  const child = spawn(npm, ["run", script], {
    stdio: "inherit",
    env: process.env,
  });

  children.add(child);
  child.on("exit", (code, signal) => {
    children.delete(child);
    if (!stopping) {
      console.error(`\n[dev:all] ${label} 已停止 (${signal || `exit ${code}`})，正在關閉其他服務。`);
      stop(code ?? 1);
    }
  });
}

function stop(exitCode = 0) {
  if (stopping) return;
  stopping = true;

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

  setTimeout(() => {
    for (const child of children) {
      child.kill("SIGKILL");
    }
    process.exit(exitCode);
  }, 3000).unref();

  if (children.size === 0) process.exit(exitCode);
}

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

console.log("[dev:all] 啟動 API http://localhost:3000 與前端 http://localhost:5173");
start("API", "dev:server");
start("前端", "dev");
