/// <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 }).catch(() => []);
  const nested = await Promise.all(entries.map(async entry => entry.isDirectory()
    ? sidecars(join(dir, entry.name))
    : entry.name.endsWith(".epub.txt") ? [join(dir, entry.name)] : []));
  return nested.flat();
}

test("EPUB XHTML main separates adjacent prose while foreign main stays inline", 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 xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles><rootfile full-path="content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>');
  zip.file("content.opf", '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>');
  zip.file("chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><body><div>Harbor directions.<main><strong>Use the north pier.</strong></main>Boats depart at noon.</div><div>Keep<x:main xmlns:x="urn:example"> this </x:main>inline too.</div></body></html>');
  const bytes = await zip.generateAsync({ type: "base64", compression: "STORE" });
  const project = await t3.project("harbor");
  const thread = await t3.thread({ project, title: "EPUB extracted text", messages: ["Start"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Read the extracted-text file for the attached EPUB and print its exact contents verbatim inside a code block, preserving every line break. Do nothing else.");
  await browser.evaluate((payload: string) => {
    const input = document.querySelector<HTMLInputElement>('form[data-chat-composer-form] input[type="file"]');
    if (!input) throw new Error("No attachment picker input");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(payload), c => c.charCodeAt(0))], "harbor.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, bytes);
  await composer.press("Enter");
  // Observe the real upload's sidecar rather than asking replay to invent extraction output.
  let extracted = "";
  await expect.poll(async () => {
    const files = await sidecars(join(T3_HOME, "userdata"));
    if (!files[0]) return false;
    extracted = await readFile(files[0], "utf8");
    await copyFile(files[0], join(project, "harbor-extracted.txt"));
    return true;
  }).toBe(true);
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await composer.fill("Actual server-generated EPUB text: [harbor-extracted.txt](harbor-extracted.txt)");
  await composer.press("Enter");
  await screen.getByRole("link", "harbor-extracted.txt", { exact: true }).tap();
  await browser.locator("[data-right-panel-surface-content]").waitFor();
  const rendered = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return null;
  });
  await expect.poll(rendered).toContain("Harbor directions.");
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("epub-extracted-text");
  expect(extracted).toContain("Harbor directions.\nUse the north pier.\nBoats depart at noon.");
  expect(extracted).toContain("Keep this inline too.");
});
