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

test("Uploaded EPUB extracted text keeps its authored table caption before the rows", WEB, async ({t3, app, browser, screen}) => {
  const epub = await new JSZip()
    .file("mimetype", "application/epub+zip", {compression: "STORE"})
    .file("META-INF/container.xml", '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
    .file("OEBPS/content.opf", '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book">revenue</dc:identifier><dc:title>Revenue report</dc:title><dc:language>en</dc:language></metadata><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
    .file("OEBPS/chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><h1>Chapter 1</h1><p>This chapter summarises revenue for the first half of the year.</p><table><caption>Table 1: Quarterly revenue</caption><tr><th>Q1</th><th>Q2</th></tr><tr><td>100</td><td>200</td></tr></table></body></html>')
    .generateAsync({type: "base64"});
  const project = await t3.project("revenue-report");
  const thread = await t3.thread({project, title: "EPUB attachment extraction", messages: ["Review the revenue report"]});
  await t3.open(thread);
  await screen.getByRole("button", "Attach files").waitFor();
  await screen.getByRole("textbox").fill("Read the extracted-text file for the attached EPUB (not the .epub itself) and quote its full contents verbatim in a code block. Then say whether a table caption appears in it.");
  await browser.evaluate(async (base64) => {
    const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
    if (!input) throw new Error("Attachment input missing");
    const originalSend = XMLHttpRequest.prototype.send;
    let complete!: () => void;
    const uploaded = new Promise<void>(resolve => { complete = resolve; });
    XMLHttpRequest.prototype.send = function(body) {
      this.addEventListener("loadend", () => {
        if (this.responseURL.includes("/api/attachments/upload/")) {
          XMLHttpRequest.prototype.send = originalSend;
          complete();
        }
      });
      originalSend.call(this, body);
    };
    const files = new DataTransfer();
    files.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "revenue-report.epub", {type: "application/epub+zip"}));
    input.files = files.files;
    input.dispatchEvent(new Event("change", {bubbles: true}));
    await uploaded;
    return null;
  }, epub);
  await screen.getByRole("button", "File attachment, revenue-report.epub", {exact: false}).waitFor();
  await screen.getByRole("textbox").tap();
  await browser.keyboard.press("End");
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete").waitFor();
  await screen.getByRole("button", "Stop generation", {exact: true}).waitFor({state: "hidden"});
  const dir = `${T3_HOME}/userdata/attachments`;
  const sidecar = (await readdir(dir)).find(name => name.endsWith(".epub.txt") && !name.startsWith("pending-"));
  if (!sidecar) throw new Error("Upload did not produce extracted-text sidecar");
  const text = await readFile(`${dir}/${sidecar}`, "utf8");
  await writeFile(`${project}/revenue-report.epub.txt`, text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("revenue-report.epub.txt");
  await screen.getByRole("option", "revenue-report.epub.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 "";
  });
  // Wait for the actual sidecar to render before capturing either outcome.
  await expect.poll(editorText).toContain("100");
  await app.screenshot("extracted-epub-text");
  expect(text).toContain("Table 1: Quarterly revenue\nQ1\tQ2\n100\t200");
});
