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

async function epub(prefixed: boolean) {
  const tag = (name: string) => prefixed ? `m:${name}` : name;
  const math = `<${tag("math")} ${prefixed ? 'xmlns:m' : 'xmlns'}="http://www.w3.org/1998/Math/MathML"><${tag("semantics")}><${tag("mrow")}><${tag("mi")}>x</${tag("mi")}><${tag("mo")}>+</${tag("mo")}><${tag("mi")}>y</${tag("mi")}></${tag("mrow")}><${tag("annotation")} encoding="application/x-tex">x+y</${tag("annotation")}><${tag("annotation-xml")} encoding="application/mathml-content+xml"><${tag("apply")}><${tag("plus")}/><${tag("ci")}>x</${tag("ci")}><${tag("ci")}>y</${tag("ci")}></${tag("apply")}></${tag("annotation-xml")}></${tag("semantics")}></${tag("math")}>`;
  return new JSZip()
    .file("mimetype", "application/epub+zip", { compression: "STORE" })
    .file("META-INF/container.xml", '<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", '<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">symmetric</dc:identifier><dc:title>Symmetry</dc:title><dc:language>en</dc:language></metadata><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml" properties="mathml"/></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><p>The expression ${math} is symmetric.</p></body></html>`)
    .generateAsync({ type: "base64" });
}

async function sidecars() {
  const files = await readdir(T3_HOME, { recursive: true });
  return files.filter(file => file.endsWith(".epub.txt")).sort();
}

test("EPUB uploads extract the displayed MathML expression once", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("epub-proof");
  const thread = await t3.thread({ project, title: "EPUB MathML extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const texts: string[] = [];
  for (const prefixed of [true, false]) {
    const previous = await sidecars();
    const name = prefixed ? "symmetric-prefixed.epub" : "symmetric-default-ns.epub";
    await browser.evaluate(({ base64, name }) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
      if (!input) throw new Error("Attachment file input not found");
      const data = new DataTransfer();
      data.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], name, { type: "application/epub+zip" }));
      input.files = data.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
    }, { base64: await epub(prefixed), name });
    await expect.poll(async () => (await sidecars()).filter(file => !previous.includes(file)).length).toBe(1);
    const file = (await sidecars()).find(file => !previous.includes(file))!;
    texts.push(`${name}\n${await readFile(join(T3_HOME, file), "utf8")}`);
  }
  // Display a verbatim copy of the real upload sidecars in the app's file viewer.
  await writeFile(join(project, "extracted-epub-text.txt"), texts.join("\n\n--------------------\n\n"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-epub-text.txt");
  await screen.getByRole("option", "extracted-epub-text.txt", { exact: false }).tap();
  const visibleText = () => browser.evaluate(() => {
    const panel = document.querySelector("[data-right-panel-surface-content]");
    for (const host of panel?.querySelectorAll("*") ?? []) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return panel?.textContent ?? "";
  });
  await expect.poll(visibleText).toContain("The expression");
  await app.screenshot("uploaded-epub-extracted-text");
  await expect.poll(visibleText).not.toContain("x+yx+yxy");
  for (const text of texts) expect(text).toContain("The expression x+y is symmetric.");
});
