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

test("Question options show multiline drafts before selection", { ...IOS, video: "off" }, async ({ t3, app, screen }) => {
  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.getByText("Approve issue draft", { exact: false }).first().waitFor({ state: "visible", timeout: 120_000 });
  await screen.getByText("Approve issue draft", { exact: false }).first().tap();
  await screen.getByRole("radio", "Shorter, Use the shorter draft", { exact: true }).waitFor({ state: "visible" });
  const capture = async (label: string) => {
    const path = await app.screenshot(label);
    await copyFile(path, path.replace(".png", "-full.png"));
    execFileSync("convert", [path, "-gravity", "South", "-crop", "100%x75%+0+0", "+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();
});
