/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

async function findText(dir: string): Promise<string | null> {
  for (const item of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, item.name);
    if (item.isDirectory()) { const found = await findText(path); if (found) return found; }
    else if (item.name.endsWith(".txt")) {
      const text = await readFile(path, "utf8");
      if (text.includes("Glossary") && text.includes("Port")) return text;
    }
  }
  return null;
}

test("EPUB attachment extraction preserves glossary term and definition boundaries", WEB, async ({t3, app, screen, browser}) => {
  const epub = await new JSZip()
    .file("mimetype", "application/epub+zip", {compression:"STORE"})
    .file("META-INF/container.xml", '<container><rootfiles><rootfile full-path="content.opf"/></rootfiles></container>')
    .file("content.opf", '<package><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"><body><h1>Glossary</h1><dl><dt>Port</dt><dd>443</dd><dt>Timeout</dt><dd>30 seconds</dd></dl></body></html>')
    .generateAsync({type:"base64"});
  const project = await t3.project("glossary-demo");
  const thread = await t3.thread({project, title:"EPUB glossary extraction", messages:["first"]});
  await browser.setViewport({width:1440,height:1080});
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  const composer = screen.getByRole("textbox");
  await composer.fill("Read the extracted text file for the attached EPUB with cat and quote the glossary section verbatim inside a code block, preserving line breaks exactly. Do not reformat.");
  await browser.evaluate((encoded) => {
    const bytes = Uint8Array.from(atob(encoded), c => c.charCodeAt(0));
    const data = new DataTransfer();
    data.items.add(new File([bytes], "glossary.epub", {type:"application/epub+zip"}));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", {clipboardData:data,bubbles:true,cancelable:true}));
  }, epub);
  await screen.getByText("glossary.epub", {exact:false}).waitFor();
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor();
  let extracted: string | null = null;
  await expect.poll(async () => { extracted = await findText(join(T3_HOME,"userdata")); return extracted !== null; }).toBe(true);
  // Display the actual server-written sidecar through the app's file viewer.
  await writeFile(join(project,"glossary-extracted.txt"), extracted!);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("glossary-extracted.txt");
  await screen.getByRole("option", "glossary-extracted.txt", {exact:false}).tap();
  await screen.getByText("Port", {exact:false}).first().waitFor();
  await app.screenshot("glossary-extracted-text");
  expect(extracted).toContain("Port\n443\nTimeout\n30 seconds");
});
