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 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:title>Disclosure</dc:title><dc:identifier id="id">disclosure</dc:identifier><dc:language>en</dc:language></metadata><manifest><item id="a" href="a.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="a"/></spine></package>')
    .file("a.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>Intro<details open="open"><summary><strong>Supported</strong> files</summary>JPEG <em>files</em> only.</details>Next section</div></body></html>')
    .generateAsync({ type: "base64" });
}
async function sidecars(dir: string): Promise<string[]> {
  const found: string[] = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) found.push(...await sidecars(path));
    else if (entry.name.endsWith(".epub.txt")) found.push(path);
  }
  return found;
}

test("EPUB upload separates disclosure summary and answer from surrounding prose", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("disclosure-proof");
  const thread = await t3.thread({ project, title: "EPUB disclosure extraction", messages: ["Inspect the extracted text of disclosure.epub." ] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read the attached 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], "disclosure.epub", { type: "application/epub+zip" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
  }, await epub());
  await screen.getByRole("button", /^(Submit|Send) message$/, { exact: true }).tap();
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const files = await sidecars(join(T3_HOME, "userdata"));
  if (!files.length) throw new Error("No extracted EPUB sidecar after upload");
  const extracted = await readFile(files[0]!, "utf8");
  await writeFile(join(project, "extracted-epub.txt"), extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-epub.txt");
  await screen.getByRole("option", "extracted-epub.txt", { exact: false }).tap();
  await screen.getByRole("textbox", "extracted-epub.txt", { exact: true }).waitFor();
  await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
  await app.screenshot("epub-extracted-text");
  expect(extracted).toContain("Intro\nSupported files\nJPEG files only.\nNext section");
});
