import { u as resolveGatewayPort } from "./paths-B2cMK-wd.js";
import { t as formatCliCommand } from "./command-format-BORwwHyH.js";
import { _ as sleep } from "./utils-DvkbxKCZ.js";
import { d as resolveGatewayLaunchAgentLabel, g as resolveNodeLaunchAgentLabel, m as resolveGatewayWindowsTaskName, p as resolveGatewaySystemdServiceName } from "./paths-D_QOPpsq.js";
import { n as buildGatewayInstallPlan, r as gatewayInstallErrorHint } from "./auth-install-policy-CaDim72q.js";
import { n as GATEWAY_DAEMON_RUNTIME_OPTIONS, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-C4_-bMd5.js";
import { o as getResolvedLoggerSettings } from "./logger-BiJB5UNm.js";
import { t as resolveGatewayInstallToken } from "./gateway-install-token-VQ1HTzXF.js";
import { a as isSystemdUserServiceAvailable, m as classifySystemdUnavailableDetail } from "./systemd-CdXXLlky.js";
import { n as isLaunchAgentLoaded, o as repairLaunchAgentBootstrap, r as launchAgentPlistExists } from "./launchd-CsEDWcEx.js";
import "./config-B9rKdgUB.js";
import { r as resolveGatewayService, t as describeGatewayServiceRestart } from "./service-CG565my8.js";
import { a as inspectPortUsage, c as formatPortDiagnostics } from "./ports-CeWeqdIQ.js";
import { a as isSystemdUnavailableDetail, i as resolveDaemonContainerContext, o as renderSystemdUnavailableHints, r as formatRuntimeStatus, t as buildPlatformRuntimeLogHints } from "./runtime-hints-BP8FTQLN.js";
import { r as isWSLEnv, t as isWSL } from "./wsl-BJkxH6R1.js";
import { t as readLastGatewayErrorLine } from "./diagnostics-qdhCYEH2.js";
import { r as findSystemGatewayServices } from "./inspect-CJVSnNc6.js";
import "./logging-BQYx_Wtx.js";
import { t as note } from "./note-DRReSDjk.js";
import { n as formatHealthCheckFailure } from "./health-format-Dk684kZ5.js";
import { n as healthCommand } from "./health-uNPFxXHN.js";
import { a as resolveServiceRepairPolicy, i as isServiceRepairExternallyManaged, n as SERVICE_REPAIR_POLICY_ENV, r as confirmDoctorServiceRepair, t as EXTERNAL_SERVICE_REPAIR_NOTE } from "./doctor-service-repair-policy-BU_HRn5D.js";
//#region src/commands/doctor-format.ts
function formatGatewayRuntimeSummary(runtime) {
	return formatRuntimeStatus(runtime);
}
function buildGatewayRuntimeHints(runtime, options = {}) {
	const hints = [];
	if (!runtime) return hints;
	const platform = options.platform ?? process.platform;
	const env = options.env ?? process.env;
	const container = Boolean(resolveDaemonContainerContext(env));
	const fileLog = (() => {
		try {
			return getResolvedLoggerSettings().file;
		} catch {
			return null;
		}
	})();
	if (platform === "linux" && isSystemdUnavailableDetail(runtime.detail)) {
		hints.push(...renderSystemdUnavailableHints({
			wsl: isWSLEnv(),
			kind: classifySystemdUnavailableDetail(runtime.detail),
			container
		}));
		if (fileLog) hints.push(`File logs: ${fileLog}`);
		return hints;
	}
	if (runtime.cachedLabel && platform === "darwin") {
		const label = resolveGatewayLaunchAgentLabel(env.OPENCLAW_PROFILE);
		hints.push(`LaunchAgent label cached but plist missing. Clear with: launchctl bootout gui/$UID/${label}`);
		hints.push(`Then reinstall: ${formatCliCommand("openclaw gateway install", env)}`);
	}
	if (runtime.missingUnit) {
		hints.push(`Service not installed. Run: ${formatCliCommand("openclaw gateway install", env)}`);
		if (fileLog) hints.push(`File logs: ${fileLog}`);
		return hints;
	}
	if (runtime.missingSupervision && platform === "darwin") {
		hints.push(`LaunchAgent installed but not loaded. Run: ${formatCliCommand("openclaw gateway restart", env)}`);
		if (fileLog) hints.push(`File logs: ${fileLog}`);
		return hints;
	}
	if (runtime.status === "stopped") {
		hints.push("Service is loaded but not running (likely exited immediately).");
		if (fileLog) hints.push(`File logs: ${fileLog}`);
		hints.push(...buildPlatformRuntimeLogHints({
			platform,
			env,
			systemdServiceName: resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE),
			windowsTaskName: resolveGatewayWindowsTaskName(env.OPENCLAW_PROFILE)
		}));
	}
	return hints;
}
//#endregion
//#region src/commands/doctor-gateway-daemon-flow.ts
async function maybeRepairLaunchAgentBootstrap(params) {
	if (process.platform !== "darwin") return false;
	if (!await launchAgentPlistExists(params.env)) return false;
	if (await isLaunchAgentLoaded({ env: params.env })) return false;
	note("LaunchAgent 已安装但未在 launchd 中加载。", `${params.title} LaunchAgent`);
	if (params.serviceRepairExternal) {
		note(EXTERNAL_SERVICE_REPAIR_NOTE, `${params.title} LaunchAgent`);
		return false;
	}
	if (!await confirmDoctorServiceRepair(params.prompter, {
		message: `Repair ${params.title} LaunchAgent bootstrap now?`,
		initialValue: true
	})) return false;
	params.runtime.log(`Bootstrapping ${params.title} LaunchAgent...`);
	const repair = await repairLaunchAgentBootstrap({ env: params.env });
	if (!repair.ok) {
		params.runtime.error(`${params.title} LaunchAgent bootstrap failed: ${repair.detail ?? "unknown error"}`);
		return false;
	}
	if (!await isLaunchAgentLoaded({ env: params.env })) {
		params.runtime.error(`${params.title} LaunchAgent still not loaded after repair.`);
		return false;
	}
	note(`${params.title} LaunchAgent 已修复。`, `${params.title} LaunchAgent`);
	return true;
}
function renderBlockingSystemGatewayServices(services) {
	return [
		"System-level OpenClaw gateway service detected while the user gateway service is not installed.",
		...services.map((svc) => `- ${svc.label} (${svc.detail})`),
		"OpenClaw will not install a second user-level gateway service automatically.",
		"Run `openclaw gateway status --deep` or `openclaw doctor --deep` to inspect duplicate services.",
		`Set ${SERVICE_REPAIR_POLICY_ENV}=external if a system supervisor owns the gateway lifecycle.`
	].join("\n");
}
async function maybeRepairGatewayDaemon(params) {
	if (params.healthOk) return;
	const serviceRepairPolicy = resolveServiceRepairPolicy();
	const serviceRepairExternal = isServiceRepairExternallyManaged(serviceRepairPolicy);
	const service = resolveGatewayService();
	let loaded = false;
	try {
		loaded = await service.isLoaded({ env: process.env });
	} catch {
		loaded = false;
	}
	let serviceRuntime;
	if (loaded) serviceRuntime = await service.readRuntime(process.env).catch(() => void 0);
	if (process.platform === "darwin" && params.cfg.gateway?.mode !== "remote") {
		const gatewayRepaired = await maybeRepairLaunchAgentBootstrap({
			env: process.env,
			title: "Gateway",
			runtime: params.runtime,
			prompter: params.prompter,
			serviceRepairExternal
		});
		await maybeRepairLaunchAgentBootstrap({
			env: {
				...process.env,
				OPENCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel()
			},
			title: "Node",
			runtime: params.runtime,
			prompter: params.prompter,
			serviceRepairExternal
		});
		if (gatewayRepaired) {
			loaded = await service.isLoaded({ env: process.env });
			if (loaded) serviceRuntime = await service.readRuntime(process.env).catch(() => void 0);
		}
	}
	if (params.cfg.gateway?.mode !== "remote") {
		const diagnostics = await inspectPortUsage(resolveGatewayPort(params.cfg, process.env));
		if (diagnostics.status === "busy") note(formatPortDiagnostics(diagnostics).join("\n"), "网关端口");
		else if (loaded && serviceRuntime?.status === "running") {
			const lastError = await readLastGatewayErrorLine(process.env);
			if (lastError) note(`最近网关错误: ${lastError}`, "网关");
		}
	}
	if (!loaded) {
		if (process.platform === "linux") {
			if (!await isSystemdUserServiceAvailable().catch(() => false)) {
				note(renderSystemdUnavailableHints({
					wsl: await isWSL(),
					kind: "generic_unavailable"
				}).join("\n"), "网关");
				return;
			}
		}
		note("网关服务未安装。", "网关");
		if (params.cfg.gateway?.mode !== "remote") {
			if (process.platform === "linux") {
				const systemGatewayServices = await findSystemGatewayServices();
				if (systemGatewayServices.length > 0) {
					note(renderBlockingSystemGatewayServices(systemGatewayServices), "Gateway");
					return;
				}
			}
			if (serviceRepairExternal) {
				note(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
				return;
			}
			if (await confirmDoctorServiceRepair(params.prompter, {
				message: "现在安装网关服务？",
				initialValue: true
			}, serviceRepairPolicy)) {
				const daemonRuntime = await params.prompter.select({
					message: "网关服务运行时",
					options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
					initialValue: DEFAULT_GATEWAY_DAEMON_RUNTIME
				}, DEFAULT_GATEWAY_DAEMON_RUNTIME);
				const tokenResolution = await resolveGatewayInstallToken({
					config: params.cfg,
					env: process.env
				});
				for (const warning of tokenResolution.warnings) note(warning, "Gateway");
				if (tokenResolution.unavailableReason) {
					note([
						"Gateway service install aborted.",
						tokenResolution.unavailableReason,
						"Fix gateway auth config/token input and rerun doctor."
					].join("\n"), "Gateway");
					return;
				}
				const port = resolveGatewayPort(params.cfg, process.env);
				const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
					env: process.env,
					port,
					runtime: daemonRuntime,
					warn: (message, title) => note(message, title),
					config: params.cfg
				});
				try {
					await service.install({
						env: process.env,
						stdout: process.stdout,
						programArguments,
						workingDirectory,
						environment
					});
				} catch (err) {
					note(`网关服务安装失败：${String(err)}`, "网关");
					note(gatewayInstallErrorHint(), "Gateway");
				}
			}
		}
		return;
	}
	const summary = formatGatewayRuntimeSummary(serviceRuntime);
	const hints = buildGatewayRuntimeHints(serviceRuntime, {
		platform: process.platform,
		env: process.env
	});
	if (summary || hints.length > 0) {
		const lines = [];
		if (summary) lines.push(`Runtime: ${summary}`);
		lines.push(...hints);
		note(lines.join("\n"), "Gateway");
	}
	if (serviceRuntime?.status !== "running") {
		if (serviceRepairExternal) {
			note(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
			return;
		}
		if (await confirmDoctorServiceRepair(params.prompter, {
			message: "Start gateway service now?",
			initialValue: true
		}, serviceRepairPolicy)) {
			const restartStatus = describeGatewayServiceRestart("Gateway", await service.restart({
				env: process.env,
				stdout: process.stdout
			}));
			if (!restartStatus.scheduled) await sleep(1500);
			else note(restartStatus.message, "Gateway");
		}
	}
	if (process.platform === "darwin") {
		const label = resolveGatewayLaunchAgentLabel(process.env.OPENCLAW_PROFILE);
		note(`LaunchAgent loaded; stopping requires "${formatCliCommand("openclaw gateway stop")}" or launchctl bootout gui/$UID/${label}.`, "Gateway");
	}
	if (serviceRuntime?.status === "running") {
		if (serviceRepairExternal) {
			note(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
			return;
		}
		if (await confirmDoctorServiceRepair(params.prompter, {
			message: "现在重启网关服务？",
			initialValue: true
		}, serviceRepairPolicy)) {
			const restartStatus = describeGatewayServiceRestart("Gateway", await service.restart({
				env: process.env,
				stdout: process.stdout
			}));
			if (restartStatus.scheduled) {
				note(restartStatus.message, "Gateway");
				return;
			}
			await sleep(1500);
			try {
				await healthCommand({
					json: false,
					timeoutMs: 1e4
				}, params.runtime);
			} catch (err) {
				if (String(err).includes("gateway closed")) {
					note("网关未运行。", "网关");
					note(params.gatewayDetailsMessage, "网关连接");
				} else params.runtime.error(formatHealthCheckFailure(err));
			}
		}
	}
}
//#endregion
export { maybeRepairGatewayDaemon };
