import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
//#region src/browser/cdp-supervisor.ts
init_logger();
const log = createLogger("CDPSupervisor");
const DEFAULT_OPTIONS = {
	dialogPolicy: "auto_dismiss",
	dialogTimeoutSeconds: 300,
	maxConsoleEntries: 200
};
/**
* CDP Supervisor — persistent event listener for browser pages.
*
* Monitors Dialog events, console output, and frame navigation.
* Aligned with hermes-agent's `CDPSupervisor` pattern but using
* Playwright's high-level event API instead of raw CDP WebSocket.
*/
var CdpSupervisor = class {
	options;
	dialogQueue = [];
	consoleBuffer = [];
	attachedPages = /* @__PURE__ */ new WeakSet();
	dialogCounter = 0;
	pendingDialog = null;
	constructor(options) {
		this.options = {
			...DEFAULT_OPTIONS,
			...options
		};
	}
	/** Attach the supervisor to a page to begin monitoring. */
	attach(page) {
		if (this.attachedPages.has(page)) return;
		this.attachedPages.add(page);
		page.on("dialog", (dialog) => this._onDialog(dialog));
		page.on("console", (msg) => this._onConsole(msg));
		page.on("close", () => this.attachedPages.delete(page));
		log.debug("Supervisor attached to page");
	}
	/** Get all pending (unhandled) dialogs. */
	getPendingDialogs() {
		return this.dialogQueue.filter((d) => !d.handled);
	}
	/** Get all captured dialog events (including handled). */
	getAllDialogs() {
		return [...this.dialogQueue];
	}
	/** Get recent console entries. */
	getConsoleEntries(limit) {
		const max = limit ?? this.options.maxConsoleEntries;
		return this.consoleBuffer.slice(-max);
	}
	/** Handle a pending dialog by id or the most recent one. */
	async handleDialog(action, options) {
		let targetEvent;
		if (options?.dialogId) targetEvent = this.dialogQueue.find((d) => d.id === options.dialogId && !d.handled);
		else targetEvent = this.dialogQueue.findLast((d) => !d.handled);
		if (!targetEvent) return void 0;
		if (this.pendingDialog) {
			try {
				if (action === "accept") await this.pendingDialog.accept(options?.promptText ?? "");
				else await this.pendingDialog.dismiss();
			} catch {}
			this.pendingDialog = null;
		}
		targetEvent.handled = true;
		targetEvent.response = action === "accept" ? "accepted" : "dismissed";
		return targetEvent;
	}
	/** Clear all dialog history. */
	clearDialogs() {
		this.dialogQueue = [];
	}
	/** Clear console buffer. */
	clearConsole() {
		this.consoleBuffer = [];
	}
	_onDialog(dialog) {
		this.dialogCounter += 1;
		const event = {
			id: `dialog-${this.dialogCounter}`,
			type: dialog.type(),
			message: dialog.message(),
			defaultValue: dialog.defaultValue(),
			timestamp: Date.now(),
			handled: false
		};
		this.dialogQueue.push(event);
		this.pendingDialog = dialog;
		log.info({
			dialogId: event.id,
			type: event.type,
			message: event.message
		}, "Dialog detected");
		switch (this.options.dialogPolicy) {
			case "auto_accept":
				dialog.accept().then(() => {
					event.handled = true;
					event.response = "accepted";
					this.pendingDialog = null;
				}).catch(() => {});
				break;
			case "auto_dismiss":
				dialog.dismiss().then(() => {
					event.handled = true;
					event.response = "dismissed";
					this.pendingDialog = null;
				}).catch(() => {});
				break;
			case "must_respond":
				setTimeout(() => {
					if (!event.handled) dialog.dismiss().then(() => {
						event.handled = true;
						event.response = "dismissed";
						this.pendingDialog = null;
						log.warn({ dialogId: event.id }, "Dialog auto-dismissed after timeout");
					}).catch(() => {});
				}, this.options.dialogTimeoutSeconds * 1e3);
				break;
		}
	}
	_onConsole(msg) {
		const entry = {
			type: msg.type(),
			text: msg.text(),
			timestamp: Date.now()
		};
		this.consoleBuffer.push(entry);
		if (this.consoleBuffer.length > this.options.maxConsoleEntries * 1.5) this.consoleBuffer = this.consoleBuffer.slice(-this.options.maxConsoleEntries);
	}
};
//#endregion
export { CdpSupervisor };

//# sourceMappingURL=cdp-supervisor.js.map