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

test("EPUB extraction omits hidden map groups with parenthesised style values", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip()
    .file("mimetype", "application/epub+zip")
    .file("META-INF/container.xml", '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>')
    .file("book.opf", '<package version="3.0"><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="map" href="map.svg" media-type="image/svg+xml"/></manifest><spine><itemref idref="chapter"/><itemref idref="map"/></spine></package>')
    .file("chapter.xhtml", '<html xmlns="http://www.w3.org/1999/xhtml"><body><p>Welcome to the harbour guide.</p></body></html>')
    .file("map.svg", `<svg xmlns="http://www.w3.org/2000/svg"><text>Harbour map</text><g><text>Visible ferry terminal</text></g><g style="display: none !important"><text>Superseded gate</text></g><g style="transform: translate(10px); display: none !important"><text>Closed ferry berth</text></g><g style="filter: drop-shadow(0 0 1px red); display: none !important"><text>Old pier</text></g><g style="transform: translate(5px)"><text>Visible lighthouse</text></g><g style="filter: url('#shadow'); display: none !important"><text>Hidden URL label</text></g><g style="transform: translate(2px); display: none !important; display: block !important"><text>Reopened quay</text></g></svg>`);
  const bytes = await zip.generateAsync({ type: "uint8array" });
  const project = await t3.project("harbour-guide");
  await t3.open();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await screen.getByRole("option", /Multi turn/).tap();
  const selector = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(selector).waitFor({ state: "attached" });
  await browser.evaluate(({ selector, bytes }) => {
    const input = document.querySelector<HTMLInputElement>(selector)!;
    const transfer = new DataTransfer();
    transfer.items.add(new File([new Uint8Array(bytes)], "harbour-guide.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, { selector, bytes: Array.from(bytes) });
  await screen.getByRole("button", /^File attachment, harbour-guide\.epub,/).waitFor();
  await screen.getByRole("textbox").fill("Summarise the harbour map in this guide.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor({ timeout: 120_000 });
  const dir = `${T3_HOME}/userdata/attachments`;
  const files = await readdir(dir, { recursive: true });
  const name = files.find((name) => name.endsWith(".epub.txt"));
  if (!name) throw new Error(`No extracted EPUB text: ${files.join(", ")}`);
  const text = await readFile(`${dir}/${name}`, "utf8");
  await writeFile(`${project}/extracted-harbour-map.txt`, text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-harbour-map.txt");
  await screen.getByRole("option", "extracted-harbour-map.txt", { exact: false }).tap();
  await screen.getByText("Welcome to the harbour guide.", { exact: false }).waitFor();
  await app.screenshot("extracted-harbour-map");
  expect(text).not.toContain("Closed ferry berth");
  expect(text).not.toContain("Old pier");
  expect(text).not.toContain("Hidden URL label");
  expect(text).not.toContain("Superseded gate");
  for (const label of ["Harbour map", "Visible ferry terminal", "Visible lighthouse", "Reopened quay"]) expect(text).toContain(label);
});
