/// <reference types="node" />

import { expect, test, type Page } from "@playwright/test";
import { readFile } from "node:fs/promises";

async function setEditor(page: Page, testId: string, value: string) {
  await page.getByTestId(testId).locator(".cm-content").fill(value);
}

test("real ECMAScript and PCRE2 workers compare exact snapshots and generate reviewed C", async ({
  page,
}) => {
  const pageErrors: string[] = [];
  page.on("pageerror", (error) => pageErrors.push(error.message));
  await page.goto("./");
  await page.getByLabel("Live").uncheck();
  await setEditor(
    page,
    "editor-regular-expression-pattern",
    "(?<word>[A-Za-z]+)",
  );
  await setEditor(page, "editor-test-text", "alpha beta");
  await expect(
    page.getByRole("button", { name: "Run", exact: true }),
  ).toBeEnabled({ timeout: 15_000 });

  await page
    .getByRole("button", { name: "Compare & code", exact: true })
    .click();
  const dialog = page.getByRole("dialog", { name: "Compare & generate" });
  await expect(dialog).toBeVisible();
  await expect(dialog).toBeInViewport();
  await dialog.getByRole("button", { name: "Run comparison" }).click();

  const verdict = dialog.locator(".comparison-verdict");
  await expect(
    verdict.getByRole("heading", { name: "same for current input" }),
  ).toBeVisible({ timeout: 20_000 });
  await expect(verdict).toContainText("not a proof");
  const sideCards = dialog.locator(".comparison-side-card");
  await expect(sideCards).toHaveCount(2);
  await expect(sideCards.nth(0)).toContainText("Native ECMAScript RegExp");
  await expect(sideCards.nth(0)).toContainText("native utf16");
  await expect(sideCards.nth(1)).toContainText("PCRE2 WebAssembly");
  await expect(sideCards.nth(1)).toContainText("10.47 2025-10-21");
  await expect(sideCards.nth(1)).toContainText("native utf8-byte");
  await expect(
    dialog.locator(".comparison-alignments table tbody tr"),
  ).toHaveCount(2);

  await dialog.getByLabel("Shared comparison pattern").fill("(?>a+)");
  await dialog.getByLabel("Comparison subject").fill("aaa");
  await dialog.getByRole("button", { name: "Run comparison" }).click();
  await expect(
    verdict.getByRole("heading", { name: "not comparable" }),
  ).toBeVisible({ timeout: 20_000 });
  await expect(dialog).toContainText("flavour specific syntax");
  await expect(dialog).toContainText(
    "no runtime equivalence claim is possible",
  );

  await dialog.getByLabel("Pattern model").selectOption("variants");
  await dialog.getByLabel("PCRE2 pattern variant").fill("(?<word>[a-z]++)");
  await dialog.getByLabel("Comparison subject").fill("alpha beta");
  await dialog.getByRole("tab", { name: "PCRE2 C code" }).click();
  await dialog.getByRole("button", { name: "Generate reviewed C17" }).click();
  await expect(dialog).toContainText("PCRE2 10.47 8-bit · all-matches");
  await expect(dialog).toContainText("Exact UTF-8 byte arrays");
  const source = dialog.locator(".generated-code-result pre");
  await expect(source).toContainText(
    "This generated program requires PCRE2 10.47 exactly.",
  );
  await expect(source).toContainText("0x2b, 0x2b");
  await expect(source).not.toContainText("(?<word>[a-z]++)");

  const downloadPromise = page.waitForEvent("download");
  await dialog.getByRole("button", { name: "Download .c" }).click();
  const download = await downloadPromise;
  expect(download.suggestedFilename()).toBe("regex-tools-pcre2-match.c");
  const downloadPath = await download.path();
  if (!downloadPath) throw new Error("Generated C download is unavailable.");
  const downloadedSource = await readFile(downloadPath, "utf8");
  expect(downloadedSource).toContain(
    '#error "This generated program requires PCRE2 10.47 exactly."',
  );
  expect(downloadedSource).toContain("pcre2_set_match_limit");
  expect(downloadedSource).not.toContain("(?<word>[a-z]++)");
  expect(pageErrors).toEqual([]);
});
