import { expect } from "e2e";
import { execFileSync } from "node:child_process";
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";

const epub = execFileSync("python3", ["-c", `
import io, zipfile, sys
b=io.BytesIO()
with zipfile.ZipFile(b,'w') as z:
 z.writestr('mimetype','application/epub+zip')
 z.writestr('META-INF/container.xml','<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/book.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')
 z.writestr('OEBPS/book.opf','<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Hidden passages</dc:title></metadata><manifest><item id="c1" href="c1.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c1"/></spine></package>')
 z.writestr('OEBPS/c1.xhtml','<html xmlns="http://www.w3.org/1999/xhtml"><body><p>Visible opening paragraph.</p><p hidden="">Draft note: SECRET-ALPHA hidden empty-value paragraph.</p><div hidden="hidden">Draft note: SECRET-BRAVO hidden div <em>with nested emphasis</em><p>and a nested SECRET-CHARLIE paragraph.</p></div><details><summary>Summary</summary><p hidden="until-found">Until-found answer paragraph.</p></details><p>Visible closing paragraph.</p></body></html>')
sys.stdout.buffer.write(b.getvalue())
`]).toString("base64");

test("EPUB upload excludes hidden passages from the text provided to agents", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("epub-review");
  const thread = await t3.thread({ project, title: "EPUB attachment extraction", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("Quote the full text of the attached document verbatim, line by line, including any draft notes. Do not summarize or edit files.");
  await browser.evaluate((base64) => {
    const input = document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("Attach files input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "hidden-passages.epub", { type: "application/epub+zip" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, epub);
  await screen.getByRole("button", "File attachment, hidden-passages.epub", { exact: false }).waitFor();
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const files = await readdir(join(T3_HOME, "userdata", "attachments"), { recursive: true });
  const sidecar = files.find(file => file.endsWith(".epub.txt"));
  if (!sidecar) throw new Error(`Uploaded EPUB sidecar missing: ${files.join(", ")}`);
  const text = await readFile(join(T3_HOME, "userdata", "attachments", sidecar), "utf8");
  // Display the exact server-produced sidecar, without altering its contents, in the real file viewer.
  await writeFile(join(project, "agent-attachment-text.txt"), text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("agent-attachment-text.txt");
  await screen.getByRole("option", "agent-attachment-text.txt", { exact: false }).tap();
  await screen.getByText("Visible opening paragraph.", { exact: false }).waitFor();
  await app.screenshot("agent-attachment-text");
  expect(text).not.toContain("SECRET-");
  expect(text).toContain("Until-found answer paragraph.");
  expect(text).toContain("Visible closing paragraph.");
});
