import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { loadPlaywrightCoreModule } from "./playwright-doctor.js";
//#region src/browser/providers/browser-use.ts
init_logger();
const log = createLogger("BrowserProvider:BrowserUse");
/**
* Browser Use cloud browser provider.
*
* Connects to a Browser Use-managed session via CDP WebSocket.
* Requires `BROWSER_USE_API_KEY` or config-level `apiKey`.
*
* @see https://docs.browser-use.com
*/
var BrowserUseProvider = class {
	name = "browser-use";
	browser = null;
	context = null;
	sessionId = null;
	config;
	constructor(config) {
		this.config = config;
	}
	async connect() {
		const apiKey = this.config.apiKey || process.env.BROWSER_USE_API_KEY;
		if (!apiKey) throw new Error("Browser Use API key not configured (set BROWSER_USE_API_KEY or browser.cloudProvider config)");
		const response = await fetch("https://api.browser-use.com/api/v1/sessions", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				Authorization: `Bearer ${apiKey}`
			},
			body: JSON.stringify({})
		});
		if (!response.ok) {
			const errorText = await response.text().catch(() => "unknown");
			throw new Error(`Browser Use session creation failed (${response.status}): ${errorText}`);
		}
		const session = await response.json();
		this.sessionId = session.session_id;
		const pw = await loadPlaywrightCoreModule();
		const chromium = pw.chromium ?? pw.default?.chromium;
		if (!chromium?.connectOverCDP) throw new Error("playwright-core does not support connectOverCDP");
		this.browser = await chromium.connectOverCDP(session.ws_url);
		const contexts = this.browser.contexts();
		this.context = contexts.length > 0 ? contexts[0] : await this.browser.newContext();
		log.info({ sessionId: this.sessionId }, "Connected to Browser Use");
		return {
			browser: this.browser,
			context: this.context
		};
	}
	async disconnect() {
		if (this.browser) {
			await this.browser.close().catch(() => {});
			this.browser = null;
			this.context = null;
			log.info({ sessionId: this.sessionId }, "Disconnected from Browser Use");
			this.sessionId = null;
		}
	}
	isConnected() {
		return this.browser !== null && this.browser.isConnected();
	}
};
//#endregion
export { BrowserUseProvider };

//# sourceMappingURL=browser-use.js.map