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

async function epub() {
  return 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="book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
    .file("book.opf", '<?xml version="1.0"?><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">example</dc:identifier><dc:title>Example</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("chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>Example command:<pre><code>git status --short\n  git log -1</code></pre><p>Inspect the output.</p></div></body></html>')
    .generateAsync({ type: "base64" });
}

test("EPUB upload separates preformatted commands from surrounding prose", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("EPUB example", { "extracted.txt": "Waiting for attachment extraction" });
  const thread = await t3.thread({ project, title: "EPUB extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Inspect example.epub");
  await browser.evaluate((base64: string) => {
    const bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([bytes], "example.epub", { type: "application/epub+zip" }));
    const editor = document.querySelector('[contenteditable="true"]');
    if (!editor) throw new Error("Composer missing");
    editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
  }, await epub());
  const sidecar = async () => {
    const dir = join(T3_HOME, "userdata", "attachments");
    const entries = await readdir(dir, { recursive: true });
    const file = entries.find(name => name.endsWith(".epub.txt"));
    return file ? readFile(join(dir, file), "utf8") : "";
  };
  // Wait for the real upload's extracted-text sidecar, then display its unmodified bytes in the app.
  await expect.poll(sidecar).not.toBe("");
  const extracted = await sidecar();
  await writeFile(join(project, "extracted.txt"), extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted.txt");
  await screen.getByRole("option", "extracted.txt", { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("Example command:");
  await app.screenshot("extracted-epub-text");
  expect(extracted).toBe("## Chapter 1\nExample command:\ngit status --short\n  git log -1\nInspect the output.");
});
