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

test("EPUB figure captions keep block and paragraph boundaries", WEB, async ({ t3, app, screen, browser }) => {
  const epub = await 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">river</dc:identifier><dc:title>River</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><figure><img src="map.png" alt="Map of the river"/><figcaption>Figure 1. River crossings</figcaption></figure><p>Water levels rose in May.</p><figure><img src="map.png" alt="Map of the valley"/><figcaption><p>Figure 2. Valley crossings</p><p>Surveyed in June.</p></figcaption></figure><p>Rain returned in July.</p></body></html>')
    .generateAsync({ type: "base64" });
  const project = await t3.project("river-demo");
  const thread = await t3.thread({ project, title: "Summarize the river chapter", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("Summarize the attached chapter.");
  await browser.evaluate((payload: string) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("No attachment file input");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(payload), c => c.charCodeAt(0))], "river.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, epub);
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const files = await fs.readdir(path.join(T3_HOME, "userdata/attachments"));
  const extracted = files.find(f => f.endsWith(".epub.txt"));
  if (!extracted) throw new Error(`No extracted EPUB text: ${files.join(", ")}`);
  const text = await fs.readFile(path.join(T3_HOME, "userdata/attachments", extracted), "utf8");
  await fs.writeFile(path.join(project, "extracted-river.txt"), text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-river.txt");
  await screen.getByRole("option", "extracted-river.txt", { exact: false }).tap();
  await screen.getByText("Map of the river", { exact: false }).first().waitFor();
  await app.screenshot("extracted-epub-text");
  expect(text).toContain("Map of the river\nFigure 1. River crossings\nWater levels rose in May.");
  expect(text).toMatch(/Map of the valley\nFigure 2\. Valley crossings\n+Surveyed in June\.\n+Rain returned in July\./);
});
