/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { readFile, readdir, 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 p = 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
  zip.file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/></Types>');
  zip.file("_rels/.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/></Relationships>');
  zip.file("ppt/presentation.xml", `<p:presentation ${p} xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main"><p:sldIdLst><p:sldId id="256" r:id="rId1"/><p:sldId id="257" r:id="rId2"/></p:sldIdLst><p:extLst><p:ext uri="{521415D9-36F7-43E2-AB2F-B90AF26B5E84}"><p14:sectionLst><p14:section name="Trip" id="{BB587EDD-AB10-4127-9436-3F093CCBD14F}"><p14:sldIdLst><p14:sldId id="256"/><p14:sldId id="257"/></p14:sldIdLst></p14:section></p14:sectionLst></p:ext></p:extLst></p:presentation>`);
  zip.file("ppt/_rels/presentation.xml.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Target="slides/slide1.xml"/><Relationship Id="rId2" Target="slides/slide2.xml"/></Relationships>');
  for (const [i, title, notes] of [[1,"Packing list for Lisbon","Remember the adapter"],[2,"Departure at 07:40","Board at gate 4"]] as const) {
    zip.file(`ppt/slides/slide${i}.xml`, `<p:sld ${p}><p:cSld><p:spTree><p:sp><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>${title}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>`);
    zip.file(`ppt/slides/_rels/slide${i}.xml.rels`, `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="notes" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notes${i}.xml"/></Relationships>`);
    zip.file(`ppt/notesSlides/notes${i}.xml`, `<p:notes ${p}><p:cSld><p:spTree><p:sp><p:txBody><a:p><a:r><a:t>${notes}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:notes>`);
  }
  return zip.generateAsync({ type: "nodebuffer" });
}

test("Sectioned PowerPoint upload extracts only the two actual slides", WEB, async ({ t3, app, screen, browser }) => {
  const pptx = await deck();
  const project = await t3.project("Trip", { "trip-sections.pptx": pptx });
  const thread = await t3.thread({ project, title: "PowerPoint attachment extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Read the extracted text of the attached PowerPoint and list every slide heading it contains and every extraction notice, verbatim.");
  const uploaded = browser.waitForResponse(/\/api\/attachments\/upload\//);
  await browser.evaluate((base64) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
    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))], "trip-sections.pptx", { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, pptx.toString("base64"));
  const response = await uploaded;
  await response.body();
  // Read the real upload sidecar; no extractor invocation or synthetic agent answer.
  const root = join(T3_HOME, "userdata");
  const files = await readdir(root, { recursive: true });
  const sidecar = files.find(f => f.includes("attachments/") && f.endsWith(".pptx.txt"));
  if (!sidecar) throw new Error("Upload did not produce its extracted-text sidecar");
  const extracted = await readFile(join(root, sidecar), "utf8");
  await writeFile(join(project, "trip-sections.extracted.txt"), extracted);
  await screen.getByRole("textbox").fill("Read the extracted text of the attached PowerPoint and list every slide heading it contains and every extraction notice, verbatim.");
  await screen.getByRole("textbox").press("Enter");
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("trip-sections.extracted.txt");
  await screen.getByRole("option", "trip-sections.extracted.txt", { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("Board at gate 4");
  // Capture the server's verbatim extraction in the real app file viewer.
  await app.screenshot("extracted-slide-text");
  await expect(extracted).toBe("## Slide 1\nPacking list for Lisbon\nNotes:\nRemember the adapter\n\n## Slide 2\nDeparture at 07:40\nNotes:\nBoard at gate 4");
});
