import { s as createSubsystemLogger } from "./entry.js";
import { z as loadConfig } from "./auth-profiles-CgnoZiYS.js";
import "./agent-scope-Cezno7_M.js";
import "./utils-CD6tCvSG.js";
import "./core-root-CmA71BTT.js";
import "./logger-BcqRk323.js";
import "./exec-CaapFZaD.js";
import "./registry-CBFkaKwt.js";
import "./github-copilot-token-DHTToceK.js";
import "./manifest-registry-DdFBL-mx.js";
import "./version-sf9dgjHP.js";
import "./image-ops-DxLQocoR.js";
import "./chrome-CNj5RXTP.js";
import "./tailscale-5K9XNlhO.js";
import "./tailnet-mjXbAxqf.js";
import "./ws-GlDBWD0H.js";
import "./auth-V2FS08vr.js";
import { c as resolveBrowserControlAuth, i as resolveBrowserConfig, r as registerBrowserRoutes, s as ensureBrowserControlAuth, t as createBrowserRouteContext } from "./server-context-BF4RP1eP.js";
import "./path-alias-guards-CNxRjVah.js";
import "./paths-BDDFj5Fw.js";
import "./redact-CC_d52A1.js";
import "./errors-DAcI6n_m.js";
import "./fs-safe-qdP8sV7U.js";
import "./proxy-env-B6UxsfXo.js";
import "./store-B5eeaWQa.js";
import "./ports-D8nInYfq.js";
import "./trash-CrF5N5Zh.js";
import { n as installBrowserCommonMiddleware, t as installBrowserAuthMiddleware } from "./server-middleware-BniDse6Q.js";
import { n as stopKnownBrowserProfiles, t as ensureExtensionRelayForProfiles } from "./server-lifecycle-BH1bn6N4.js";
import { t as isPwAiLoaded } from "./runtime-whatsapp-login.runtime-DU2sMuXH.js";
import express from "express";

//#region src/browser/server.ts
let state = null;
const logServer = createSubsystemLogger("browser").child("server");
async function startBrowserControlServerFromConfig() {
	if (state) return state;
	const cfg = loadConfig();
	const resolved = resolveBrowserConfig(cfg.browser, cfg);
	if (!resolved.enabled) return null;
	let browserAuth = resolveBrowserControlAuth(cfg);
	let browserAuthBootstrapFailed = false;
	try {
		const ensured = await ensureBrowserControlAuth({ cfg });
		browserAuth = ensured.auth;
		if (ensured.generatedToken) logServer.info("No browser auth configured; generated gateway.auth.token automatically.");
	} catch (err) {
		logServer.warn(`failed to auto-configure browser auth: ${String(err)}`);
		browserAuthBootstrapFailed = true;
	}
	if (browserAuthBootstrapFailed && !browserAuth.token && !browserAuth.password) {
		logServer.error("browser control startup aborted: authentication bootstrap failed and no fallback auth is configured.");
		return null;
	}
	const app = express();
	installBrowserCommonMiddleware(app);
	installBrowserAuthMiddleware(app, browserAuth);
	registerBrowserRoutes(app, createBrowserRouteContext({
		getState: () => state,
		refreshConfigFromDisk: true
	}));
	const port = resolved.controlPort;
	const server = await new Promise((resolve, reject) => {
		const s = app.listen(port, "127.0.0.1", () => resolve(s));
		s.once("error", reject);
	}).catch((err) => {
		logServer.error(`gensparx browser server failed to bind 127.0.0.1:${port}: ${String(err)}`);
		return null;
	});
	if (!server) return null;
	state = {
		server,
		port,
		resolved,
		profiles: /* @__PURE__ */ new Map()
	};
	await ensureExtensionRelayForProfiles({
		resolved,
		onWarn: (message) => logServer.warn(message)
	});
	const authMode = browserAuth.token ? "token" : browserAuth.password ? "password" : "off";
	logServer.info(`Browser control listening on http://127.0.0.1:${port}/ (auth=${authMode})`);
	return state;
}
async function stopBrowserControlServer() {
	const current = state;
	if (!current) return;
	await stopKnownBrowserProfiles({
		getState: () => state,
		onWarn: (message) => logServer.warn(message)
	});
	if (current.server) await new Promise((resolve) => {
		current.server?.close(() => resolve());
	});
	state = null;
	if (isPwAiLoaded()) try {
		await (await import("./pw-ai-Bga3Sw5D.js")).closePlaywrightBrowserConnection();
	} catch {}
}

//#endregion
export { startBrowserControlServerFromConfig, stopBrowserControlServer };