/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { readFile, readdir, copyFile } 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 zip = new JSZip();
  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"/><Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+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 xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst></p:presentation>');
  zip.file("ppt/_rels/presentation.xml.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>');
  zip.file("ppt/slides/slide1.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:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/><p:sp><p:nvSpPr><p:cNvPr id="2" name="TextBox 1"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>Doors open at nine.</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld><p:timing><p:tnLst><p:par><p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst><p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst><p:par><p:cTn id="3" fill="hold"><p:childTnLst><p:par><p:cTn id="4" presetID="1" presetClass="entr" presetSubtype="0" fill="hold" nodeType="clickEffect"><p:childTnLst><p:set><p:cBhvr><p:cTn id="5" dur="1" fill="hold"/><p:tgtEl><p:spTgt spid="2"/></p:tgtEl><p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst></p:cBhvr><p:to><p:strVal val="visible"/></p:to></p:set></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn></p:seq></p:childTnLst></p:cTn></p:par></p:tnLst><p:bldLst><p:bldP spid="2" grpId="0"/></p:bldLst></p:timing></p:sld>`);
  return zip.generateAsync({ type: "uint8array" });
}

async function sidecars(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  return (await Promise.all(entries.map(async entry => entry.isDirectory() ? sidecars(join(dir, entry.name)) : entry.name.endsWith(".pptx.txt") ? [join(dir, entry.name)] : []))).flat();
}

test("PowerPoint attachment text excludes animation metadata", WEB, async ({ t3, app, screen, browser }) => {
  const bytes = await presentation();
  const project = await t3.project("presentation-proof", { "doors.pptx": bytes, "doors-extracted.txt": "Waiting for upload\n" });
  const thread = await t3.thread({ project, title: "PowerPoint attachment extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Quote the extracted text of doors.pptx.");
  await browser.evaluate((data: number[]) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("Attachment file input missing");
    const transfer = new DataTransfer();
    transfer.items.add(new File([new Uint8Array(data)], "doors.pptx", { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, Array.from(bytes));
  let extracted = "";
  await expect.poll(async () => {
    const paths = await sidecars(join(T3_HOME, "userdata"));
    if (paths.length !== 1) return false;
    extracted = await readFile(paths[0], "utf8");
    await copyFile(paths[0], join(project, "doors-extracted.txt"));
    return extracted.includes("Doors open at nine.");
  }).toBe(true);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("doors-extracted.txt");
  await screen.getByRole("option", "doors-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?.textContent?.includes("Doors open")) return content.textContent;
    }
    return "";
  })).toContain("Doors open at nine.");
  await app.screenshot("uploaded-presentation-extracted-text");
  expect(extracted).toBe("## Slide 1\nDoors open at nine.");
});
