import { readFile, copyFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Question options show multiline drafts before selection", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Issue preview demo");
  await t3.thread({ project, title: "Approve issue draft", messages: ["Approve this issue title/body?"], model: "question" });
  await t3.open();
  await screen.getByRole("button", "Approve issue draft, Input, Issue preview demo", { exact: true }).tap();
  await screen.getByRole("button", /Shorter/).waitFor({ state: "visible" });
  await browser.evaluate(async () => { await document.fonts.ready; });
  const capture = async (label: string) => {
    const path = await app.screenshot(label);
    await copyFile(path, path.replace(".png", "-full.png"));
    // Keep the question and composer; exclude the unrelated elapsed-turn clock.
    execFileSync("convert", [path, "-crop", "680x500+290+280", "+repage", "-strip", path]);
    return path;
  };
  for (let attempt = 0; attempt < 8; attempt++) {
    const first = await capture(`stability-${attempt}-a`);
    await new Promise((resolve) => setTimeout(resolve, 500));
    const second = await capture(`stability-${attempt}-b`);
    if ((await readFile(first)).equals(await readFile(second))) break;
    if (attempt === 7) throw new Error("The capture did not settle");
  }
  await capture("option-previews");
  await expect(screen.getByText("Title: Fix login", { exact: false })).toBeVisible();
  await expect(screen.getByText("Quote in password breaks login.", { exact: false })).toBeVisible();
  expect(await browser.evaluate(() => [...document.querySelectorAll("p")]
    .filter((p) => p.textContent?.startsWith("Body:"))
    .map((p) => p.querySelectorAll("br").length))).toEqual([2, 1]);
});
