import { chromium } from "playwright";
import { existsSync } from "node:fs";
import { createLogger } from "../logger.js";
import { HYDRATION_PROBE_SOURCE } from "./hydration-probe.js";
const log = createLogger("playwright-tier");
async function detectPlaywrightInstall() {
  try {
    const exec = chromium.executablePath();
    if (exec && existsSync(exec)) return { installed: true };
    return { installed: false, hint: "npx playwright install chromium" };
  } catch {
    return { installed: false, hint: "npx playwright install chromium" };
  }
}
function shouldEscalate(body) {
  if (!body) return true;
  if (body.length < 500) return true;
  if (/enable javascript/i.test(body)) return true;
  return false;
}
let _browser = null;
let _ctx = null;
let _launching = null;
async function getDaemonBrowser() {
  if (_browser && _ctx) return { browser: _browser, context: _ctx };
  if (_launching) return _launching;
  _launching = (async () => {
    try {
      const status = await detectPlaywrightInstall();
      if (!status.installed) {
        const err = new Error("playwright_not_installed");
        err.hint = status.hint;
        throw err;
      }
      const browser = await chromium.launch({ headless: true });
      const context = await browser.newContext();
      _browser = browser;
      _ctx = context;
      log.info("Playwright daemon browser launched");
      return { browser, context };
    } finally {
      _launching = null;
    }
  })();
  return _launching;
}
async function closeDaemonBrowser() {
  _launching = null;
  if (_ctx) {
    await _ctx.close();
    _ctx = null;
  }
  if (_browser) {
    await _browser.close();
    _browser = null;
  }
}
async function fetchWithPlaywright(url, opts = {}) {
  const { context } = await getDaemonBrowser();
  const page = await context.newPage();
  try {
    const overall = opts.timeoutMs ?? 3e4;
    await page.goto(url, { waitUntil: "load", timeout: overall });
    const hydrationBudget = Math.min(5e3, Math.max(800, Math.floor(overall / 6)));
    await Promise.race([
      page.waitForFunction(HYDRATION_PROBE_SOURCE, void 0, { timeout: hydrationBudget }).catch(() => void 0),
      page.waitForLoadState("networkidle", { timeout: hydrationBudget }).catch(() => void 0)
    ]);
    const html = await page.content();
    const text = await page.evaluate(() => document.body?.innerText ?? "");
    return { html, text };
  } finally {
    await page.close();
  }
}
export {
  closeDaemonBrowser,
  detectPlaywrightInstall,
  fetchWithPlaywright,
  getDaemonBrowser,
  shouldEscalate
};
//# sourceMappingURL=playwright-tier.js.map