// @ts-nocheck
import fs from "node:fs";
import { chromium, firefox } from "playwright";

const visibleBrowsers = new Set();

export async function openInBrowser(url, { engine = "chromium" } = {}) {
  const browser = await launchBrowser(engine, false);
  const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30_000 });
  visibleBrowsers.add(browser);
  return { browser, page };
}

export async function searchInBrowser({ url, engine = "chromium", headless = true, waitAfterLoadMs = 3000 }) {
  const browser = await launchBrowser(engine, headless);
  const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });

  try {
    const response = await page.goto(url, {
      waitUntil: "domcontentloaded",
      timeout: 30_000,
    });
    await page.waitForTimeout(Math.max(250, Number(waitAfterLoadMs) || 3000));

    const [currentUrl, title, pageSource] = await Promise.all([
      page.url(),
      page.title(),
      page.content(),
    ]);
    const cleanText = await page.locator("body").innerText().catch(() => "");
    const failed = /something has gone wrong|reference id|access denied/i.test(cleanText);

    return {
      ok: Boolean(response?.ok()) && !failed,
      status: response?.status() || 0,
      url: currentUrl,
      title,
      text: cleanText.slice(0, 1200),
      pageSource,
    };
  } finally {
    await browser.close();
  }
}

export async function scrapePage(url, options = {}) {
  return searchInBrowser({ url, engine: "chromium", headless: true, waitAfterLoadMs: 750, ...options });
}

function launchBrowser(engine, headless) {
  const normalizedEngine = String(engine).toLowerCase() === "firefox" ? "firefox" : "chromium";
  const browserType = normalizedEngine === "firefox" ? firefox : chromium;
  const executablePath = resolveSystemBrowser(normalizedEngine);
  const options = {
    headless,
    timeout: 10_000,
    ...(executablePath ? { executablePath } : {}),
  };

  return browserType.launch(options);
}

function resolveSystemBrowser(engine) {
  if (process.platform !== "win32") return "";
  if (engine === "firefox") return "";

  const candidates = [
    "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
    "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
  ];

  return candidates.find((candidate) => fs.existsSync(candidate)) || "";
}

export async function closeVisibleBrowsers() {
  await Promise.all([...visibleBrowsers].map((browser) => browser.close().catch(() => {})));
  visibleBrowsers.clear();
}
