/// <reference lib="dom" />
import { readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import JSZip from "jszip";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

async function fixture(padded: boolean) {
  const cell = (text: string, attrs = "") => `<a:tc ${attrs}><a:txBody><a:p><a:r><a:t>${text}</a:t></a:r></a:p></a:txBody></a:tc>`;
  const 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:graphicFrame><a:graphic><a:graphicData><a:tbl><a:tblGrid><a:gridCol/><a:gridCol/><a:gridCol/></a:tblGrid><a:tr>${cell("Route", 'gridSpan="2"')}${cell("Old spare", `hMerge="${padded ? " true " : "1"}"`)}${cell("Status")}</a:tr><a:tr>${cell("North", 'rowSpan="2"')}${cell("Gate A")}${cell("Open")}</a:tr><a:tr>${cell("Old north", `vMerge="${padded ? " 1 " : "1"}"`)}${cell("Gate B")}${cell("Closed")}</a:tr></a:tbl></a:graphicData></a:graphic></p:graphicFrame></p:spTree></p:cSld></p:sld>`;
  return new JSZip()
    .file("ppt/presentation.xml", '<presentation><sldIdLst><sldId r:id="a"/></sldIdLst></presentation>')
    .file("ppt/_rels/presentation.xml.rels", '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>')
    .file("ppt/slides/a.xml", xml).generateAsync({ type: "uint8array" });
}
async function extractedFiles(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  return (await Promise.all(entries.map(async entry => entry.isDirectory() ? extractedFiles(join(dir, entry.name)) : entry.name.endsWith(".pptx.txt") ? [join(dir, entry.name)] : []))).flat();
}

test("Padded PowerPoint merge flags keep covered cells empty on upload", WEB, async ({ t3, app, browser, screen }) => {
  const control = await fixture(false);
  const padded = await fixture(true);
  const project = await t3.project("table-review", { "extracted-tables.txt": "Waiting for upload" });
  const thread = await t3.thread({ project, title: "PowerPoint table extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.evaluate((files) => {
    const input = document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("Attachment input missing");
    const data = new DataTransfer();
    for (const file of files) data.items.add(new File([new Uint8Array(file.bytes)], file.name, { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, [{name: "control.pptx", bytes: Array.from(control)}, {name: "padded.pptx", bytes: Array.from(padded)}]);
  await screen.getByRole("button", "File attachment, control.pptx", { exact: false }).waitFor();
  await screen.getByRole("button", "File attachment, padded.pptx", { exact: false }).waitFor();
  let paths: string[] = [];
  await expect.poll(async () => { paths = await extractedFiles(T3_HOME); return paths.length; }).toBe(2);
  const texts = await Promise.all(paths.map(path => readFile(path, "utf8")));
  // Identify the control by its original uploaded bytes, not by the extraction result.
  const originals = await Promise.all(paths.map(path => readFile(path.slice(0, -4))));
  const controlIndex = originals.findIndex(bytes => Buffer.from(bytes).equals(Buffer.from(control)));
  const controlText = texts[controlIndex];
  const paddedText = texts[1 - controlIndex];
  await writeFile(join(project, "extracted-tables.txt"), `REAL SERVER UPLOAD EXTRACTION\n\nControl: hMerge="1", vMerge="1"\n${controlText}\n\nPadded: hMerge=" true ", vMerge=" 1 "\n${paddedText}\n\nCovered cells should be empty in both tables.\nTabs preserve the three table columns.\n`);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-tables.txt");
  await screen.getByRole("option", "extracted-tables.txt", { exact: false }).tap();
  await screen.getByText("REAL SERVER UPLOAD EXTRACTION", { exact: false }).waitFor();
  await app.screenshot("extracted-tables");
  expect(controlText).toContain("Route\t\tStatus\nNorth\tGate A\tOpen\n\tGate B\tClosed");
  expect(paddedText).toContain("Route\t\tStatus\nNorth\tGate A\tOpen\n\tGate B\tClosed");
});
