/// <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";

const comment = '<office:annotation><dc:creator>Jane Reviewer</dc:creator><dc:date>2026-11-17T10:00:00</dc:date><meta:creator-initials>JR</meta:creator-initials><text:p>Check</text:p></office:annotation>';
const wrap = (body: string) => `<?xml version="1.0"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML"><office:body>${body}</office:body></office:document-content>`;
const samples = [
 { name: "fee.odt", kind: "text", body: `<office:text><text:p>Fee ${comment}$700</text:p></office:text>` },
 { name: "budget.ods", kind: "spreadsheet", body: `<office:spreadsheet><table:table table:name="Sheet1"><table:table-row><table:table-cell><text:p>Total</text:p></table:table-cell><table:table-cell office:value-type="float" office:value="150">${comment.replace("Check", "was 120")}</table:table-cell></table:table-row></table:table></office:spreadsheet>` },
 { name: "slides.odp", kind: "presentation", body: `<office:presentation><draw:page draw:name="Slide1"><draw:frame><draw:text-box><text:p>Approved ${comment}plan</text:p></draw:text-box></draw:frame></draw:page></office:presentation>` },
 { name: "formula.odt", kind: "text", body: `<office:text><text:p>Formula <math:math><math:semantics><math:mrow>x+y</math:mrow><math:annotation encoding="application/x-tex">x+y</math:annotation></math:semantics></math:math></text:p></office:text>` },
];

test("ODF uploads exclude comments, retain cell values and preserve MathML", WEB, async ({ t3, app, screen, browser }) => {
 await browser.setViewport({ width: 1600, height: 1000 });
 await browser.addInitScript(() => localStorage.setItem("t3code.renderMarkdown", "true"));
 const files: Record<string, Uint8Array> = {};
 for (const sample of samples) {
  files[sample.name] = await new JSZip().file("mimetype", `application/vnd.oasis.opendocument.${sample.kind}`, { compression: "STORE" }).file("content.xml", wrap(sample.body)).generateAsync({ type: "uint8array" });
 }
 const project = await t3.project("documents", files);
 const thread = await t3.thread({ project, title: "ODF attachment extraction", messages: ["Review the attached documents."] });
 await t3.open(thread);
 const outputs: Record<string, string> = {};
 for (const sample of samples) {
  const uploaded = browser.waitForResponse("**/api/attachments/upload/**");
  await browser.locator('input[type="file"]').setInputFiles(join(project, sample.name));
  const response = await uploaded;
  if (response.status !== 204) throw new Error(`Upload failed: ${response.status}`);
 }
 const folder = join(T3_HOME, "userdata", "attachments");
 const entries = await readdir(folder, { recursive: true });
 for (const entry of entries) {
  if (!entry.endsWith(".txt")) continue;
  const text = await readFile(join(folder, entry), "utf8");
  if (text.startsWith("Formula")) outputs["formula.odt"] = text;
  else if (text.startsWith("Fee")) outputs["fee.odt"] = text;
  else if (text.includes("Sheet1")) outputs["budget.ods"] = text;
  else if (text.includes("Slide 1")) outputs["slides.odp"] = text;
 }
 if (Object.keys(outputs).length !== 4) throw new Error("Missing server-generated sidecar");
 const report = "# Server attachment extraction\n\nFresh uploads through the composer. Text below is copied verbatim from the server-generated .txt sidecars.\n\n" + samples.map(s => `## ${s.name}\n\n${outputs[s.name].split("\n").map(line => "`" + line + "`").join("  \n")}\n`).join("\n");
 await writeFile(join(project, "extraction-report.md"), report);
 await browser.keyboard.press("Control+p");
 await screen.getByPlaceholder("Search files…").fill("extraction-report.md");
 await screen.getByRole("option", "extraction-report.md", { exact: false }).tap();
 await screen.getByText("Server attachment extraction", { exact: false }).first().waitFor({ state: "visible" });
 await screen.getByRole("button", "Hide file explorer").tap();
 await screen.getByRole("button", "Maximize panel").tap();
 await screen.getByText(outputs["fee.odt"], { exact: true }).waitFor({ state: "visible" });
 await screen.getByText("Formula x+yx+y", { exact: true }).waitFor({ state: "visible" });
 await app.screenshot("server-extracted-text");
 expect(outputs).toEqual({ "fee.odt": "Fee $700", "budget.ods": "## Sheet: Sheet1\nTotal\t150", "slides.odp": "## Slide 1\nApproved plan", "formula.odt": "Formula x+yx+y" });
});
