"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pages = void 0;
exports.ensureBrowser = ensureBrowser;
exports.allocatePageId = allocatePageId;
exports.getPage = getPage;
exports.getPageId = getPageId;
exports.stopPlaywrightServer = stopPlaywrightServer;
const playwright_1 = require("playwright");
const logger_1 = require("../../../lib/logger");
// Browser lifecycle: shared instance across tool calls within a single
// server lifetime. Lazy-launched on first use, cleaned up via
// stopPlaywrightServer().
let browser = null;
exports.pages = new Map();
let pageCounter = 0;
async function ensureBrowser() {
    if (!browser || !browser.isConnected()) {
        browser = await playwright_1.chromium.launch({ headless: true });
        logger_1.loggerRegistry.info('[lt-mcp:playwright] browser launched');
    }
    return browser;
}
function allocatePageId() {
    return `page_${++pageCounter}`;
}
// Page lookup helpers
function getPage(pageId) {
    if (pageId) {
        const page = exports.pages.get(pageId);
        if (!page)
            throw new Error(`Page not found: ${pageId}`);
        return page;
    }
    const entries = Array.from(exports.pages.entries());
    if (entries.length === 0)
        throw new Error('No pages open. Navigate to a URL first.');
    return entries[entries.length - 1][1];
}
function getPageId(pageId) {
    if (pageId)
        return pageId;
    const entries = Array.from(exports.pages.entries());
    if (entries.length === 0)
        throw new Error('No pages open');
    return entries[entries.length - 1][0];
}
// Shutdown: close all pages and the browser.
async function stopPlaywrightServer() {
    for (const [id, page] of exports.pages) {
        try {
            await page.close();
        }
        catch { /* ignore */ }
        exports.pages.delete(id);
    }
    if (browser) {
        await browser.close();
        browser = null;
    }
    pageCounter = 0;
    logger_1.loggerRegistry.info('[lt-mcp:playwright] browser closed');
}
