import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { spawn } from "node:child_process";
//#region src/gateway/respawn.ts
/**
* Process Respawn - Process respawn logic
*/
init_logger();
const log = createLogger("ProcessRespawn");
const SUPERVISOR_HINT_ENV_VARS = [
	"LAUNCH_JOB_LABEL",
	"LAUNCH_JOB_NAME",
	"INVOCATION_ID",
	"SYSTEMD_EXEC_PID",
	"JOURNAL_STREAM",
	"XOPC_SERVICE_MARKER"
];
function isTruthy(value) {
	if (!value) return false;
	const normalized = value.trim().toLowerCase();
	return [
		"1",
		"true",
		"yes",
		"on"
	].includes(normalized);
}
function hasSupervisorHint(env = process.env) {
	return SUPERVISOR_HINT_ENV_VARS.some((key) => {
		const value = env[key];
		return typeof value === "string" && value.trim().length > 0;
	});
}
/**
* Restart gateway process
* - Supervised environment: exit and let supervisor restart
* - XOPC_NO_RESPAWN=1: in-process restart
* - Otherwise: spawn detached child, then exit
*/
function restartGatewayProcessWithFreshPid() {
	if (isTruthy(process.env.XOPC_NO_RESPAWN)) {
		log.info("Respawn disabled (XOPC_NO_RESPAWN)");
		return { mode: "disabled" };
	}
	if (hasSupervisorHint(process.env)) {
		log.info("Detected supervisor environment, exiting for supervisor restart");
		return { mode: "supervised" };
	}
	try {
		const args = [...process.execArgv, ...process.argv.slice(1)];
		log.info({ args }, "Spawning new gateway process");
		const child = spawn(process.execPath, args, {
			env: process.env,
			detached: true,
			stdio: "inherit"
		});
		child.unref();
		log.info({ pid: child.pid }, "New process spawned, exiting");
		return {
			mode: "spawned",
			pid: child.pid ?? void 0
		};
	} catch (err) {
		const detail = err instanceof Error ? err.message : String(err);
		log.error({ err }, "Failed to spawn new process");
		return {
			mode: "failed",
			detail
		};
	}
}
//#endregion
export { restartGatewayProcessWithFreshPid };

//# sourceMappingURL=respawn.js.map