import "./paths-Ci0O5IXU.js";
import "./globals-o4Hkf2nH.js";
import "./utils-DXDZXfi2.js";
import "./agent-scope-BUcFoOez.js";
import { t as createSubsystemLogger } from "./subsystem-CocLsF9M.js";
import "./core-root-D_XTmw6_.js";
import "./logger-B4_TThxB.js";
import "./exec-Bvzmovpq.js";
import { rn as loadConfig } from "./model-selection-YEFtLNSF.js";
import "./registry-CZfQ-snX.js";
import "./github-copilot-token-DqwKrrmK.js";
import "./boolean-C6Pbt2Ue.js";
import "./env-D3eA4r2n.js";
import "./manifest-registry-CqRtX07d.js";
import "./chrome-BBVmc3Se.js";
import "./tailscale-BxdRBeK_.js";
import "./tailnet-DONkFGUG.js";
import "./ws-DQm2qOSB.js";
import "./auth-BfvQ8QYP.js";
import { c as resolveBrowserControlAuth, i as resolveBrowserConfig, r as registerBrowserRoutes, s as ensureBrowserControlAuth, t as createBrowserRouteContext } from "./server-context-Ba0Dvxyt.js";
import "./path-alias-guards-Cjml85oF.js";
import "./paths-CI0-x9aa.js";
import "./redact-Nl4LWTUL.js";
import "./errors-D2aogITB.js";
import "./fs-safe-4KkU2jy0.js";
import "./proxy-env-QR3xvEvF.js";
import "./image-ops-BMK3YDnH.js";
import "./store-wnkoDS0q.js";
import "./ports-BJ314ngw.js";
import "./trash-C57Djqhz.js";
import { n as installBrowserCommonMiddleware, t as installBrowserAuthMiddleware } from "./server-middleware-Db5VJPvz.js";
import { n as stopKnownBrowserProfiles, t as ensureExtensionRelayForProfiles } from "./server-lifecycle-ChsLH-5K.js";
import { t as isPwAiLoaded } from "./runtime-whatsapp-login.runtime-tuSnDoWM.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-DTRPQK-O.js")).closePlaywrightBrowserConnection();
	} catch {}
}

//#endregion
export { startBrowserControlServerFromConfig, stopBrowserControlServer };