import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Expanded pending questions preserve single newlines and Markdown", WEB, async ({ t3, app, screen, browser }) => {
    const project = await t3.project("question-preview");
    await t3.thread({ project, title: "Review multiline question", messages: ["Show the multiline Markdown question preview."], model: "question" });
    await t3.open();
    await screen.getByRole("button", "Review multiline question, Input, question-preview", { exact: true }).tap();
    await screen.getByRole("heading", "Markdown preview").waitFor();
    const firstCapture = await app.screenshot("stability-check");
    execFileSync("convert", [firstCapture, "-crop", "700x440+280+340", "+repage", firstCapture]);
    await new Promise((resolve) => setTimeout(resolve, 500));
    const capture = await app.screenshot("expanded-question");
    execFileSync("convert", [capture, "-crop", "700x440+280+340", "+repage", capture]);
    const hash = async (path: string) => createHash("sha256").update(execFileSync("convert", [path, "rgba:-"], { maxBuffer: 10_000_000 })).digest("hex");
    if (await hash(firstCapture) !== await hash(capture)) throw new Error("Capture is not stable");
    const lines = await browser.evaluate(() => {
      const p = [...document.querySelectorAll("p")].find((node) => node.textContent?.includes("First line"));
      if (!p) throw new Error("Question paragraph missing");
      const rects = (text: string) => {
        const walker = document.createTreeWalker(p, NodeFilter.SHOW_TEXT);
        let node;
        while ((node = walker.nextNode())) {
          const index = node.textContent?.indexOf(text) ?? -1;
          if (index >= 0) {
            const range = document.createRange();
            range.setStart(node, index);
            range.setEnd(node, index + text.length);
            return range.getBoundingClientRect().top;
          }
        }
        throw new Error(`Missing ${text}`);
      };
      return { first: rects("First line"), second: rects("Second line") };
    });
    expect(lines.second).toBeGreaterThan(lines.first);
    await expect(screen.getByRole("heading", "Markdown preview")).toBeVisible();
    await expect(screen.getByText("Keep Markdown lists", { exact: true })).toBeVisible();
});
