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

const RTF = String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`;

test("ANSI-font attachment extraction preserves Windows-1252 characters", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("RTF extraction", { "ansi-font.rtf": RTF });
    const thread = await t3.thread({ project, title: "ANSI font extraction", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
    await screen.getByRole("textbox").fill("Read the extracted text of the attached RTF and quote it exactly, character for character, inside a code block. Do not interpret or fix it.");
    await browser.evaluate((rtf) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"]');
      if (!input) throw new Error("Attachment input is missing");
      const files = new DataTransfer();
      files.items.add(new File([rtf], "ansi-font.rtf", { type: "application/rtf" }));
      input.files = files.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
      return null;
    }, RTF);
    await screen.getByRole("button", "Submit message", { exact: true }).tap();
    await screen.getByText("second fixture turn complete", { exact: false }).waitFor({ timeout: 120_000 });

    // Replay cannot read a newly uploaded file. Display the real server sidecar verbatim.
    const attachments = join(T3_HOME, "userdata", "attachments");
    const entries = await readdir(attachments, { recursive: true });
    const sidecar = entries.find((entry) => entry.endsWith(".rtf.txt"));
    if (!sidecar) throw new Error("The server did not publish an RTF text sidecar");
    await copyFile(join(attachments, sidecar), join(project, "extracted-text.txt"));
    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();
    const editorText = () => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const content = host.shadowRoot?.querySelector("[data-content]");
        if (content) return content.textContent ?? "";
      }
      return null;
    });
    try {
      await expect.poll(editorText).toContain("€5 café");
    } finally {
      await app.screenshot("extracted-attachment-text");
    }
  });
