import { listPortListeners } from "../gateway/ports.js";
import { isGatewayArgv, parseProcCmdline } from "./gateway-process-argv.js";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
//#region src/infra/gateway-processes.ts
function readGatewayProcessArgsSync(pid) {
	if (process.platform === "linux") try {
		return parseProcCmdline(fs.readFileSync(`/proc/${pid}/cmdline`, "utf8"));
	} catch {
		return null;
	}
	if (process.platform === "darwin") {
		const ps = spawnSync("ps", [
			"-o",
			"command=",
			"-p",
			String(pid)
		], {
			encoding: "utf8",
			timeout: 1e3
		});
		if (ps.error || ps.status !== 0) return null;
		const command = ps.stdout.trim();
		return command ? command.split(/\s+/) : null;
	}
	if (process.platform === "win32") {
		const ps = spawnSync("powershell", [
			"-NoProfile",
			"-Command",
			`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`
		], {
			encoding: "utf8",
			timeout: 3e3
		});
		if (ps.error || ps.status !== 0) return null;
		const command = ps.stdout.trim();
		return command ? command.split(/\s+/) : null;
	}
	return null;
}
function signalVerifiedGatewayPidSync(pid, signal) {
	const args = readGatewayProcessArgsSync(pid);
	if (!args || !isGatewayArgv(args, { allowGatewayBinary: true })) throw new Error(`refusing to signal non-gateway process pid ${pid}`);
	if (signal === "SIGUSR1" && process.platform === "win32") throw new Error("SIGUSR1 is not supported on Windows; use SIGTERM with a restart intent file instead");
	process.kill(pid, signal);
}
function findGatewayPidsOnPortSync(port) {
	try {
		return listPortListeners(port).map((entry) => entry.pid).filter((pid) => Number.isFinite(pid) && pid > 0);
	} catch {
		return [];
	}
}
function findVerifiedGatewayListenerPidsOnPortSync(port) {
	return Array.from(new Set(findGatewayPidsOnPortSync(port))).filter((pid) => pid !== process.pid).filter((pid) => {
		const args = readGatewayProcessArgsSync(pid);
		return args != null && isGatewayArgv(args, { allowGatewayBinary: true });
	});
}
function formatGatewayPidList(pids) {
	return pids.join(", ");
}
//#endregion
export { findGatewayPidsOnPortSync, findVerifiedGatewayListenerPidsOnPortSync, formatGatewayPidList, readGatewayProcessArgsSync, signalVerifiedGatewayPidSync };

//# sourceMappingURL=gateway-processes.js.map