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

const expected = "The shipment left.[1: Inspect the seals before departure.] Finance booked revenue.\nThe ledger lists Tokyo[2: Includes freight.\nDuties excluded.] and Osaka.";

test("ODT attachment footnotes remain distinct from prose", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("META-INF/manifest.xml", '<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.text"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>')
    .file("content.xml", '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:t="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:text><t:p>The shipment left.<t:note t:id="ftn0" t:note-class="footnote"><t:note-citation>1</t:note-citation><t:note-body><t:p>Inspect the seals before departure.</t:p></t:note-body></t:note> Finance booked revenue.</t:p><t:p>The ledger lists Tokyo<t:note t:id="ftn1" t:note-class="footnote"><t:note-citation>2</t:note-citation><t:note-body><t:p>Includes freight.</t:p><t:p>Duties excluded.</t:p></t:note-body></t:note> and Osaka.</t:p></office:text></office:body></office:document-content>');
  const bytes = await zip.generateAsync({ type: "uint8array" });
  const project = await t3.project("footnote-proof", { "footnotes.odt": bytes });
  const thread = await t3.thread({ project, title: "ODT footnote extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.evaluate((data: number[]) => {
    const input = document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    const transfer = new DataTransfer();
    transfer.items.add(new File([new Uint8Array(data)], "footnotes.odt", { type: "application/vnd.oasis.opendocument.text" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, Array.from(bytes));
  await screen.getByRole("textbox").fill("Print the extracted text file for this attachment verbatim (use cat).");
  await browser.keyboard.press("Enter");
  const sidecar = async () => {
    const root = join(T3_HOME, "userdata");
    const files = await readdir(root, { recursive: true });
    return files.find((file) => file.endsWith(".odt.txt"));
  };
  // Wait for the real upload/extraction, without asserting unrelated UI behavior.
  await expect.poll(sidecar, { timeout: 60_000 }).toBeTruthy();
  const source = join(T3_HOME, "userdata", (await sidecar())!);
  const extracted = await readFile(source, "utf8");
  await copyFile(source, join(project, "footnotes.odt.txt"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await terminal.waitFor();
  await expect(terminal).toHaveAttribute("data-workspace-focus-default", "");
  await terminal.focus();
  await browser.keyboard.type("export PS1='$ '; clear; cat footnotes.odt.txt; printf '\\n'; touch capture.done\n");
  await expect.poll(async () => (await readdir(project)).includes("capture.done")).toBe(true);
  await app.screenshot("extracted-footnotes");
  expect(extracted.trim()).toBe(expected);
});
