/**
 * ============================================================
 *  src/tools/browser.ts —— Playwright Browser 单例
 * ------------------------------------------------------------
 *  整个 session 复用同一个 headless Chromium page。
 *  动态 import playwright-core，按需加载，避免未安装时拖累主程序。
 * ============================================================
 */
import os from 'node:os';
import path from 'node:path';
let browserInstance = null;
let pageInstance = null;
/**
 * 获取或创建 browser page 单例。
 * 每次导航后手动更新 pageInstance.url()。
 */
export async function getBrowserPage() {
    if (!browserInstance) {
        // 动态 import，按需加载
        const { chromium } = await import('playwright-core');
        try {
            browserInstance = await chromium.launch({
                headless: true,
                args: ['--no-sandbox', '--disable-setuid-sandbox'],
            });
        }
        catch (e) {
            const message = e instanceof Error ? e.message : String(e);
            throw new Error(`Failed to launch browser: ${message}\n` +
                `请先安装 playwright 及浏览器：\n` +
                `  npm install playwright-core\n` +
                `  npx playwright install chromium`);
        }
    }
    if (!pageInstance) {
        pageInstance = await browserInstance.newPage();
        await pageInstance.setViewportSize({ width: 1280, height: 720 });
    }
    return pageInstance;
}
/** 关闭浏览器（session 结束时调用） */
export async function closeBrowser() {
    if (pageInstance) {
        await pageInstance.close();
        pageInstance = null;
    }
    if (browserInstance) {
        await browserInstance.close();
        browserInstance = null;
    }
}
/** 生成截图路径 */
export function screenshotPath(prefix = 'browser') {
    return path.join(os.tmpdir(), `${prefix}-${Date.now()}.png`);
}
