import * as fs from "node:fs/promises";
import * as path from "node:path";
import { setTimeout } from "node:timers/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("RTF footnotes and text boxes survive blank source lines", WEB, async ({t3, app, screen, browser}) => {
  const footnote = (n: number) => String.raw`{\rtf1 A{\super\chftn}{\*` + "\r\n".repeat(n) + String.raw`\footnote\pard{\super\chftn} Comment.}B}`;
  const textbox = (n: number) => String.raw`{\rtf1 A{\shp{\*` + "\r\n".repeat(n) + String.raw`\shpinst{\shptxt Visible}}}B}`;
  const project = await t3.project("RTF documents", {"footnote.rtf":footnote(4),"footnote0.rtf":footnote(0),"textbox.rtf":textbox(40),"textbox0.rtf":textbox(0)});
  const thread = await t3.thread({project,title:"Review RTF documents",messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor({state:"visible"});
  const stableCapture = async (label: string) => {
    let previous = await fs.readFile(await app.screenshot(label + "-settling"));
    for (let attempt = 0; attempt < 10; attempt++) {
      await setTimeout(500);
      const current = await fs.readFile(await app.screenshot(label));
      if (previous.equals(current)) return;
      previous = current;
    }
    throw new Error("Preview did not become visually stable");
  };
  const rendered: Record<string,string> = {};
  for (const file of ["footnote0.rtf","footnote.rtf","textbox0.rtf","textbox.rtf"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option",file,{exact:false}).tap();
    const body = browser.frameLocator(`iframe[title^="${file}"]`).locator("body");
    await body.waitFor({state:"visible",timeout:120000});
    await screen.getByText("1 page",{exact:false}).waitFor({state:"visible",timeout:120000});
    rendered[file] = await body.textContent() ?? "";
    await stableCapture(file.replace(".rtf",""));
  }
  const composer = screen.getByRole("textbox");
  await composer.fill("Read both RTF attachments.");
  await browser.locator('input[type="file"]').setInputFiles([path.join(project,"textbox.rtf"),path.join(project,"textbox0.rtf")]);
  await composer.getByRole("button", "File attachment, textbox.rtf,", {exact:false}).waitFor({state:"visible"});
  await composer.press("Enter");
  await screen.getByText("second fixture turn complete",{exact:false}).waitFor({state:"visible",timeout:120000});
  const results: Record<string,string> = {};
  for (const entry of await fs.readdir(T3_HOME,{recursive:true})) {
    if (!entry.endsWith(".rtf.txt")) continue;
    const original = await fs.readFile(path.join(T3_HOME,entry.slice(0,-4)),"utf8");
    results[original.includes("\r\n") ? "textbox.rtf" : "textbox0.rtf"] = await fs.readFile(path.join(T3_HOME,entry),"utf8");
  }
  const report = "Actual server attachment text sidecars after sending both RTF files:\n\n" + Object.entries(results).map(([name,text]) => `${name}: ${text}`).join("\n");
  await fs.writeFile(path.join(project,"extracted-text.txt"),report);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-text.txt");
  await screen.getByRole("option","extracted-text.txt",{exact:false}).tap();
  await screen.getByText("Actual server attachment text sidecars after sending both RTF files:",{exact:false}).first().waitFor({state:"visible"});
  await screen.getByText("second fixture turn complete",{exact:false}).tap();
  await stableCapture("attachment-extracted-text");
  expect(results["textbox.rtf"]).toBe("AVisibleB");
  expect(rendered["footnote.rtf"]).toContain("Comment.");
  expect(rendered["textbox.rtf"]).toContain("Visible");
});
