/// <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 rel = '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"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/></Types>');
  zip.file('_rels/.rels', `<Relationships><Relationship Id="main" Type="${rel}/officeDocument" Target="ppt/presentation.xml"/></Relationships>`);
  zip.file('ppt/presentation.xml', `<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="${rel}"><p:sldIdLst><p:sldId id="256" r:id="s1"/><p:sldId id="257" r:id="s2"/></p:sldIdLst></p:presentation>`);
  zip.file('ppt/_rels/presentation.xml.rels', `<Relationships><Relationship Id="s1" Type="${rel}/slide" Target="slides/slide1.xml"/><Relationship Id="s2" Type="${rel}/slide" Target="slides/slide2.xml"/></Relationships>`);
  const text = (kind: string, value: string) => `<p:${kind} 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>${value}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:${kind}>`;
  for (const n of [1, 2]) {
    zip.file(`ppt/slides/slide${n}.xml`, text('sld', n === 1 ? 'Dot segment slide' : 'Control slide'));
    zip.file(`ppt/notesSlides/notesSlide${n}.xml`, text('notes', n === 1 ? 'Secret note PELICAN-42' : 'Control note HERON-17'));
    zip.file(`ppt/slides/_rels/slide${n}.xml.rels`, `<Relationships><Relationship Id="notes" Type="${rel}/notesSlide" Target="${n === 1 ? '/ppt/slides/../notesSlides/notesSlide1.xml' : '../notesSlides/notesSlide2.xml'}"/></Relationships>`);
  }
  return zip.generateAsync({ type: 'base64' });
}
async function sidecars(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  const nested = await Promise.all(entries.map(e => e.isDirectory() ? sidecars(join(dir, e.name)) : Promise.resolve(e.name.endsWith('.pptx.txt') ? [join(dir, e.name)] : [])));
  return nested.flat();
}

test('An attached PPTX resolves speaker notes through package-root dot segments', WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project('Speaker notes proof');
  const thread = await t3.thread({ project, title: 'PPTX notes extraction', messages: ['Start'] });
  await t3.open(thread);
  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 data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(bytes), c => c.charCodeAt(0))], 'notes-dot-segments.pptx', { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }));
    picker.files = data.files;
    picker.dispatchEvent(new Event('change', { bubbles: true }));
  }, { input, bytes: await deck() });
  await screen.getByRole('button', 'File attachment, notes-dot-segments.pptx', { exact: false }).waitFor();
  await browser.keyboard.type('Read the extracted text of the attached PPTX. Quote verbatim every line of the extracted text file, including any speaker notes and any [Skipped ...] lines.');
  await screen.getByRole('textbox').press('Enter');
  await screen.getByRole('button', 'Stop generation').waitFor({ state: 'hidden' });
  // Inspect the real server's sidecar rather than asking a fixed replay response to quote it.
  const paths = await sidecars(T3_HOME);
  if (!paths.length) throw new Error('Attachment extraction produced no PPTX sidecar');
  const extracted = await readFile(paths[0]!, 'utf8');
  await writeFile(join(project, 'extracted-speaker-notes.txt'), extracted);
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('extracted-speaker-notes.txt');
  await screen.getByRole('option', 'extracted-speaker-notes.txt', { exact: false }).tap();
  await screen.getByText('Control note HERON-17', { exact: false }).waitFor();
  await app.screenshot('extracted-speaker-notes');
  await expect(extracted).toContain('Secret note PELICAN-42');
});
