import { init_paths, resolveConfigPath } from "../../../config/paths.js";
import { loadConfig } from "../../../config/loader.js";
import "../../../config/index.js";
import { isRestartEnabled } from "../../../config/commands.flags.js";
import { resolveGatewayService } from "../../../daemon/service.js";
import { authorizeGatewaySigusr1Restart, writeGatewayRestartIntentSync } from "../../../infra/restart.js";
import { findVerifiedGatewayListenerPidsOnPortSync, formatGatewayPidList, signalVerifiedGatewayPidSync } from "../../../infra/gateway-processes.js";
import { runServiceRestart, runServiceStop } from "./lifecycle-core.js";
import { DEFAULT_RESTART_HEALTH_ATTEMPTS, renderGatewayPortHealthDiagnostics, waitForGatewayHealthyListener } from "./restart-health.js";
import { parsePortFromArgs, renderGatewayServiceStartHints, resolveGatewayPortFromConfig } from "./shared.js";
//#region src/cli/commands/gateway/lifecycle.ts
/**
* Gateway lifecycle orchestration — OpenClaw-aligned service + unmanaged fallback.
*/
init_paths();
const POST_RESTART_HEALTH_ATTEMPTS = DEFAULT_RESTART_HEALTH_ATTEMPTS;
const POST_RESTART_HEALTH_DELAY_MS = 500;
async function resolveGatewayLifecyclePort(service) {
	return parsePortFromArgs((await (service ?? await resolveGatewayService()).readCommand(process.env).catch(() => null))?.programArguments) ?? resolveGatewayPortFromConfig();
}
function resolveVerifiedGatewayListenerPids(port) {
	return findVerifiedGatewayListenerPidsOnPortSync(port).filter((pid) => Number.isFinite(pid) && pid > 0);
}
async function assertUnmanagedGatewayRestartEnabled(port) {
	if (!isRestartEnabled(loadConfig(resolveConfigPath()))) throw new Error("Gateway restart is disabled in config (commands.restart=false); unmanaged SIGUSR1 restart would be ignored");
	try {
		const controller = new AbortController();
		const timeout = setTimeout(() => controller.abort(), 1e3);
		const response = await fetch(`http://127.0.0.1:${port}/api/health`, {
			method: "GET",
			signal: controller.signal
		});
		clearTimeout(timeout);
		if (!response.ok) return;
	} catch {}
}
async function stopGatewayWithoutServiceManager(port) {
	const pids = resolveVerifiedGatewayListenerPids(port);
	if (pids.length === 0) return null;
	for (const pid of pids) signalVerifiedGatewayPidSync(pid, "SIGTERM");
	return {
		result: "stopped",
		message: `Gateway stop signal sent to unmanaged process${pids.length === 1 ? "" : "es"} on port ${port}: ${formatGatewayPidList(pids)}.`
	};
}
async function restartGatewayWithoutServiceManager(port) {
	await assertUnmanagedGatewayRestartEnabled(port);
	const pids = resolveVerifiedGatewayListenerPids(port);
	if (pids.length === 0) return null;
	if (pids.length > 1) throw new Error(`multiple gateway processes are listening on port ${port}: ${formatGatewayPidList(pids)}; use "xopc gateway status" before retrying restart`);
	const targetPid = pids[0];
	if (process.platform === "win32") {
		writeGatewayRestartIntentSync({ targetPid });
		signalVerifiedGatewayPidSync(targetPid, "SIGTERM");
	} else {
		authorizeGatewaySigusr1Restart();
		signalVerifiedGatewayPidSync(targetPid, "SIGUSR1");
	}
	return {
		result: "restarted",
		message: `Gateway restart signal sent to unmanaged process on port ${port}: ${targetPid}.`
	};
}
async function runDaemonStop(options = {}) {
	const service = await resolveGatewayService();
	let gatewayPortPromise;
	await runServiceStop({
		service,
		opts: options,
		onNotLoaded: async () => {
			gatewayPortPromise ??= resolveGatewayLifecyclePort(service);
			return stopGatewayWithoutServiceManager(await gatewayPortPromise);
		}
	});
}
async function runDaemonRestart(options = {}) {
	const service = await resolveGatewayService();
	let restartedWithoutServiceManager = false;
	const restartPort = await resolveGatewayLifecyclePort(service);
	const restartHealthAttempts = POST_RESTART_HEALTH_ATTEMPTS;
	const restartWaitSeconds = Math.round(restartHealthAttempts * POST_RESTART_HEALTH_DELAY_MS / 1e3);
	await runServiceRestart({
		service,
		opts: options,
		renderStartHints: renderGatewayServiceStartHints,
		checkTokenDrift: true,
		onNotLoaded: async () => {
			const handled = await restartGatewayWithoutServiceManager(restartPort);
			if (handled) restartedWithoutServiceManager = true;
			return handled;
		},
		postRestartCheck: async ({ options: opts, fail }) => {
			if (!restartedWithoutServiceManager) return;
			const health = await waitForGatewayHealthyListener({
				port: restartPort,
				attempts: restartHealthAttempts,
				delayMs: POST_RESTART_HEALTH_DELAY_MS
			});
			if (health.healthy) return;
			const diagnostics = renderGatewayPortHealthDiagnostics(health);
			fail(`Gateway restart timed out after ${restartWaitSeconds}s waiting for health checks.`, ["xopc gateway status", "xopc doctor"], diagnostics, opts);
		}
	});
}
//#endregion
export { runDaemonRestart, runDaemonStop };

//# sourceMappingURL=lifecycle.js.map