/// <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 documentBytes(extension: string) {
  const zip = new JSZip();
  const kind = extension === "ods" ? "spreadsheet" : extension === "odt" ? "text" : "presentation";
  zip.file("mimetype", `application/vnd.oasis.opendocument.${kind}`);
  const table = `<table:table table:name="Budget"><table:table-row><table:table-cell><text:p>Region</text:p></table:table-cell><table:table-cell><text:p>Q1</text:p></table:table-cell><table:table-cell><text:p>Q2</text:p></table:table-cell><table:table-cell><text:p>Total</text:p></table:table-cell></table:table-row><table:table-row><table:table-cell table:number-columns-spanned="3"><text:p>North (merged)</text:p></table:table-cell><table:covered-table-cell office:value-type="float" office:value="777001"/><table:covered-table-cell><text:p>HIDDEN-SECRET-Q2</text:p></table:covered-table-cell><table:table-cell office:value-type="float" office:value="15"/><table:table-cell table:number-columns-repeated="4"/></table:table-row><table:table-row table:number-rows-repeated="3"><table:table-cell/></table:table-row></table:table>`;
  const body = kind === "presentation" ? `<draw:page draw:name="Budget">${table}</draw:page>` : table;
  zip.file("content.xml", `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"><office:body><office:${kind}>${body}</office:${kind}></office:body></office:document-content>`);
  return zip.generateAsync({ type: "base64" });
}

test("OpenDocument attachment text keeps covered positions blank", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("budget-review");
  const thread = await t3.thread({ project, title: "Merged budget attachments", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill('Read only the extracted .txt supplied for the attached spreadsheets. Transcribe every row, showing tabs as " | ".');
  const files = await Promise.all(["ods", "odt", "odp"].map(async extension => ({ extension, base64: await documentBytes(extension) })));
  await browser.evaluate((files) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("No attachment file input");
    const transfer = new DataTransfer();
    for (const {extension, base64} of files) transfer.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], `merged-budget.${extension}`, {type: `application/vnd.oasis.opendocument.${extension === "ods" ? "spreadsheet" : extension === "odt" ? "text" : "presentation"}`}));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", {bubbles: true}));
    return null;
  }, files);
  await screen.getByRole("button", /Submit message|Send message/, { exact: true }).tap();
  await screen.getByRole("textbox").waitFor();
  const dir = join(T3_HOME, "userdata", "attachments");
  let texts: string[] = [];
  let extensions: string[] = [];
  await expect.poll(async () => {
    const names = (await readdir(dir)).filter(n => n.endsWith(".txt") && !n.startsWith("pending-"));
    names.sort();
    extensions = names.map(n => n.split(".").at(-2)!.toUpperCase());
    texts = await Promise.all(names.map(n => readFile(join(dir,n), "utf8")));
    return texts.length;
  }).toBe(3);
  const display = texts.map((text, i) => `SERVER ATTACHMENT TEXT ${i+1} (${extensions[i]})\n${text.replaceAll("\t", " | ")}`).join("\n\n");
  await writeFile(join(project,"attachment-text.txt"), display);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("attachment-text.txt");
  await screen.getByRole("option", "attachment-text.txt", {exact: false}).tap();
  await browser.locator('[data-active-tab="true"]').getByText("attachment-text.txt", {exact: true}).waitFor();
  await screen.getByText("SERVER ATTACHMENT TEXT 1", {exact: false}).waitFor();
  await screen.getByRole("button", "Maximize panel", {exact: true}).tap();
  await app.screenshot("server-extracted-attachment-text");
  for (const text of texts) {
    expect(text).not.toContain("777001");
    expect(text).not.toContain("HIDDEN-SECRET-Q2");
    expect(text).toContain("North (merged)\t\t\t15");
    expect(text.endsWith("15")).toBe(true);
  }
});
