/// <reference lib="dom" />
import { expect } from "e2e";
import { readdir, readFile, copyFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const RTF = String.raw`{\rtf1\ansi\ansicpg1252\cocoartf2580
{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;}
\f0\fs24 \cf0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : \f0 \'c7\'e1\'e4\'d5\f1  (Synthetic fixture)\par
}`;

test("An attached RTF preserves the font's Arabic character set in the agent text sidecar", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("RTF-attachment-proof");
    const thread = await t3.thread({ project, title: "RTF font character set", messages: ["first"] });
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
    await screen.getByRole("textbox").fill("Read the extracted text file of the attached RTF (do not open the .rtf itself) and quote its first line exactly, verbatim.");
    await browser.evaluate((rtf: string) => {
      const data = new DataTransfer();
      data.items.add(new File([rtf], "LegalTextGeneric.rtf", { type: "application/rtf" }));
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    }, RTF);
    await screen.getByRole("button", "File attachment", { exact: false }).waitFor();
    await browser.keyboard.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
    const root = join(T3_HOME, "userdata", "attachments");
    const paths = await readdir(root, { recursive: true });
    const sidecar = paths.find((p) => p.endsWith(".rtf.txt"));
    if (!sidecar) throw new Error("The completed attachment turn did not create an RTF text sidecar: " + paths.join(", "));
    const source = join(root, sidecar);
    const extracted = await readFile(source, "utf8");
    // Show the server's exact sidecar bytes in the app's file viewer, without private server paths.
    await copyFile(source, join(project, "LegalTextGeneric.rtf.txt"));
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("LegalTextGeneric.rtf.txt");
    await screen.getByRole("option", "LegalTextGeneric.rtf.txt", { exact: false }).tap();
    await screen.getByText("Synthetic fixture", { exact: false }).waitFor();
    await app.screenshot("agent-extracted-text");
    expect(extracted.trim()).toBe("ملاحظة: النص (Synthetic fixture)");
  });
