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

const cases = [
  { name: "utf8.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg65001 \'e4\'bd\'a0\'e5\'a5\'bd}`, text: "你好" },
  { name: "sjis-doc.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`, text: "あ" },
  { name: "sjis-font.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0\fswiss Arial;}{\f1\fcharset128 MS Gothic;}}\f0 Latin \f1\'82\'a0\f0  end}`, text: "Latin あ end" },
  { name: "gbk-doc.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg936 \'c4\'e3\'ba\'c3}`, text: "你好" },
  { name: "euckr-doc.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg949 \'be\'c8}`, text: "안" },
  { name: "big5-doc.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg950 \'a7\'41\'a6\'6e}`, text: "你好" },
  { name: "mixed-fonts.rtf", rtf: String.raw`{\rtf1\ansi\ansicpg1252{\fonttbl{\f0\fcharset128 Mincho;}{\f1\fcharset134 SimSun;}{\f2\fcharset129 Gulim;}{\f3\fcharset136 MingLiU;}{\f4\cpg65001 Noto;}}\f0\'82\'a0\f1\'c4\'e3\f2\'be\'c8\f3\'a7\'41\f4\'e2\'9c\'93}`, text: "あ你안你✓" },
];

test("Uploaded RTF attachments provide readable UTF-8 and CJK text to agents", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("RTF attachments");
  const thread = await t3.thread({ project, title: "RTF extraction", messages: ["Start"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Review these RTF attachments.");
  await browser.evaluate((files) => {
    const clipboardData = new DataTransfer();
    for (const file of files) clipboardData.items.add(new File([file.rtf], file.name, { type: "application/rtf" }));
    const editor = document.querySelector('[contenteditable="true"]');
    if (!editor) throw new Error("No composer editor");
    editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  }, cases);
  await screen.getByRole("button", "File attachment, mixed-fonts.rtf", { exact: false }).waitFor();
  await composer.focus();
  await browser.keyboard.press("Enter");
  await browser.locator('[data-message-role="user"]').filter({ hasText: "Review these RTF attachments." }).waitFor();
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await app.screenshot("attachments-sent");
  // The completed agent turn has claimed every upload; read the published sidecars.
  const dir = `${T3_HOME}/userdata/attachments`;
  const files = (await readdir(dir)).filter((name) => name.endsWith(".rtf"));
  const rows = [];
  for (const item of cases) {
    let actual = "[NO EXTRACTED TEXT SIDECAR]";
    for (const name of files) {
      if (await readFile(`${dir}/${name}`, "utf8") !== item.rtf) continue;
      actual = await readFile(`${dir}/${name}.txt`, "utf8").catch(() => "[NO EXTRACTED TEXT SIDECAR]");
      break;
    }
    rows.push({ name: item.name, expected: item.text, actual });
  }
  // Display the server artifacts in the app's file viewer, not the RTF preview (which already works on base).
  const report = ["RTF ATTACHMENT EXTRACTION — REAL SERVER SIDECARS", "", "Uploaded through chat; read .rtf.txt after upload completed.", "These are the text files supplied to agents, not the RTF web preview.", "", ...rows.flatMap((row) => [row.name, `  Expected: ${row.expected}    |    Actual: ${row.actual}`, ""])].join("\n");
  await writeFile(`${project}/extraction-results.txt`, report);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extraction-results.txt");
  await screen.getByRole("option", "extraction-results.txt", { exact: false }).tap();
  // Wait for the viewer without asserting a setup step as the bug verdict.
  await browser.locator("diffs-container").waitFor();
  await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("agent-text-sidecars");
  expect(rows.map((row) => row.actual)).toEqual(cases.map((item) => item.text));
});
