/// <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 presentation() {
  const frame = (attributes: string, text: string) => `<draw:frame ${attributes}><draw:text-box><text:p>${text}</text:p></draw:text-box></draw:frame>`;
  return new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.presentation", { compression: "STORE" })
    .file("content.xml", `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:drawooo="http://openoffice.org/2010/draw" office:version="1.3"><office:body><office:presentation><draw:page draw:name="Slide 1">${frame('', 'Visible slide text')}${frame('drawooo:display="screen"', 'Screen-only text')}${frame('drawooo:display="printer"', 'Printed handout only')}${frame('draw:layer="PrintOnly"', 'Print-only layer')}</draw:page></office:presentation></office:body></office:document-content>`)
    .file("styles.xml", '<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"><office:master-styles><draw:layer-set><draw:layer draw:name="PrintOnly" draw:display="printer"/></draw:layer-set></office:master-styles></office:document-styles>')
    .generateAsync({ type: "uint8array" });
}

test("Presentation attachment supplies only on-screen text", WEB, async ({ t3, app, screen, browser }) => {
  const bytes = await presentation();
  const project = await t3.project("presentation-proof", { "printonly-object.odp": bytes });
  const thread = await t3.thread({ project, title: "Presentation text extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(({ input, bytes }) => {
    const picker = document.querySelector<HTMLInputElement>(input)!;
    const files = new DataTransfer();
    files.items.add(new File([new Uint8Array(bytes)], "printonly-object.odp", { type: "application/vnd.oasis.opendocument.presentation" }));
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, { input, bytes: Array.from(bytes) });
  await screen.getByRole("button", "File attachment, printonly-object.odp", { exact: false }).waitFor();
  await screen.getByRole("textbox").focus();
  await browser.keyboard.press("End");
  await browser.keyboard.type("Read the attached slides.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const attachmentDir = join(T3_HOME, "userdata", "attachments");
  const names = await readdir(attachmentDir, { recursive: true });
  const name = names.find((name) => name.endsWith(".odp.txt"));
  if (!name) throw new Error("No extracted presentation attachment text found");
  const extracted = await readFile(join(attachmentDir, name), "utf8");
  // Display the actual sidecar supplied by the server, without asking replay to invent a response.
  await writeFile(join(project, "extracted-attachment.txt"), extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-attachment.txt");
  await screen.getByRole("option", "extracted-attachment.txt", { exact: false }).tap();
  await screen.getByText("Visible slide text", { exact: false }).waitFor();
  await app.screenshot("extracted-presentation-text");
  expect(extracted).toContain("Visible slide text");
  expect(extracted).toContain("Screen-only text");
  expect(extracted).not.toContain("Printed handout only");
  expect(extracted).not.toContain("Print-only layer");
});
