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

test("ODT attachment extraction excludes unused automatic currency styles", WEB, async ({t3, app, browser, screen}) => {
  const bytes = await 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:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" office:version="1.3"><office:automatic-styles><number:currency-style style:name="UnusedCurrency"><number:currency-symbol>USD</number:currency-symbol></number:currency-style></office:automatic-styles><office:body><office:text><text:p>Invoice was paid in euros.</text:p></office:text></office:body></office:document-content>')
    .generateAsync({type:"base64"});
  const project = await t3.project("invoice-demo");
  const thread = await t3.thread({project, title:"Invoice attachment extraction", messages:["Start"]});
  await t3.open(thread);
  await expect(screen.getByRole("button", "Attach files")).toBeVisible();
  await browser.evaluate((base64) => {
    const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
    if (!input) throw new Error("Attachment file input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "invoice.odt", {type:"application/vnd.oasis.opendocument.text"}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
  }, bytes);
  await screen.getByRole("textbox").fill("Read the extracted-text file for the attached document with cat and quote its first line exactly, in a code block.");
  await browser.keyboard.press("Enter");
  await expect(screen.getByText("second fixture turn complete")).toBeVisible();
  const dir = `${T3_HOME}/userdata/attachments`;
  const files = await readdir(dir, {recursive:true});
  const sidecar = files.find(f => f.endsWith(".odt.txt"));
  if (!sidecar) throw new Error(`No ODT extraction sidecar: ${files.join(",")}`);
  const extracted = await readFile(`${dir}/${sidecar}`, "utf8");
  await copyFile(`${dir}/${sidecar}`, `${project}/invoice.odt.txt`);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await input.focus();
  await browser.keyboard.type("PS1='$ '; clear; echo Server-written invoice.odt.txt; cat invoice.odt.txt; echo\n");
  const terminalText = async () => {
    await browser.evaluate(() => {
      delete document.body.dataset.terminalCopy;
      window.addEventListener("copy", event => { document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? ""; }, {once:true});
    });
    await input.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
  };
  await expect.poll(terminalText).toContain("Invoice was paid in euros.");
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("extracted-invoice");
  expect(extracted.trim()).toBe("Invoice was paid in euros.");
});
