import { init_public_url, normalizePublicUrlOrNull } from "../config/public-url.js";
import { isNetworkAccessibleBindHost, resolveGatewayBindMode, resolveGatewayEffectiveHost } from "../config/gateway-bind.js";
import { enumerateLanGatewayCandidates } from "./tunnel-qr.js";
import { buildMobileConnectUrlOrder } from "./pair-url.js";
//#region src/tunnel/pair-context.ts
init_public_url();
function buildMobilePairContext(params) {
	const port = params.config.gateway?.port ?? 18790;
	const bindMode = resolveGatewayBindMode(params.config);
	const listenHost = resolveGatewayEffectiveHost(params.config);
	const lanListenReady = isNetworkAccessibleBindHost(listenHost);
	const lanEnumerated = enumerateLanGatewayCandidates(port);
	const candidates = lanEnumerated.map((entry) => ({
		kind: "lan",
		url: entry.url,
		label: entry.interfaceName,
		reachable: lanListenReady,
		...lanListenReady ? {} : { note: "requires_lan_bind" }
	}));
	const tunnelUrl = params.tunnelPublicUrl?.trim() || null;
	const tunnelConnected = params.tunnelConnected === true && Boolean(tunnelUrl);
	if (tunnelConnected && tunnelUrl) candidates.unshift({
		kind: "tunnel",
		url: tunnelUrl,
		reachable: true
	});
	const configuredReverseProxy = normalizePublicUrlOrNull(params.config.gateway?.publicUrl);
	const reverseProxyUrl = params.reverseProxyPublicUrl !== void 0 ? normalizePublicUrlOrNull(params.reverseProxyPublicUrl) : configuredReverseProxy;
	if (reverseProxyUrl) candidates.unshift({
		kind: "reverse-proxy",
		url: reverseProxyUrl,
		reachable: true
	});
	let recommended = {
		mode: null,
		url: null
	};
	if (reverseProxyUrl) recommended = {
		mode: "reverse-proxy",
		url: reverseProxyUrl
	};
	else if (tunnelConnected && tunnelUrl) recommended = {
		mode: "tunnel",
		url: tunnelUrl
	};
	else if (lanListenReady && lanEnumerated[0]) recommended = {
		mode: "lan",
		url: lanEnumerated[0].url
	};
	else if (lanEnumerated[0]) recommended = {
		mode: "lan",
		url: lanEnumerated[0].url
	};
	const pairingReady = Boolean(reverseProxyUrl || tunnelConnected || lanListenReady && lanEnumerated.length > 0);
	let blockReason;
	if (!pairingReady) blockReason = !lanListenReady && !tunnelConnected ? "GATEWAY_LOOPBACK_ONLY" : "NO_REACHABLE_URL";
	const lanUrlForConnect = lanListenReady && lanEnumerated[0] ? lanEnumerated[0].url : null;
	const hasUpstream = Boolean(reverseProxyUrl) || tunnelConnected;
	const connectUrls = buildMobileConnectUrlOrder({
		reverseProxyUrl,
		baseUrl: reverseProxyUrl ? reverseProxyUrl : tunnelConnected && tunnelUrl ? tunnelUrl : lanListenReady && recommended.url ? recommended.url : null,
		lanUrl: hasUpstream ? lanUrlForConnect : null,
		tunnelUrl: tunnelConnected ? tunnelUrl : null
	});
	return {
		port,
		bindMode,
		listenHost,
		pairingReady,
		...blockReason ? { blockReason } : {},
		candidates,
		recommended,
		connectUrls
	};
}
//#endregion
export { buildMobilePairContext };

//# sourceMappingURL=pair-context.js.map