import { r as formatErrorMessage } from "./errors-CGMew-1w.js";
import { t as restoreTerminalState } from "./restore-DOhcxwFr.js";
import { d as pathExists, m as resolveUserPath } from "./utils-CE5zxr9Z.js";
import { r as DEFAULT_BOOTSTRAP_FILENAME } from "./workspace-CnnxQiol.js";
import { n as resolveCliName } from "./cli-name-CQICB27Q.js";
import { t as formatCliCommand } from "./command-format-BeJUeZeT.js";
import { n as buildGatewayInstallPlan, r as gatewayInstallErrorHint, t as resolveGatewayInstallToken } from "./gateway-install-token-i7vMHWqf.js";
import { n as GATEWAY_DAEMON_RUNTIME_OPTIONS, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-MHppfqEw.js";
import { t as resolveControlUiLinks } from "./control-ui-links-CwbPc9S7.js";
import { n as openUrl, t as detectBrowserOpenSupport } from "./browser-open-CtZ0gtJJ.js";
import { h as waitForGatewayReachable, i as formatControlUiSshHint, u as probeGatewayReachable } from "./onboard-helpers-Dea9ivZy.js";
import { i as isSystemdUserServiceAvailable } from "./systemd-BzKNKK7i.js";
import { r as resolveGatewayService, t as describeGatewayServiceRestart } from "./service-CP2j6WNs.js";
import { n as listConfiguredWebSearchProviders } from "./runtime-CEmhNOnx.js";
import { t as ensureControlUiAssetsBuilt } from "./control-ui-assets-A53m8hYI.js";
import { r as installCompletion } from "./completion-cli-B_YzBO2C.js";
import { r as healthCommand } from "./health-DORszRyW.js";
import { t as resolveSetupSecretInputString } from "./setup.secret-input-BR7Y2Hg1.js";
import { t as formatHealthCheckFailure } from "./health-format-lG7x3cNF.js";
import { r as ensureCompletionCacheExists, t as checkShellCompletionStatus } from "./doctor-completion-B12WhquS.js";
import { t as runTui } from "./tui-BtScIjan.js";
import path from "node:path";
import os from "node:os";
import fs from "node:fs/promises";
//#region src/wizard/setup.completion.ts
async function resolveProfileHint(shell) {
	const home = process.env.HOME || os.homedir();
	if (shell === "zsh") return "~/.zshrc";
	if (shell === "bash") return await pathExists(path.join(home, ".bashrc")) ? "~/.bashrc" : "~/.bash_profile";
	if (shell === "fish") return "~/.config/fish/config.fish";
	return "$PROFILE";
}
function formatReloadHint(shell, profileHint) {
	if (shell === "powershell") return "Restart your shell (or reload your PowerShell profile).";
	return `Restart your shell or run: source ${profileHint}`;
}
async function setupWizardShellCompletion(params) {
	const deps = {
		resolveCliName,
		checkShellCompletionStatus,
		ensureCompletionCacheExists,
		installCompletion,
		...params.deps
	};
	const cliName = deps.resolveCliName();
	const completionStatus = await deps.checkShellCompletionStatus(cliName);
	if (completionStatus.usesSlowPattern) {
		if (await deps.ensureCompletionCacheExists(cliName)) await deps.installCompletion(completionStatus.shell, true, cliName);
		return;
	}
	if (completionStatus.profileInstalled && !completionStatus.cacheExists) {
		await deps.ensureCompletionCacheExists(cliName);
		return;
	}
	if (!completionStatus.profileInstalled) {
		if (!(params.flow === "quickstart" ? true : await params.prompter.confirm({
			message: `Enable ${completionStatus.shell} shell completion for ${cliName}?`,
			initialValue: true
		}))) return;
		if (!await deps.ensureCompletionCacheExists(cliName)) {
			await params.prompter.note(`Failed to generate completion cache. Run \`${cliName} completion --install\` later.`, "Shell completion");
			return;
		}
		await deps.installCompletion(completionStatus.shell, true, cliName);
		const profileHint = await resolveProfileHint(completionStatus.shell);
		await params.prompter.note(`Shell completion installed. ${formatReloadHint(completionStatus.shell, profileHint)}`, "Shell completion");
	}
}
//#endregion
//#region src/wizard/setup.finalize.ts
async function finalizeSetupWizard(options) {
	const { flow, opts, baseConfig, nextConfig, settings, prompter, runtime } = options;
	let gatewayProbe = { ok: true };
	const withWizardProgress = async (label, options, work) => {
		const progress = prompter.progress(label);
		try {
			return await work(progress);
		} finally {
			progress.stop(typeof options.doneMessage === "function" ? options.doneMessage() : options.doneMessage);
		}
	};
	const systemdAvailable = process.platform === "linux" ? await isSystemdUserServiceAvailable() : true;
	if (process.platform === "linux" && !systemdAvailable) await prompter.note("Systemd user services are unavailable. Skipping lingering checks and service install.", "Systemd");
	if (process.platform === "linux" && systemdAvailable) {
		const { ensureSystemdUserLingerInteractive } = await import("./systemd-linger-WPxNRIRJ.js");
		await ensureSystemdUserLingerInteractive({
			runtime,
			prompter: {
				confirm: prompter.confirm,
				note: prompter.note
			},
			reason: "Linux installs use a systemd user service by default. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.",
			requireConfirm: false
		});
	}
	const explicitInstallDaemon = typeof opts.installDaemon === "boolean" ? opts.installDaemon : void 0;
	let installDaemon;
	if (explicitInstallDaemon !== void 0) installDaemon = explicitInstallDaemon;
	else if (process.platform === "linux" && !systemdAvailable) installDaemon = false;
	else if (flow === "quickstart") installDaemon = true;
	else installDaemon = await prompter.confirm({
		message: "安装网关服务（推荐）",
		initialValue: true
	});
	if (process.platform === "linux" && !systemdAvailable && installDaemon) {
		await prompter.note("Systemd user services are unavailable; skipping service install. Use your container supervisor or `docker compose up -d`.", "Gateway service");
		installDaemon = false;
	}
	if (installDaemon) {
		const daemonRuntime = flow === "quickstart" ? DEFAULT_GATEWAY_DAEMON_RUNTIME : await prompter.select({
			message: "网关服务运行时",
			options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
			initialValue: opts.daemonRuntime ?? "node"
		});
		if (flow === "quickstart") await prompter.note("QuickStart uses Node for the Gateway service (stable + supported).", "Gateway service runtime");
		const service = resolveGatewayService();
		const loaded = await service.isLoaded({ env: process.env });
		let restartWasScheduled = false;
		if (loaded) {
			const action = await prompter.select({
				message: "网关服务已安装",
				options: [
					{
						value: "restart",
						label: "重启"
					},
					{
						value: "reinstall",
						label: "重新安装"
					},
					{
						value: "skip",
						label: "跳过"
					}
				]
			});
			if (action === "restart") {
				let restartDoneMessage = "Gateway service restarted.";
				await withWizardProgress("Gateway service", { doneMessage: () => restartDoneMessage }, async (progress) => {
					progress.update("Restarting Gateway service…");
					const restartStatus = describeGatewayServiceRestart("Gateway", await service.restart({
						env: process.env,
						stdout: process.stdout
					}));
					restartDoneMessage = restartStatus.progressMessage;
					restartWasScheduled = restartStatus.scheduled;
				});
			} else if (action === "reinstall") await withWizardProgress("Gateway service", { doneMessage: "Gateway service uninstalled." }, async (progress) => {
				progress.update("Uninstalling Gateway service…");
				await service.uninstall({
					env: process.env,
					stdout: process.stdout
				});
			});
		}
		if (!loaded || !restartWasScheduled && loaded && !await service.isLoaded({ env: process.env })) {
			const progress = prompter.progress("Gateway service");
			let installError = null;
			try {
				progress.update("Preparing Gateway service…");
				const tokenResolution = await resolveGatewayInstallToken({
					config: nextConfig,
					env: process.env
				});
				for (const warning of tokenResolution.warnings) await prompter.note(warning, "Gateway service");
				if (tokenResolution.unavailableReason) installError = [
					"Gateway install blocked:",
					tokenResolution.unavailableReason,
					"Fix gateway auth config/token input and rerun setup."
				].join(" ");
				else {
					const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
						env: process.env,
						port: settings.port,
						runtime: daemonRuntime,
						warn: (message, title) => prompter.note(message, title),
						config: nextConfig
					});
					progress.update("Installing Gateway service…");
					await service.install({
						env: process.env,
						stdout: process.stdout,
						programArguments,
						workingDirectory,
						environment
					});
				}
			} catch (err) {
				installError = formatErrorMessage(err);
			} finally {
				progress.stop(installError ? "网关服务安装失败。" : "网关服务已安装。");
			}
			if (installError) {
				await prompter.note(`网关服务安装失败：${installError}`, "Gateway");
				await prompter.note(gatewayInstallErrorHint(), "Gateway");
			}
		}
	}
	if (!opts.skipHealth) {
		const probeLinks = resolveControlUiLinks({
			bind: nextConfig.gateway?.bind ?? "loopback",
			port: settings.port,
			customBindHost: nextConfig.gateway?.customBindHost,
			basePath: void 0
		});
		gatewayProbe = await waitForGatewayReachable({
			url: probeLinks.wsUrl,
			token: settings.gatewayToken,
			deadlineMs: 15e3
		});
		if (gatewayProbe.ok) try {
			await healthCommand({
				json: false,
				timeoutMs: 1e4
			}, runtime);
		} catch (err) {
			runtime.error(formatHealthCheckFailure(err));
			await prompter.note(["Docs:", "https://github.com/Kaiji-Z/kaijibot/issues"].join("\n"), "Health check help");
		}
		else if (installDaemon) {
			runtime.error(formatHealthCheckFailure(new Error(gatewayProbe.detail ?? `gateway did not become reachable at ${probeLinks.wsUrl}`)));
			await prompter.note(["Docs:", "https://github.com/Kaiji-Z/kaijibot/issues"].join("\n"), "Health check help");
		} else await prompter.note([
			"Gateway not detected yet.",
			"Setup was run without Gateway service install, so no background gateway is expected.",
			`Start now: ${formatCliCommand("kaijibot gateway run")}`,
			`Or rerun with: ${formatCliCommand("kaijibot onboard --install-daemon")}`,
			`Or skip this probe next time: ${formatCliCommand("kaijibot onboard --skip-health")}`
		].join("\n"), "Gateway");
	}
	const controlUiEnabled = nextConfig.gateway?.controlUi?.enabled ?? baseConfig.gateway?.controlUi?.enabled ?? true;
	if (!opts.skipUi && controlUiEnabled) {
		const controlUiAssets = await ensureControlUiAssetsBuilt(runtime);
		if (!controlUiAssets.ok && controlUiAssets.message) runtime.error(controlUiAssets.message);
	}
	await prompter.note("", "Optional apps");
	const controlUiBasePath = nextConfig.gateway?.controlUi?.basePath ?? baseConfig.gateway?.controlUi?.basePath;
	const links = resolveControlUiLinks({
		bind: settings.bind,
		port: settings.port,
		customBindHost: settings.customBindHost,
		basePath: controlUiBasePath
	});
	const authedUrl = settings.authMode === "token" && settings.gatewayToken ? `${links.httpUrl}#token=${encodeURIComponent(settings.gatewayToken)}` : links.httpUrl;
	let resolvedGatewayPassword = "";
	if (settings.authMode === "password") try {
		resolvedGatewayPassword = await resolveSetupSecretInputString({
			config: nextConfig,
			value: nextConfig.gateway?.auth?.password,
			path: "gateway.auth.password",
			env: process.env
		}) ?? "";
	} catch (error) {
		await prompter.note(["Could not resolve gateway.auth.password SecretRef for setup auth.", formatErrorMessage(error)].join("\n"), "Gateway auth");
	}
	if (opts.skipHealth || !gatewayProbe.ok) gatewayProbe = await probeGatewayReachable({
		url: links.wsUrl,
		token: settings.authMode === "token" ? settings.gatewayToken : void 0,
		password: settings.authMode === "password" ? resolvedGatewayPassword : ""
	});
	const gatewayStatusLine = gatewayProbe.ok ? "Gateway: reachable" : `Gateway: not detected${gatewayProbe.detail ? ` (${gatewayProbe.detail})` : ""}`;
	const bootstrapPath = path.join(resolveUserPath(options.workspaceDir), DEFAULT_BOOTSTRAP_FILENAME);
	const hasBootstrap = await fs.access(bootstrapPath).then(() => true).catch(() => false);
	await prompter.note([
		`Web UI: ${links.httpUrl}`,
		settings.authMode === "token" && settings.gatewayToken ? `Web UI (with token): ${authedUrl}` : void 0,
		`Gateway WS: ${links.wsUrl}`,
		gatewayStatusLine,
		"Docs: https://github.com/Kaiji-Z/kaijibot"
	].filter(Boolean).join("\n"), "Control UI");
	let controlUiOpened = false;
	let controlUiOpenHint;
	let hatchChoice = null;
	let launchedTui = false;
	if (!opts.skipUi && gatewayProbe.ok) {
		if (hasBootstrap) await prompter.note([
			"This is the defining action that makes your agent you.",
			"Please take your time.",
			"The more you tell it, the better the experience will be.",
			"我们将发送唤醒消息来激活机器人。"
		].join("\n"), "Start TUI (best option!)");
		await prompter.note([
			"Gateway token: shared auth for the Gateway + Control UI.",
			"Stored in: $KAIJIBOT_CONFIG_PATH (default: ~/.kaijibot/kaijibot.json) under gateway.auth.token, or in KAIJIBOT_GATEWAY_TOKEN.",
			`View token: ${formatCliCommand("kaijibot config get gateway.auth.token")}`,
			`Generate token: ${formatCliCommand("kaijibot doctor --generate-gateway-token")}`,
			"Web UI keeps dashboard URL tokens in memory for the current tab and strips them from the URL after load.",
			`Open the dashboard anytime: ${formatCliCommand("kaijibot dashboard --no-open")}`,
			"If prompted: paste the token into Control UI settings (or use the tokenized dashboard URL)."
		].join("\n"), "Token");
		hatchChoice = await prompter.select({
			message: "你想怎样启动你的机器人？",
			options: [
				{
					value: "tui",
					label: "在 TUI 中启动（推荐）"
				},
				{
					value: "web",
					label: "打开 Web 控制面板"
				},
				{
					value: "later",
					label: "稍后再说"
				}
			],
			initialValue: "tui"
		});
		if (hatchChoice === "tui") {
			restoreTerminalState("pre-setup tui", { resumeStdinIfPaused: true });
			await runTui({
				url: links.wsUrl,
				token: settings.authMode === "token" ? settings.gatewayToken : void 0,
				password: settings.authMode === "password" ? resolvedGatewayPassword : "",
				deliver: false,
				message: hasBootstrap ? "你好！我是你的 KaijiBot 助手。" : void 0
			});
			launchedTui = true;
		} else if (hatchChoice === "web") {
			if ((await detectBrowserOpenSupport()).ok) {
				controlUiOpened = await openUrl(authedUrl);
				if (!controlUiOpened) controlUiOpenHint = formatControlUiSshHint({
					port: settings.port,
					basePath: controlUiBasePath,
					token: settings.authMode === "token" ? settings.gatewayToken : void 0
				});
			} else controlUiOpenHint = formatControlUiSshHint({
				port: settings.port,
				basePath: controlUiBasePath,
				token: settings.authMode === "token" ? settings.gatewayToken : void 0
			});
			await prompter.note([
				`Dashboard link (with token): ${authedUrl}`,
				controlUiOpened ? "Opened in your browser. Keep that tab to control KaijiBot." : "Copy/paste this URL in a browser on this machine to control KaijiBot.",
				controlUiOpenHint
			].filter(Boolean).join("\n"), "Dashboard ready");
		} else await prompter.note(`When you're ready: ${formatCliCommand("kaijibot dashboard --no-open")}`, "Later");
	} else if (opts.skipUi) await prompter.note("Skipping Control UI/TUI prompts.", "Control UI");
	await prompter.note(["Back up your agent workspace.", "Docs: https://github.com/Kaiji-Z/kaijibot"].join("\n"), "Workspace backup");
	await prompter.note("安全提示：不要将 Gateway 暴露在公网，API Key 不要放在 agent 可访问的路径下。", "安全须知");
	await setupWizardShellCompletion({
		flow,
		prompter
	});
	if (!opts.skipUi && gatewayProbe.ok && settings.authMode === "token" && Boolean(settings.gatewayToken) && hatchChoice === null) {
		if ((await detectBrowserOpenSupport()).ok) {
			controlUiOpened = await openUrl(authedUrl);
			if (!controlUiOpened) controlUiOpenHint = formatControlUiSshHint({
				port: settings.port,
				basePath: controlUiBasePath,
				token: settings.gatewayToken
			});
		} else controlUiOpenHint = formatControlUiSshHint({
			port: settings.port,
			basePath: controlUiBasePath,
			token: settings.gatewayToken
		});
		await prompter.note([
			`Dashboard link (with token): ${authedUrl}`,
			controlUiOpened ? "Opened in your browser. Keep that tab to control KaijiBot." : "Copy/paste this URL in a browser on this machine to control KaijiBot.",
			controlUiOpenHint
		].filter(Boolean).join("\n"), "Dashboard ready");
	}
	const { describeCodexNativeWebSearch } = await import("./codex-native-web-search-B7USpnFn.js");
	const codexNativeSummary = describeCodexNativeWebSearch(nextConfig);
	const webSearchProvider = nextConfig.tools?.web?.search?.provider;
	const webSearchEnabled = nextConfig.tools?.web?.search?.enabled;
	const configuredSearchProviders = listConfiguredWebSearchProviders({ config: nextConfig });
	if (webSearchProvider) {
		const { resolveExistingKey, hasExistingKey, hasKeyInEnv } = await import("./onboard-search-BtW5U2GQ.js");
		const entry = configuredSearchProviders.find((e) => e.id === webSearchProvider);
		const label = entry?.label ?? webSearchProvider;
		const storedKey = entry ? resolveExistingKey(nextConfig, webSearchProvider) : void 0;
		const keyConfigured = entry ? hasExistingKey(nextConfig, webSearchProvider) : false;
		const envAvailable = entry ? hasKeyInEnv(entry) : false;
		const hasKey = keyConfigured || envAvailable;
		const keySource = storedKey ? "API key: stored in config." : keyConfigured ? "API key: configured via secret reference." : envAvailable ? `API key: provided via ${entry?.envVars.join(" / ")} env var.` : void 0;
		if (!entry) await prompter.note([
			`Web search provider ${label} is selected but unavailable under the current plugin policy.`,
			"web_search will not work until the provider is re-enabled or a different provider is selected.",
			`  ${formatCliCommand("kaijibot configure --section web")}`,
			"",
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
		else if (webSearchEnabled !== false && hasKey) await prompter.note([
			"Web search is enabled, so your agent can look things up online when needed.",
			"",
			`Provider: ${label}`,
			...keySource ? [keySource] : [],
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
		else if (!hasKey) await prompter.note([
			`Provider ${label} is selected but no API key was found.`,
			"web_search will not work until a key is added.",
			`  ${formatCliCommand("kaijibot configure --section web")}`,
			"",
			`Get your key at: ${entry?.signupUrl ?? "https://github.com/Kaiji-Z/kaijibot"}`,
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
		else await prompter.note([
			`Web search (${label}) is configured but disabled.`,
			`Re-enable: ${formatCliCommand("kaijibot configure --section web")}`,
			"",
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
	} else {
		const { hasExistingKey, hasKeyInEnv } = await import("./onboard-search-BtW5U2GQ.js");
		const legacyDetected = configuredSearchProviders.find((e) => hasExistingKey(nextConfig, e.id) || hasKeyInEnv(e));
		if (legacyDetected) await prompter.note([`Web search is available via ${legacyDetected.label} (auto-detected).`, "Docs: https://github.com/Kaiji-Z/kaijibot"].join("\n"), "Web search");
		else if (codexNativeSummary) await prompter.note([
			"Managed web search provider was skipped.",
			codexNativeSummary,
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
		else await prompter.note([
			"Web search was skipped. You can enable it later:",
			`  ${formatCliCommand("kaijibot configure --section web")}`,
			"",
			"Docs: https://github.com/Kaiji-Z/kaijibot"
		].join("\n"), "Web search");
	}
	if (codexNativeSummary) await prompter.note([
		codexNativeSummary,
		"Used only for Codex-capable models.",
		"Docs: https://github.com/Kaiji-Z/kaijibot"
	].join("\n"), "Codex native search");
	await prompter.note("接下来：探索 KaijiBot 的认知功能，与你的机器人开始对话。", "What now");
	await prompter.outro(controlUiOpened ? "配置完成。控制面板已打开，保持该标签页即可管理 KaijiBot。" : "配置完成。");
	return { launchedTui };
}
//#endregion
export { finalizeSetupWizard };
