import { c as normalizeOptionalString } from "./string-coerce-mnp54Vah.js";
import { t as formatCliCommand } from "./command-format-CKGmlpAQ.js";
import { m as resolveSecretInputRef } from "./types.secrets-_0JOMGE5.js";
import { t as shouldRequireGatewayTokenForInstall } from "./auth-install-policy-2_eneEl5.js";
import { r as hasAmbiguousGatewayAuthModeConfig } from "./auth-mode-policy-Byq0myX3.js";
import { t as resolveGatewayAuthToken } from "./auth-token-resolution-DpRryhzq.js";
import "./auth-Cb6BsbaQ.js";
import { n as resolveGatewayAuth } from "./auth-resolve-BSKl_nHz.js";
import { n as isUnsafeGatewayTailscaleNoAuth, t as formatUnsafeGatewayTailscaleNoAuthMessage } from "./gateway-tailscale-auth-policy-DLytnhv-.js";
import { d as readConfigFileSnapshotForWrite } from "./io-meLURSOC.js";
import { i as replaceConfigFile } from "./config-R-DNt3t0.js";
import { t as randomToken } from "./random-token-hQenuzDT.js";
//#region src/commands/gateway-install-token.ts
async function maybePersistAutoGeneratedGatewayInstallToken(params) {
	try {
		const prepared = params.configSnapshot && params.configWriteOptions ? {
			snapshot: params.configSnapshot,
			writeOptions: params.configWriteOptions
		} : await readConfigFileSnapshotForWrite();
		const snapshot = params.configSnapshot ?? prepared.snapshot;
		if (snapshot.exists && !snapshot.valid) {
			params.warnings.push("Warning: config file exists but is invalid; skipping token persistence.");
			return params.token;
		}
		const baseConfig = snapshot.exists ? snapshot.sourceConfig ?? snapshot.config : {};
		const existingTokenRef = resolveSecretInputRef({
			value: baseConfig.gateway?.auth?.token,
			defaults: baseConfig.secrets?.defaults
		}).ref;
		const baseConfigToken = existingTokenRef || typeof baseConfig.gateway?.auth?.token !== "string" ? void 0 : normalizeOptionalString(baseConfig.gateway.auth.token);
		if (!existingTokenRef && !baseConfigToken) {
			await replaceConfigFile({
				nextConfig: {
					...baseConfig,
					gateway: {
						...baseConfig.gateway,
						auth: {
							...baseConfig.gateway?.auth,
							mode: baseConfig.gateway?.auth?.mode ?? "token",
							token: params.token
						}
					}
				},
				snapshot,
				writeOptions: {
					baseSnapshot: snapshot,
					...prepared.writeOptions,
					...params.configWriteOptions,
					skipRuntimeSnapshotRefresh: true
				},
				afterWrite: { mode: "auto" }
			});
			return params.token;
		}
		if (baseConfigToken) return baseConfigToken;
		params.warnings.push("Warning: gateway.auth.token is SecretRef-managed; skipping plaintext token persistence.");
		return;
	} catch (err) {
		params.warnings.push(`Warning: could not persist token to config: ${String(err)}`);
		return params.token;
	}
}
function formatAmbiguousGatewayAuthModeReason() {
	return ["gateway.auth.token and gateway.auth.password are both configured while gateway.auth.mode is unset.", `Set ${formatCliCommand("openclaw config set gateway.auth.mode token")} or ${formatCliCommand("openclaw config set gateway.auth.mode password")}.`].join(" ");
}
async function resolveGatewayInstallToken(options) {
	const cfg = options.config;
	const warnings = [];
	if (hasAmbiguousGatewayAuthModeConfig(cfg)) return {
		token: void 0,
		tokenRefConfigured: Boolean(resolveSecretInputRef({
			value: cfg.gateway?.auth?.token,
			defaults: cfg.secrets?.defaults
		}).ref),
		unavailableReason: formatAmbiguousGatewayAuthModeReason(),
		warnings
	};
	const resolvedAuth = resolveGatewayAuth({
		authConfig: cfg.gateway?.auth,
		env: options.env,
		tailscaleMode: cfg.gateway?.tailscale?.mode ?? "off"
	});
	const tailscaleMode = cfg.gateway?.tailscale?.mode ?? "off";
	if (isUnsafeGatewayTailscaleNoAuth({
		authMode: resolvedAuth.mode,
		tailscaleMode
	})) return {
		token: void 0,
		tokenRefConfigured: false,
		unavailableReason: formatUnsafeGatewayTailscaleNoAuthMessage(tailscaleMode),
		warnings
	};
	const needsToken = shouldRequireGatewayTokenForInstall(cfg, options.env) && !resolvedAuth.allowTailscale;
	if (!needsToken) return {
		token: void 0,
		tokenRefConfigured: Boolean(resolveSecretInputRef({
			value: cfg.gateway?.auth?.token,
			defaults: cfg.secrets?.defaults
		}).ref),
		unavailableReason: void 0,
		warnings
	};
	const resolvedToken = await resolveGatewayAuthToken({
		cfg,
		env: options.env,
		explicitToken: options.explicitToken,
		envFallback: "no-secret-ref",
		unresolvedReasonStyle: "detailed"
	});
	const tokenRefConfigured = resolvedToken.secretRefConfigured;
	let token = resolvedToken.source === "secretRef" ? void 0 : resolvedToken.token;
	let unavailableReason;
	if (tokenRefConfigured && resolvedToken.source === "secretRef" && needsToken) warnings.push("gateway.auth.token is SecretRef-managed; install will not persist a resolved token in service environment. Ensure the SecretRef is resolvable in the daemon runtime context.");
	else if (tokenRefConfigured && !token && needsToken) unavailableReason = `gateway.auth.token SecretRef is configured but unresolved (${resolvedToken.unresolvedRefReason ?? "unknown reason"}).`;
	const allowAutoGenerate = options.autoGenerateWhenMissing ?? false;
	const persistGeneratedToken = options.persistGeneratedToken ?? false;
	if (!token && !tokenRefConfigured && allowAutoGenerate) {
		token = randomToken();
		warnings.push(persistGeneratedToken ? "No gateway token found. Auto-generated one and saving to config." : "No gateway token found. Auto-generated one for this run without saving to config.");
		if (persistGeneratedToken) token = await maybePersistAutoGeneratedGatewayInstallToken({
			token,
			config: cfg,
			configSnapshot: options.configSnapshot,
			configWriteOptions: options.configWriteOptions,
			warnings
		});
	}
	return {
		token,
		tokenRefConfigured,
		unavailableReason,
		warnings
	};
}
//#endregion
export { resolveGatewayInstallToken as t };
