/// <reference lib="dom" />
import { readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import JSZip from "jszip";
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="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">boarding-guide</dc:identifier><dc:title>Boarding guide</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("OEBPS/chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Boarding guide</title></head><body><h1>Travel day</h1><ol><li>Before boarding<div><ul><li>Check passports</li></ul></div></li></ol><p>Intro</p><div><ul><li>Read the checklist</li></ul></div><p>Empty control starts<ul></ul>ends</p><p>Hidden control starts<ul><li hidden="hidden">Invisible</li></ul>ends</p></body></html>')
    .generateAsync({ type: "base64" });
}
async function extracted() {
  const entries = await readdir(T3_HOME, { recursive: true });
  const file = entries.find((name) => name.endsWith(".epub.txt"));
  return file ? readFile(join(T3_HOME, file), "utf8") : "";
}
test("Wrapped EPUB nested lists keep their text boundary after composer upload", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("boarding-guide");
  const thread = await t3.thread({ project, title: "Boarding guide extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read the attached boarding guide and preserve its line breaks.");
  await browser.evaluate((base64) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("Attachment input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "boarding-guide.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, await epub());
  await screen.getByText("boarding-guide.epub", { exact: false }).first().waitFor();
  await browser.keyboard.press("Enter");
  await expect.poll(extracted, { timeout: 120000 }).toContain("Travel day");
  const text = await extracted();
  // Show the server-created sidecar verbatim in the app's file viewer, without model rewriting.
  await writeFile(join(project, "extracted-attachment.txt"), text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-attachment.txt");
  await screen.getByRole("option", "extracted-attachment.txt", { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("Check passports");
  await app.screenshot("extracted-attachment-text");
  expect(text).toContain("Before boarding\nCheck passports");
  expect(text).toContain("Intro\nRead the checklist");
  expect(text).toContain("Empty control startsends");
  expect(text).toContain("Hidden control startsends");
});
