import { readFile, readdir, copyFile } 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 sidecars(dir: string): Promise<string[]> {
  const found: string[] = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) found.push(...await sidecars(path));
    else if (entry.name.endsWith(".epub.txt")) found.push(path);
  }
  return found;
}

test("EPUB block quotations separate adjacent prose and preserve empty quotation spacing", 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"><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><div>Safety note<blockquote>Check the gate.</blockquote>Continue to the terminal.</div><div>Keep some <blockquote></blockquote>space.</div></body></html>')
    .generateAsync({ type: "uint8array" });
  const project = await t3.project("EPUB proof");
  const thread = await t3.thread({ project, title: "EPUB extracted text", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("Read the extracted-text file for the attached EPUB and show its full contents verbatim in a code block. Do nothing else.");
  await browser.evaluate((bytes: number[]) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("No attachment picker input");
    const transfer = new DataTransfer();
    transfer.items.add(new File([new Uint8Array(bytes)], "guide.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, Array.from(epub));
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  let path = "";
  await expect.poll(async () => { path = (await sidecars(T3_HOME))[0] ?? ""; return path !== ""; }).toBe(true);
  const text = await readFile(path, "utf8");
  // Show the actual server-generated sidecar through the app's file viewer; Replay does not read files.
  await copyFile(path, join(project, "extracted-EPUB-text.txt"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-EPUB-text.txt");
  await screen.getByRole("option", "extracted-EPUB-text.txt", { exact: false }).tap();
  await screen.getByText("Safety note", { exact: false }).first().waitFor();
  await app.screenshot("extracted-epub-text");
  expect(text).toBe("## Chapter 1\nSafety note\nCheck the gate.\nContinue to the terminal.\nKeep some space.");
});
