import { join } from "path";
import { CliError } from "../util/cli-contract.js";
import { getProjectRoot } from "../util/fs.js";
let activeSession;
export function getActiveBrowserSession() {
    return activeSession;
}
export function setActiveBrowserSession(session) {
    activeSession = session;
}
export function getBrowserSessionDir(projectRoot, sessionId) {
    const root = projectRoot ?? getProjectRoot();
    if (sessionId) {
        return join(root, ".omk", "browser", sessionId);
    }
    return join(root, ".omk", "browser");
}
export async function createBrowserSession(options) {
    const playwrightModuleName = process.env.NODE_ENV === "test"
        ? process.env.OMK_PLAYWRIGHT_MODULE ?? "playwright"
        : "playwright";
    let playwright;
    try {
        playwright = await import(playwrightModuleName);
    }
    catch {
        throw new CliError("Playwright is not installed. Run: npm install -D playwright");
    }
    const pw = playwright;
    const browser = await pw.chromium.launch({
        headless: options.headless ?? true,
    });
    const context = await browser.newContext({
        viewport: options.viewport ?? { width: 1280, height: 720 },
        deviceScaleFactor: options.deviceScaleFactor ?? 1,
    });
    const page = await context.newPage();
    await page.goto(options.url, { waitUntil: "networkidle" });
    const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
    const session = {
        sessionId,
        url: options.url,
        page,
        browser,
        createdAt: new Date().toISOString(),
        viewport: options.viewport ?? { width: 1280, height: 720 },
        deviceScaleFactor: options.deviceScaleFactor ?? 1,
    };
    activeSession = session;
    return session;
}
export async function closeBrowserSession(session) {
    const target = session ?? activeSession;
    if (!target)
        return;
    const browser = target.browser;
    if (browser && typeof browser.close === "function") {
        await browser.close();
    }
    if (activeSession?.sessionId === target.sessionId) {
        activeSession = undefined;
    }
}
