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

async function sidecars(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  const nested = await Promise.all(entries.map(entry => entry.isDirectory()
    ? sidecars(join(dir, entry.name))
    : Promise.resolve(entry.name.endsWith(".epub.txt") ? [join(dir, entry.name)] : [])));
  return nested.flat();
}

test("EPUB attachment extraction keeps center blocks on separate lines", 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", '<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">harbour</dc:identifier><dc:title>The Harbour Book</dc:title><dc:language>en</dc:language></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
    .file("OEBPS/nav.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">Chapter 1</a></li></ol></nav></body></html>')
    .file("OEBPS/chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>The Harbour Book<center>A Novel</center><center>By Ada Lovelace</center>First printing.</div></body></html>')
    .generateAsync({ type: "base64" });
  const project = await t3.project("Harbour");
  const thread = await t3.thread({ project, title: "EPUB title page", messages: ["Start"], model: "showcase" });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await screen.getByRole("textbox").fill("Quote the title page of this book line by line.");
  await browser.evaluate((base64: string) => {
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("Attachment file input missing");
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "harbour.epub", { type: "application/epub+zip" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, epub);
  await screen.getByRole("button", "File attachment, harbour.epub", { exact: false }).waitFor();
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByText("Quote the title page of this book line by line.", { exact: false }).waitFor({ state: "attached" });
  await browser.locator('button[aria-label="Submit message"]').waitFor();
  const files = await sidecars(join(T3_HOME, "userdata"));
  const sidecar = files[0];
  if (!sidecar) throw new Error("Server did not write an EPUB extracted-text sidecar");
  const extracted = await readFile(sidecar, "utf8");
  // Display an unchanged copy of the real server sidecar in the app's file viewer.
  await copyFile(sidecar, join(project, "extracted-title-page.txt"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-title-page.txt");
  await screen.getByRole("option", "extracted-title-page.txt", { exact: false }).tap();
  await screen.getByText("The Harbour Book", { exact: false }).last().waitFor();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("extracted-title-page");
  expect(extracted).toContain("The Harbour Book\nA Novel\nBy Ada Lovelace\nFirst printing.");
});
