import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { assertExposureConfig } from "../remote-access/exposure-guards.js";
import { startGatewayTailscaleExposure } from "./server-tailscale.js";
//#region src/gateway/tailscale-lifecycle.ts
init_logger();
const log = createLogger("TailscaleLifecycle");
let tailscaleCleanup = null;
let tailscaleState = {
	mode: "off",
	active: false,
	hostname: null,
	resetOnExit: true
};
function getTailscaleExposureState() {
	return { ...tailscaleState };
}
function resolveGatewayTailscaleMode(cfg, override) {
	if (override) return override;
	const envMode = process.env.XOPC_GATEWAY_TAILSCALE_MODE?.trim().toLowerCase();
	if (envMode === "serve" || envMode === "funnel" || envMode === "off") return envMode;
	return cfg.gateway?.tailscale?.mode ?? "off";
}
async function maybeStartTailscaleFromConfig(config, port, override) {
	const mode = resolveGatewayTailscaleMode(config, override);
	if (mode === "off") return;
	const resetOnExit = process.env.XOPC_GATEWAY_TAILSCALE_RESET_ON_EXIT === "1" || config.gateway?.tailscale?.resetOnExit !== false;
	tailscaleCleanup = await startGatewayTailscaleExposure({
		tailscaleMode: mode,
		resetOnExit,
		port
	});
	tailscaleState = {
		mode,
		active: true,
		hostname: null,
		resetOnExit
	};
	try {
		const { getTailnetHostname } = await import("../infra/tailscale.js");
		tailscaleState.hostname = await getTailnetHostname();
	} catch {}
}
async function stopTailscaleExposure() {
	if (tailscaleCleanup) {
		try {
			await tailscaleCleanup();
		} catch (err) {
			const em = err instanceof Error ? err.message : String(err);
			log.warn({
				err,
				errorMessage: em,
				phase: "tailscale_stop"
			}, `Tailscale cleanup failed: ${em}`);
		}
		tailscaleCleanup = null;
	}
	tailscaleState = {
		mode: "off",
		active: false,
		hostname: null,
		resetOnExit: true
	};
}
function assertTailscaleExposureCompatible(cfg) {
	assertExposureConfig(cfg);
}
function warnTailnetBindUnavailable(cfg, bindMode, bindHost) {
	if (bindMode === "tailnet" && bindHost === "127.0.0.1") log.warn({
		bindMode,
		bindHost,
		phase: "gateway_bind"
	}, "gateway.bind=tailnet but no Tailscale IPv4 found; falling back to loopback");
}
//#endregion
export { assertTailscaleExposureCompatible, getTailscaleExposureState, maybeStartTailscaleFromConfig, resolveGatewayTailscaleMode, stopTailscaleExposure, warnTailnetBindUnavailable };

//# sourceMappingURL=tailscale-lifecycle.js.map