/// <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 epub(nested: boolean) {
  const zip = new JSZip();
  zip.file("mimetype", "application/epub+zip");
  zip.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="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" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">revenue</dc:identifier><dc:title>Revenue</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>');
  const table = '<table><tr><th>Month</th><th>Revenue</th></tr><tr><td>June</td><td>400</td></tr></table>';
  zip.file("chapter.xhtml", `<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Chapter 1</title></head><body>${nested ? `<div>Quarterly revenue${table}</div>` : `<div>Quarterly revenue</div>${table}`}</body></html>`);
  return zip.generateAsync({ type: "base64" });
}

test("EPUB nested table starts on a new line", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Revenue");
  const thread = await t3.thread({ project, title: "EPUB extraction", messages: ["Inspect revenue attachments"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  const results: string[] = [];
  for (const nested of [true, false]) {
    const previous = new Set(await readdir(join(T3_HOME, "userdata", "attachments")).catch(() => []));
    await browser.evaluate(({ bytes, name }) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
      if (!input) throw new Error("Composer file input missing");
      const transfer = new DataTransfer();
      transfer.items.add(new File([Uint8Array.from(atob(bytes), c => c.charCodeAt(0))], name, { type: "application/epub+zip" }));
      input.files = transfer.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
      return null;
    }, { bytes: await epub(nested), name: nested ? "revenue-nested.epub" : "revenue-sibling.epub" });
    let extracted = "";
    await expect.poll(async () => {
      const dir = join(T3_HOME, "userdata", "attachments");
      const file = (await readdir(dir).catch(() => [])).find(f => f.endsWith(".epub.txt") && !previous.has(f));
      if (file) extracted = await readFile(join(dir, file), "utf8");
      return extracted;
    }, { timeout: 30000 }).not.toBe("");
    results.push(extracted);
  }
  await writeFile(join(project, "extraction.txt"), results.map((text, i) => `${i === 0 ? "NESTED TABLE" : "SIBLING TABLE (control)"}\n${text}\n`).join("\n"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("printf ready > shell-ready");
    await browser.keyboard.press("Enter");
    return readFile(join(project, "shell-ready"), "utf8").catch(() => "");
  }, { timeout: 30000 }).toBe("ready");
  await browser.keyboard.type("export PS1='$ '; clear; cat extraction.txt; printf '\\nEXTRACTION COMPLETE\\n'");
  await browser.keyboard.press("Enter");
  await expect.poll(async () => {
    await browser.evaluate(() => {
      delete document.body.dataset.terminalCopy;
      window.addEventListener("copy", event => { document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? ""; }, { once: true });
      return null;
    });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
  }).toContain("EXTRACTION COMPLETE");
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("extracted-revenue-table");
  expect(results[0]).toContain("Quarterly revenue\nMonth\tRevenue");
  expect(results[1]).toContain("Quarterly revenue\nMonth\tRevenue");
});
