/// <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 deck() {
  const zip = new JSZip();
  const ns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  zip.file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/></Types>');
  zip.file("ppt/presentation.xml", `<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="${ns}"><p:sldIdLst xmlns:links="${ns}"><p:sldId r:id="rId1" id="256"/><p:sldId links:id="rId2" id="257"/></p:sldIdLst></p:presentation>`);
  zip.file("ppt/_rels/presentation.xml.rels", `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="${ns}/slide" Target="slides/slide1.xml"/><Relationship Id="rId2" Type="${ns}/slide" Target="slides/slide2.xml"/></Relationships>`);
  for (const [index, name, text] of [[1, "ALPHA", "first"], [2, "BRAVO", "second"]] as const) {
    zip.file(`ppt/slides/slide${index}.xml`, `<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${name} ${text} slide text</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`);
    zip.file(`ppt/slides/_rels/slide${index}.xml.rels`, `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="notes" Type="${ns}/notesSlide" Target="../notesSlides/notesSlide${index}.xml"/></Relationships>`);
    zip.file(`ppt/notesSlides/notesSlide${index}.xml`, `<p:notes xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${name} speaker notes</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:notes>`);
  }
  return zip.generateAsync({ type: "base64" });
}

test("PowerPoint attachment keeps alternate-prefix slide text and notes", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("PowerPoint review");
  const thread = await t3.thread({ project, title: "Deck extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read the extracted text of the attached deck.");
  // Deliver the same FileList change as the composer's native Attach files picker.
  await browser.evaluate((base64: string) => {
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "alternate-prefix.pptx", { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, await deck());
  const attachments = join(T3_HOME, "userdata", "attachments");
  let sidecar = "";
  await expect.poll(async () => {
    const files = await readdir(attachments, { recursive: true });
    const file = files.find(f => f.endsWith(".pptx.txt"));
    if (!file) return "";
    sidecar = await readFile(join(attachments, file), "utf8");
    return sidecar;
  }).toContain("ALPHA first slide text");
  // Copy the actual upload sidecar unchanged into the scratch project so the real file viewer can display it.
  await writeFile(join(project, "extracted-deck.txt"), sidecar);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-deck.txt");
  await screen.getByRole("option", "extracted-deck.txt", { exact: false }).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  await expect.poll(editorText).toContain("ALPHA first slide text");
  await app.screenshot("extracted-slides-and-notes");
  await expect.poll(editorText).toContain("BRAVO second slide text");
  await expect.poll(editorText).toContain("BRAVO speaker notes");
});
