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

test("EPUB attachment extracts its manifest fallback in spine order", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip();
  zip.file("mimetype", "application/epub+zip", { compression: "STORE" });
  zip.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>`);
  zip.file("book.opf", `<?xml version="1.0"?><package version="3.0" xmlns="http://www.idpf.org/2007/opf" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">urn:uuid:02dcc9c6-e2ed-4f06-8c56-d9f67b16c759</dc:identifier><dc:title>Harbor journey</dc:title><dc:language>en</dc:language><meta property="dcterms:modified">2026-12-02T00:00:00Z</meta></metadata><manifest><item id="csv" href="schedule.csv" media-type="text/csv" fallback="dawn"/><item id="dawn" href="dawn.xhtml" media-type="application/xhtml+xml"/><item id="pier" href="pier.xhtml" media-type="application/xhtml+xml"/><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/></manifest><spine><itemref idref="csv"/><itemref idref="pier"/></spine></package>`);
  zip.file("schedule.csv", "departure,destination\n07:15,harbor\n");
  zip.file("dawn.xhtml", `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Dawn</title></head><body><p>Take the 07:15 ferry.</p></body></html>`);
  zip.file("pier.xhtml", `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Pier</title></head><body><p>Meet at Pier 8.</p></body></html>`);
  zip.file("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="dawn.xhtml">Dawn</a></li><li><a href="pier.xhtml">Pier</a></li></ol></nav></body></html>`);
  const bytes = await zip.generateAsync({ type: "base64" });
  const project = await t3.project("Harbor journey");
  const thread = await t3.thread({ project, title: "Quote both EPUB chapters", messages: ["Ready to review the EPUB."] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Please quote both chapters of the attached EPUB in reading order.");
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(({ input, bytes }) => {
    const picker = document.querySelector<HTMLInputElement>(input)!;
    const files = new DataTransfer();
    files.items.add(new File([Uint8Array.from(atob(bytes), c => c.charCodeAt(0))], "harbor.epub", { type: "application/epub+zip" }));
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, { input, bytes });
  await screen.getByRole("button", /^File attachment, harbor\.epub,/).waitFor();
  await screen.getByRole("textbox").press("Enter");

  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const files = await readdir(join(T3_HOME, "userdata", "attachments"), { recursive: true });
  const sidecar = files.find(file => file.endsWith(".epub.txt"));
  if (!sidecar) throw new Error("Uploaded EPUB extraction sidecar was not created");
  const source = join(T3_HOME, "userdata", "attachments", sidecar);
  const text = await readFile(source, "utf8");
  await copyFile(source, join(project, "harbor.epub.txt"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("harbor.epub.txt");
  await screen.getByRole("option", "README.md", { exact: false }).waitFor({ state: "hidden" });
  await screen.getByRole("option", "harbor.epub.txt", { exact: false }).waitFor();
  await screen.getByPlaceholder("Search files…").press("Enter");
  await screen.getByText("Meet at Pier 8.", { exact: false }).waitFor();
  await app.screenshot("epub-text-sent-to-agent");
  expect(text).toMatch(/Take the 07:15 ferry\.[\s\S]*Meet at Pier 8\./);
});
