/// <reference lib="dom" />
import { readFile, readdir, copyFile } from "node:fs/promises";
import JSZip from "jszip";
import { expect } from "e2e";
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 version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
    .file("EPUB/package.opf", '<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book">urn:uuid:travel-guide</dc:identifier><dc:title>Travel Guide</dc:title><dc:language>en</dc:language><meta property="dcterms:modified">2026-01-01T00:00:00Z</meta></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("EPUB/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("EPUB/chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body><div>Arrive at the platform.<hr/>Collect your luggage.</div></body></html>')
    .generateAsync({ type: "uint8array" });
}

test("EPUB attachment extraction separates passages around a thematic break", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const bytes = await epub();
  const project = await t3.project("travel-guide", { "travel-guide.epub": bytes });
  const thread = await t3.thread({ project, title: "Review EPUB attachment", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  // Supply the file to the composer's native input; upload and extraction use the real app.
  await browser.evaluate(async (bytes) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
    if (!input) throw new Error("Composer attachment input is missing");
    const original = XMLHttpRequest.prototype.send;
    const uploaded = new Promise<void>((resolve, reject) => {
      XMLHttpRequest.prototype.send = function (...args) {
        this.addEventListener("load", () => {
          if (this.responseURL.includes("/api/attachments/upload")) {
            XMLHttpRequest.prototype.send = original;
            if (this.status >= 200 && this.status < 300) resolve();
            else reject(new Error(`Upload failed: ${this.status}`));
          }
        });
        return original.apply(this, args);
      };
    });
    const data = new DataTransfer();
    data.items.add(new File([new Uint8Array(bytes)], "travel-guide.epub", { type: "application/epub+zip" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    await uploaded;
    return null;
  }, Array.from(bytes));
  const dir = `${T3_HOME}/userdata/attachments`;
  const sidecar = (await readdir(dir)).find((file) => file.endsWith(".epub.txt"));
  if (!sidecar) throw new Error("Upload did not produce an EPUB text sidecar");
  const extracted = await readFile(`${dir}/${sidecar}`, "utf8");
  // Copy the bytes unchanged so the actual generated text can be inspected in the app viewer.
  await copyFile(`${dir}/${sidecar}`, `${project}/travel-guide.epub.txt`);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("travel-guide.epub.txt");
  await screen.getByRole("option", "travel-guide.epub.txt", { exact: false }).tap();
  await browser.locator("[data-right-panel-surface-content]").getByText("Arrive at the platform.", { exact: false }).waitFor();
  await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
  await app.screenshot("extracted-epub-text");
  expect(extracted).toContain("Arrive at the platform.\nCollect your luggage.");
});
