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

// Synthetic ODT packages reproduce the reporter's LibreOffice XML structure.
const packageOdt = async (body: string) => new JSZip()
  .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
  .file("content.xml", `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" office:version="1.3"><office:body><office:text>${body}</office:text></office:body></office:document-content>`)
  .generateAsync({ type: "uint8array" });
const filesBelow = async (root: string): Promise<string[]> => {
  const entries = await readdir(root, { withFileTypes: true });
  return (await Promise.all(entries.map(entry => entry.isDirectory() ? filesBelow(join(root, entry.name)) : [join(root, entry.name)]))).flat();
};
const escape = (text: string) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");

test("Floating ODT shapes and frames keep their lines while as-char stays inline", WEB, async ({ t3, app, browser, screen }) => {
  const floatingText = "<text:p>Call the dock manager</text:p><text:p>before noon</text:p>";
  const documents = [
    { name: "floating-shape.odt", label: "Floating custom shape · paragraph anchor", bytes: await packageOdt(`<text:p>Shipping update.</text:p><text:p><draw:custom-shape text:anchor-type="paragraph">${floatingText}</draw:custom-shape>Trucks leave at six.</text:p>`) },
    { name: "floating-frame.odt", label: "Floating frame · paragraph anchor", bytes: await packageOdt(`<text:p>Shipping update.</text:p><text:p><draw:frame text:anchor-type="paragraph"><draw:text-box>${floatingText}</draw:text-box></draw:frame>Trucks leave at six.</text:p>`) },
    { name: "inline-control.odt", label: "Inline control · as-char anchor", bytes: await packageOdt(`<text:p>Badge <draw:frame text:anchor-type="as-char"><draw:text-box><text:p>A</text:p><text:p>B</text:p></draw:text-box></draw:frame> required.</text:p>`) },
  ];
  const project = await t3.project("shipping-documents", { "extraction-report.html": "<p>Awaiting upload</p>" });
  const thread = await t3.thread({ project, title: "ODT extracted text", messages: ["Start"] });
  await browser.setViewport({ width: 1600, height: 1000 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("For each attached document, read its extracted text file and quote it exactly inside a code block, preserving line breaks.");
  await browser.evaluate((documents) => {
    const clipboardData = new DataTransfer();
    for (const doc of documents) clipboardData.items.add(new File([new Uint8Array(doc.bytes)], doc.name, { type: "application/vnd.oasis.opendocument.text" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  }, documents.map(doc => ({ name: doc.name, bytes: Array.from(doc.bytes) })));
  for (const doc of documents) await browser.locator('[contenteditable="true"]').getByText(doc.name, { exact: true }).waitFor({ timeout: 15_000 });
  await browser.locator('button[aria-label="Submit message"]:enabled').waitFor();
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();

  // Read real upload sidecars, not replay output or the extraction worker imported into this test.
  const uploaded = (await filesBelow(join(T3_HOME, "userdata"))).filter(file => file.endsWith(".odt"));
  const extracted: string[] = [];
  for (const doc of documents) {
    const matches = await Promise.all(uploaded.map(async path => ({ path, bytes: await readFile(path) })));
    const match = matches.find(item => item.bytes.equals(Buffer.from(doc.bytes)));
    if (!match) throw new Error(`Upload missing: ${doc.name}`);
    extracted.push(await readFile(`${match.path}.txt`, "utf8"));
  }
  // A report only wraps the sidecars in escaped <pre> blocks; it never alters their whitespace.
  await writeFile(join(project, "extraction-report.html"), `<!doctype html><html><meta charset="utf-8"><style>body{font:16px system-ui;margin:24px;color:#e5e7eb;background:#16181d}h1{font-size:23px;margin:0 0 10px}p{color:#a9b0bd;line-height:1.5}h2{font-size:16px;margin:22px 0 8px}pre{font:17px/1.5 monospace;white-space:pre;background:#232731;padding:16px;border-radius:8px;margin:0}</style><h1>ODT upload — server-extracted text</h1><p>Verbatim .odt.txt sidecars from these three composer attachments.<br>Replay supplies the turn only; the text below comes from the real server.</p>${documents.map((doc, i) => `<h2>${escape(doc.label)}</h2><pre>${escape(extracted[i]!)}</pre>`).join("")}</html>`);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extraction-report.html");
  await screen.getByRole("option", "extraction-report.html", { exact: false }).tap();
  const report = browser.frameLocator('iframe[title="extraction-report.html"]');
  await report.getByText("Inline control · as-char anchor").waitFor({ timeout: 120_000 });
  await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await report.locator("pre").nth(2).waitFor();
  await app.screenshot("server-extracted-odt-lines");
  expect(extracted).toEqual([
    "Shipping update.\nCall the dock manager\nbefore noon\nTrucks leave at six.",
    "Shipping update.\nCall the dock manager\nbefore noon\nTrucks leave at six.",
    "Badge A\nB required.",
  ]);
});
