/// <reference lib="dom" />
import { readFile, 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";

// Upload through the real composer, then inspect the server-produced sidecars.
// The composer diagnostic is explicitly a measured report, not an agent response.
test("GB18030 RTF uploads publish correctly decoded extracted text", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("rtf-notes");
  const thread = await t3.thread({ project, title: "RTF attachment extraction", messages: ["Check RTF attachment extraction"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Quarterly notes");
  await browser.evaluate(() => {
    (window as any).uploadStatuses = [];
    const send = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(...args) {
      this.addEventListener("loadend", () => { if (this.status === 204) (window as any).uploadStatuses.push(this.status); });
      return send.apply(this, args);
    };
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([String.raw`{\rtf1\ansi\ansicpg936 Quarterly notes: \'d6\'d0\'ce\'c4}`], "gbk-control.rtf", { type: "application/rtf" }));
    clipboardData.items.add(new File([String.raw`{\rtf1\ansi\ansicpg54936 Quarterly notes: \'d6\'d0\'ce\'c4 \'95\'32\'82\'36}`], "gb18030-notes.rtf", { type: "application/rtf" }));
    const bytes = new Uint8Array(1_050_000 * 4);
    for (let i = 0; i < bytes.length; i += 4) bytes.set([0x81, 0x39, 0xee, 0x39], i);
    clipboardData.items.add(new File([String.raw`{\rtf1\ansi\ansicpg54936 `, new Uint8Array([0xd6, 0xd0]), bytes, "}"], "gb18030-long.rtf", { type: "application/rtf" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
  });
  await expect.poll(() => browser.evaluate(() => (window as any).uploadStatuses.length), { timeout: 60_000 }).toBeGreaterThanOrEqual(3);
  const root = join(T3_HOME, "userdata", "attachments");
  const entries = await readdir(root, { recursive: true });
  const measured: Record<string, string | null> = {};
  for (const name of entries.filter(name => name.endsWith(".rtf"))) {
    const source = await readFile(join(root, name));
    const label = source.length > 1_000_000 ? "long" : source.includes(Buffer.from("54936")) ? "sample" : "control";
    measured[label] = await readFile(join(root, name + ".txt"), "utf8").catch(() => null);
  }
  const long = measured.long;
  const summary = [
    "MEASURED SERVER SIDECARS (diagnostic; not an agent reply)",
    "All three RTF uploads: HTTP 204",
    `cp936 control: ${measured.control ?? "NO SIDECAR"}`,
    `cp54936 sample: ${measured.sample ?? "NO SIDECAR"}`,
    long === null ? "cp54936 long: NO SIDECAR" : `cp54936 long: ${long?.slice(0, 5)}…; ${long?.search(/[^中㐀]/u)} intact characters`,
    long === null ? "" : `Long suffix: ${long?.slice(1_000_000).trim()}`,
  ].filter(Boolean).join("\n");
  await screen.getByRole("textbox").fill(summary);
  await app.screenshot("rtf-extraction-sidecars");
  expect({ control: measured.control, sample: measured.sample, longPrefix: long?.slice(0, 5), longBoundary: long?.search(/[^中㐀]/u), longSuffix: long?.slice(1_000_000) }).toEqual({ control: "Quarterly notes: 中文", sample: "Quarterly notes: 中文 𠀀", longPrefix: "中㐀㐀㐀㐀", longBoundary: 1_000_000, longSuffix: "\n\n[Extracted text truncated at document extraction limits.]" });
});
