import { chromium } from "playwright";
import { ensureBrowser, getCdpEndpoint } from "../../agent/browser-launcher.js";
import { getRelayCdpEndpoint } from "../../utils/playwriter-relay.js";
import { buildSuiteResult, ok, runTest, skipped } from "../suite-utils.js";
async function navigateOrSkip(page, url, label) {
    try {
        await page.goto(url, { timeout: 30_000, waitUntil: "load" });
        return null;
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        if (/timeout/i.test(msg)) {
            return skipped(`${label} unreachable (timeout — external site, not a code issue)`);
        }
        throw err;
    }
}
function getCdpUrl(config) {
    if (config.browserBackend === "playwriter") {
        const host = config.playwriterRelayHost ?? "127.0.0.1";
        const port = config.playwriterRelayPort ?? 19988;
        return { url: `${getRelayCdpEndpoint(host, port)}/e2e`, mode: "playwriter" };
    }
    return { url: getCdpEndpoint(), mode: "playwright" };
}
export const browserDetectionSuite = {
    id: "browser-detection",
    name: "Browser Detection",
    run: async (context) => {
        const started = Date.now();
        const tests = [];
        const { url: cdpUrl, mode } = getCdpUrl(context.config);
        let browser;
        try {
            await ensureBrowser();
            browser = await chromium.connectOverCDP(cdpUrl);
        }
        catch (err) {
            tests.push({
                id: "browser-detection.connect",
                name: "Connect to browser",
                suite: "browser-detection",
                status: "skipped",
                durationMs: Date.now() - started,
                message: `Cannot connect to browser (${mode}): ${err instanceof Error ? err.message : String(err)}`,
            });
            return buildSuiteResult("browser-detection", "Browser Detection", started, tests);
        }
        const isRelay = mode === "playwriter";
        const ctx = isRelay ? browser.contexts()[0] : await browser.newContext();
        try {
            tests.push(await runTest("browser-detection", "browser-detection.sannysoft", "bot.sannysoft.com", async () => {
                const page = await ctx.newPage();
                try {
                    const skip = await navigateOrSkip(page, "https://bot.sannysoft.com", "bot.sannysoft.com");
                    if (skip)
                        return skip;
                    const results = await page.evaluate(`(() => {
            const rows = document.querySelectorAll("table tr");
            const findings = {};
            for (const row of rows) {
              const cells = row.querySelectorAll("td");
              if (cells.length >= 2) {
                const key = (cells[0]?.textContent ?? "").trim();
                const value = (cells[1]?.textContent ?? "").trim();
                if (key) findings[key] = value;
              }
            }
            return findings;
          })()`);
                    const failedKeys = Object.entries(results).filter(([, v]) => v.toLowerCase() === "failed");
                    if (failedKeys.length > 0) {
                        throw new Error(`Failed checks: ${failedKeys.map(([k]) => k).join(", ")}`);
                    }
                    return ok("All sannysoft checks passed", {
                        mode,
                        totalChecks: Object.keys(results).length,
                        webdriver: results.Webdriver || "not found in results",
                    });
                }
                finally {
                    await page.close();
                }
            }));
        }
        finally {
            if (!isRelay)
                await ctx.close();
            await browser.close();
        }
        return buildSuiteResult("browser-detection", "Browser Detection", started, tests);
    },
};
//# sourceMappingURL=browser-detection.js.map