/**
 * Embedded Playwright MCP server for ai-service.
 *
 * Manages lifecycle of the Playwright MCP server that enables
 * judge evaluations to interact with browsers.
 */
/**
 * Lifecycle manager for the embedded Playwright MCP server.
 *
 * Handles starting, stopping, and status checking of the server.
 * The server runs in the same process as the ai-service.
 */
export class PlaywrightMcpServerManager {
    server = null;
    logger;
    constructor(logger) {
        this.logger = logger;
    }
    /**
     * Starts the MCP server if not already running.
     *
     * @param options - Server configuration options
     * @returns Server URL for client connections
     * @throws Error if server fails to start
     */
    async start(options) {
        if (this.server) {
            this.logger.info(`Playwright MCP server already running at ${this.server.url}`);
            return this.server.url;
        }
        if (options?.connectWsEndpoint) {
            this.logger.info(`Starting embedded Playwright MCP server using existing browser at ${options.connectWsEndpoint}`);
        }
        else {
            this.logger.info(`Starting embedded Playwright MCP server: browser=${options?.browser || "chromium"}, headless=${options?.headless !== false}`);
        }
        try {
            // Import the embedded server implementation
            const { startEmbeddedPlaywrightMcpServer } = await import("./embedded-playwright-mcp-server.js");
            this.server = await startEmbeddedPlaywrightMcpServer({
                storageStatePath: options?.storageStatePath,
                jwt: options?.jwt,
                connectWsEndpoint: options?.connectWsEndpoint,
                storageStateData: options?.storageStateData,
                appUrl: options?.appUrl,
                initData: options?.initData,
                bootstrapData: options?.bootstrapData,
                sessionStorageData: options?.sessionStorageData,
                extraOrigins: options?.extraOrigins,
                saveArtifact: options?.saveArtifact,
                runTimestamp: options?.runTimestamp,
                logger: this.logger,
            });
            this.logger.info(`Playwright MCP server started successfully at ${this.server.url}`);
            return this.server.url;
        }
        catch (error) {
            // Use warn locally to avoid Datadog error alerts (expected when Playwright not configured)
            const isLocal = process.env.SUPERBLOCKS_SERVER_ENV === "local";
            const message = `Failed to start Playwright MCP server: ${String(error)}`;
            const meta = {
                error: {
                    kind: "McpServerStartError",
                    message: String(error),
                    stack: error instanceof Error ? error.stack : undefined,
                },
            };
            if (isLocal) {
                this.logger.warn(message, meta);
            }
            else {
                this.logger.error(message, meta);
            }
            throw new Error(`Failed to start MCP server: ${error}`);
        }
    }
    /**
     * Stops the MCP server if running.
     *
     * Gracefully shuts down the server and cleans up browser resources.
     */
    async stop() {
        if (!this.server) {
            this.logger.debug("Playwright MCP server not running, nothing to stop");
            return;
        }
        this.logger.info(`Stopping embedded Playwright MCP server at ${this.server.url}`);
        try {
            await this.server.close();
            this.server = null;
            this.logger.info("Playwright MCP server stopped successfully");
        }
        catch (error) {
            this.logger.error(`Error stopping Playwright MCP server: ${String(error)}`, {
                error: {
                    kind: "McpServerStopError",
                    message: String(error),
                    stack: error instanceof Error ? error.stack : undefined,
                },
            });
            // Clear server reference even on error
            this.server = null;
            throw error;
        }
    }
    /**
     * Checks if the server is currently running.
     *
     * @returns True if server is running
     */
    isRunning() {
        return this.server !== null;
    }
    /**
     * Gets the server URL if running.
     *
     * @returns Server URL or null if not running
     */
    getUrl() {
        return this.server?.url || null;
    }
    /**
     * Flushes the current action log and resets for a new session.
     * Call this after each test run to save logs without stopping the server.
     */
    async flushLog() {
        if (!this.server) {
            this.logger.debug("Playwright MCP server not running, nothing to flush");
            return;
        }
        try {
            await this.server.flushLog();
            this.logger.debug("Playwright action log flushed successfully");
        }
        catch (error) {
            this.logger.error(`Error flushing Playwright action log: ${String(error)}`, {
                error: {
                    kind: "McpServerFlushLogError",
                    message: String(error),
                    stack: error instanceof Error ? error.stack : undefined,
                },
            });
        }
    }
    /**
     * Captures interactive elements from the current page.
     * This provides DOM context that can be passed to the test LLM
     * so it knows which elements are available for interaction.
     *
     * @returns Array of interactive element info, or empty array if server not running
     */
    async captureInteractiveElements() {
        if (!this.server) {
            this.logger.debug("Playwright MCP server not running, cannot capture elements");
            return [];
        }
        try {
            const elements = await this.server.captureInteractiveElements();
            this.logger.debug(`Captured ${elements.length} interactive elements from page`);
            return elements;
        }
        catch (error) {
            this.logger.error(`Error capturing interactive elements: ${String(error)}`, {
                error: {
                    kind: "McpServerCaptureElementsError",
                    message: String(error),
                    stack: error instanceof Error ? error.stack : undefined,
                },
            });
            return [];
        }
    }
}
//# sourceMappingURL=playwright-server.js.map