import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { chromium } from "playwright";
import { ensureBrowser, getCdpEndpoint } from "../../agent/browser-launcher.js";
import { captureScreen, click, initDisplaySize, isDisplaySizeInitialized, typeText, } from "../../tools/desktop-executor-factory.js";
import { startLocalTestServer } from "../local-test-server.js";
import { buildSuiteResult, ok, runTest, skipped, warning } from "../suite-utils.js";
const execFileAsync = promisify(execFile);
export const cuaSuite = {
    id: "cua",
    name: "CUA",
    run: async (context) => {
        const started = Date.now();
        const localServer = await startLocalTestServer();
        const tests = [];
        try {
            tests.push(await runTest("cua", "cua.display_size", "Display size", async () => {
                if (!isDisplaySizeInitialized()) {
                    try {
                        await initDisplaySize();
                    }
                    catch (err) {
                        return skipped(`Display size unavailable: ${err instanceof Error ? err.message : String(err)}`);
                    }
                }
                return ok("Display size ready");
            }));
            tests.push(await runTest("cua", "cua.screenshot", "Screenshot", async () => {
                const shot = await captureScreen();
                if (!shot.base64)
                    throw new Error("Screenshot empty");
                const screenshotPath = path.join(context.artifactsDir, "cua-screenshot.png");
                fs.writeFileSync(screenshotPath, Buffer.from(shot.base64, "base64"));
                return ok("Screenshot captured", { screenshotPath });
            }));
            await ensureBrowser();
            const browser = await chromium.connectOverCDP(getCdpEndpoint());
            const ctx = browser.contexts()[0] ?? await browser.newContext();
            let cuaPage;
            try {
                tests.push(await runTest("cua", "cua.open_local_page", "Open local page", async () => {
                    cuaPage = await ctx.newPage();
                    await cuaPage.goto(`${localServer.baseUrl}/e2e/cua?runId=${context.runId}`);
                    return ok("Local CUA page opened");
                }));
                tests.push(await runTest("cua", "cua.click_and_type", "Click and type", async () => {
                    if (!isDisplaySizeInitialized()) {
                        return skipped("Display size not initialized; grant Accessibility and Screen Recording permissions");
                    }
                    const page = cuaPage ?? ctx.pages().find((p) => p.url().includes("/e2e/cua"));
                    if (!page)
                        return skipped("CUA test page not open");
                    await execFileAsync("osascript", ["-e", 'tell application "Google Chrome" to activate']);
                    await page.bringToFront();
                    await new Promise((r) => setTimeout(r, 500));
                    const box = await page.locator("#text-input").boundingBox();
                    if (!box)
                        return warning("Could not resolve input bounding box");
                    const winBounds = await page.evaluate("({ screenX: window.screenX, screenY: window.screenY, chromeHeight: window.outerHeight - window.innerHeight })");
                    const screenX = Math.round(box.x + box.width / 2 + winBounds.screenX);
                    const screenY = Math.round(box.y + box.height / 2 + winBounds.screenY + winBounds.chromeHeight);
                    await click(screenX, screenY);
                    await new Promise((r) => setTimeout(r, 200));
                    await typeText(`VisionClaw E2E ${context.runId}`);
                    await new Promise((r) => setTimeout(r, 150));
                    const value = await page.inputValue("#text-input");
                    if (!value.includes(context.runId)) {
                        throw new Error(`Typed value not reflected in page (got "${value}", coords=${screenX},${screenY}, win=${JSON.stringify(winBounds)}, box=${JSON.stringify(box)})`);
                    }
                    return ok("CUA click/type verified via Playwright");
                }));
            }
            finally {
                if (cuaPage)
                    await cuaPage.close();
                await browser.close();
            }
        }
        finally {
            await localServer.close();
        }
        return buildSuiteResult("cua", "CUA", started, tests);
    },
};
//# sourceMappingURL=cua.js.map