/**
 * Spawns the launcher for ~3s; expects java -jar to stay alive (MCP server on stdio).
 */
import { spawn } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
const launcher = path.join(root, "bin", "mcp-sonarqube-launcher.mjs");

const p = spawn(process.execPath, [launcher], {
  cwd: root,
  env: {
    ...process.env,
    STORAGE_PATH: process.env.STORAGE_PATH || "C:\\tools\\sonarqube-mcp-storage",
    SONARQUBE_URL: process.env.SONARQUBE_URL || "https://sonar.cicd.wdprapps.disney.com/",
    SONARQUBE_TOKEN: process.env.SONARQUBE_TOKEN || "",
  },
  stdio: ["ignore", "pipe", "pipe"],
});

let stderr = "";
p.stderr.on("data", (d) => {
  stderr += d.toString();
});

const t = setTimeout(() => {
  p.kill("SIGTERM");
}, 3500);

p.on("exit", (code, signal) => {
  clearTimeout(t);
  const ok =
    signal === "SIGTERM" ||
    (code === null && signal) ||
    code === 143;
  if (ok) {
    console.log("smoke-test OK: SonarQube MCP process stayed up until SIGTERM.");
    process.exit(0);
  }
  console.error("smoke-test FAIL: unexpected exit", { code, signal });
  if (stderr) console.error(stderr.slice(-1200));
  process.exit(1);
});

p.on("error", (err) => {
  console.error("smoke-test FAIL:", err.message);
  process.exit(1);
});
