/// <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";

test("ODT attachment extraction separates ruby readings and omits empty readings", 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: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" office:version="1.3"><office:body><office:text><text:p><text:ruby><text:ruby-base>東京</text:ruby-base><text:ruby-text>とうきょう</text:ruby-text></text:ruby></text:p><text:p>次は<text:ruby><text:ruby-base>京都</text:ruby-base><text:ruby-text></text:ruby-text></text:ruby>まで。</text:p></office:text></office:body></office:document-content>')
    .generateAsync({type:"base64"});
  const project = await t3.project("ODT ruby proof");
  const thread = await t3.thread({project,title:"ODT attachment reading",messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Quote the first line of the attached document exactly, inside backticks, and nothing else.");
  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 dt = new DataTransfer();
    dt.items.add(new File([Uint8Array.from(atob(base64),c=>c.charCodeAt(0))],"tokyo.odt",{type:"application/vnd.oasis.opendocument.text"}));
    input.files = dt.files;
    input.dispatchEvent(new Event("change",{bubbles:true}));
  },bytes);
  await screen.getByRole("textbox").press("Enter");
  const attachmentDir = join(T3_HOME,"userdata","attachments");
  let extracted = "";
  await expect.poll(async () => {
    const files = await readdir(attachmentDir).catch(()=>[]);
    const sidecar = files.find(name=>name.endsWith(".odt.txt"));
    if (!sidecar) return false;
    extracted = await readFile(join(attachmentDir,sidecar),"utf8");
    return true;
  },{timeout:60000}).toBe(true);
  // This is a verbatim copy of the server's actual attachment sidecar, never expected text.
  await writeFile(join(project,"tokyo.odt.txt"),extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("tokyo.odt.txt");
  await screen.getByRole("option","tokyo.odt.txt",{exact:false}).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if(content) return content.textContent ?? "";
    }
    return "";
  });
  await expect.poll(editorText).toContain("次は京都まで。");
  await app.screenshot("server-extracted-odt-text");
  expect(extracted.trim()).toBe("東京(とうきょう)\n次は京都まで。");
});
