import { readFile, readdir, writeFile, watch } 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 notice = "\n\n[Extracted text truncated at document extraction limits.]";
async function sidecar(prefix: string) {
  const dir = join(T3_HOME, "userdata", "attachments");
  const find = async () => {
    const names = await readdir(dir, { recursive: true }).catch(() => []);
    for (const name of names) {
      if ((prefix === "thread-" ? !name.split("/").at(-1)?.startsWith("pending-") : name.split("/").at(-1)?.startsWith(prefix)) && name.endsWith(".rtf.txt")) {
        const bytes = await readFile(join(dir, name));
        if (bytes.toString().endsWith(notice)) return bytes;
      }
    }
  };
  const existing = await find();
  if (existing) return existing;
  const events = watch(join(T3_HOME, "userdata"), { recursive: true, signal: AbortSignal.timeout(60000) });
  try {
    for await (const _event of events) {
      const bytes = await find();
      if (bytes) return bytes;
    }
  } finally { await events.return(); }
  throw new Error("Document sidecar was not written");
}

test("An uploaded and claimed RTF preserves Unicode at its text budget", WEB, async ({ t3, app, screen, browser }) => {
  const rtf = String.raw`{\rtf1 ` + "x".repeat(999999) + String.raw`\u-10179?\u-8576? After}`;
  const project = await t3.project("unicode-document", { "emoji-boundary.rtf": rtf });
  await t3.open();
  await screen.getByRole("textbox").fill("Summarize the attached document.");
  await browser.locator('input[type="file"]').setInputFiles(join(project, "emoji-boundary.rtf"));
  const pending = await sidecar("pending-");
  await screen.getByText("emoji-boundary.rtf", { exact: true }).first().waitFor();
  await screen.getByRole("textbox").press("Enter");
  const claimed = await sidecar("thread-");
  await screen.getByText("This turn is a replay.", { exact: false }).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await app.screenshot("attachment-sent");
  const report = ["REAL SERVER DOCUMENT OUTPUT — emoji-boundary.rtf", "Input: 999,999 x + rocket (RTF surrogate pair) + After", "Budget: 1,000,000 UTF-16 units; rocket crosses boundary", ""];
  for (const [label, bytes] of [["Uploaded sidecar", pending], ["Claimed sidecar supplied to agent", claimed]] as const) {
    const text = bytes.toString("utf8");
    report.push(label, `  Leading x: ${text.match(/^x*/)?.[0].length}`, `  Bytes: ${bytes.length}; replacement characters: ${text.split("\uFFFD").length - 1}`, `  Boundary UTF-8: ${bytes.subarray(999999, 1000006).toString("hex").match(/../g)?.join(" ")}`, `  Tail: ${JSON.stringify(text.slice(999975))}`, "");
  }
  report.push("Inspection complete (both real sidecars read from disk).");
  await writeFile(join(project, "unicode-evidence.txt"), report.join("\n"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await terminal.waitFor();
  await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
  const handle = await browser.evaluate(() => {
    const box = document.querySelector('[data-thread-terminal-drawer] .cursor-row-resize')?.getBoundingClientRect();
    return box ? { x: box.x + box.width / 2, y: box.y + 3 } : null;
  });
  if (handle) {
    await browser.mouse.move(handle.x, handle.y);
    await browser.mouse.down();
    await browser.mouse.move(handle.x, 290);
    await browser.mouse.up();
  }
  await terminal.focus();
  await browser.keyboard.type(" PS1='' ; clear ; cat unicode-evidence.txt\n");
  // The terminal canvas is synchronized through its own clipboard selection.
  const copied = async () => {
    await browser.evaluate(() => {
      document.body.dataset.terminalCopy = "";
      document.addEventListener("copy", (event) => {
        document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? "";
      }, { once: true });
    });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
  };
  // Wait for the terminal render, without an assertion that could count as the defect.
  const deadline = Date.now() + 15000;
  while (!(await copied()).includes("Inspection complete")) {
    if (Date.now() > deadline) throw new Error("Terminal did not render document inspection");
  }
  await browser.mouse.move(900, 650);
  await browser.mouse.down();
  await browser.mouse.up();
  await app.screenshot("unicode-boundary");
  for (const bytes of [pending, claimed]) {
    expect(bytes.toString("utf8").includes("\uFFFD")).toBe(false);
    expect(bytes.toString("utf8") === "x".repeat(999999) + notice).toBe(true);
  }
});
