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

const epub = () => new JSZip()
 .file("mimetype", "application/epub+zip", { compression: "STORE" })
 .file("META-INF/container.xml", '<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
 .file("book.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">travel</dc:identifier><dc:title>Travel notes</dc:title><dc:language>en</dc:language></metadata><manifest><item id="ch" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="ch"/></spine></package>')
 .file("chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>Departure information.<aside>Check local time.</aside>Board promptly.</div></body></html>')
 .generateAsync({ type: "base64" });

async function extracted() {
 const root = join(T3_HOME, "userdata");
 const entries = await readdir(root, { recursive: true });
 const sidecar = entries.find(p => p.endsWith(".epub.txt"));
 return sidecar ? readFile(join(root, sidecar), "utf8") : "";
}

test("An attached EPUB keeps the visible aside separate in its extracted text", WEB, async ({t3, app, browser, screen}) => {
 const project = await t3.project("travel-notes");
 const thread = await t3.thread({project, title: "Read EPUB extracted text", messages: ["Start"]});
 await t3.open(thread);
 await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
 const composer = screen.getByRole("textbox");
 await composer.fill("Read the attachment's extracted text file.");
 await browser.evaluate((payload) => {
  const bytes = Uint8Array.from(atob(payload), c => c.charCodeAt(0));
  const clipboardData = new DataTransfer();
  clipboardData.items.add(new File([bytes], "travel-notes.epub", {type:"application/epub+zip"}));
  document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", {clipboardData,bubbles:true,cancelable:true}));
 }, await epub());
 await browser.keyboard.press("Enter");
 // Wait for the real server's attachment claim and document extraction, then open an exact copy.
 let text = "";
 await expect.poll(async () => { text = await extracted(); return text.includes("Board promptly."); }, {timeout:60000}).toBe(true);
 await writeFile(join(project,"extracted-text.txt"), text);
 await browser.keyboard.press("Control+p");
 await screen.getByPlaceholder("Search files…").fill("extracted-text.txt");
 await screen.getByRole("option", "extracted-text.txt", {exact:false}).tap();
 await screen.getByText("Departure information.", {exact:false}).first().waitFor();
 await app.screenshot("extracted-epub-text");
 await expect(text).toContain("Departure information.\nCheck local time.\nBoard promptly.");
});
