/**
 * Service that manages a Playwright TraceRecordingBackend instance,
 * exposing browser tools + skyramp_export_zip for use by the Skyramp MCP.
 *
 * The Playwright fork is CJS; this project is ESM. We use createRequire
 * to bridge the module systems.
 */
import { createRequire } from "module";
import { logger } from "../utils/logger.js";
export class PlaywrightTraceService {
    _backend = null;
    _tools = [];
    _options;
    constructor(options) {
        this._options = options || {};
    }
    async initialize() {
        if (this._backend) {
            logger.info("PlaywrightTraceService already initialized");
            return;
        }
        try {
            // Dynamic require of CJS Playwright module from ESM context
            const require = createRequire(import.meta.url);
            const { TraceRecordingBackend } = require("playwright/lib/mcp/skyramp");
            this._backend = new TraceRecordingBackend({
                headless: this._options.headless,
                outputDir: this._options.outputDir || process.cwd(),
            });
            // Initialize with a synthetic client info
            await this._backend.initialize({
                name: "skyramp-mcp",
                version: "1.0.0",
                roots: [],
                timestamp: Date.now(),
            });
            this._tools = await this._backend.listTools();
            logger.info(`PlaywrightTraceService initialized with ${this._tools.length} tools`);
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            logger.error(`Failed to initialize PlaywrightTraceService: ${msg}`);
            throw error;
        }
    }
    isInitialized() {
        return this._backend !== null;
    }
    getTools() {
        return this._tools;
    }
    async callTool(name, args) {
        if (!this._backend) {
            return {
                content: [
                    {
                        type: "text",
                        text: "### Error\nPlaywright trace service not initialized. This is an internal error.",
                    },
                ],
                isError: true,
            };
        }
        return this._backend.callTool(name, args);
    }
    async shutdown() {
        if (this._backend) {
            this._backend.serverClosed?.();
            this._backend = null;
            this._tools = [];
            logger.info("PlaywrightTraceService shut down");
        }
    }
}
