/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { readdir, readFile, 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 fixture() {
  const p = (text: string) => `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`;
  const cell = (text: string, merge?: string) => `<w:tc>${merge ? `<w:tcPr><w:hMerge w:val="${merge}"/></w:tcPr>` : ""}${p(text)}</w:tc>`;
  const ns = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
  return new JSZip()
    .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="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/footnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"/></Types>')
    .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="word/document.xml"/></Relationships>')
    .file("word/_rels/document.xml.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes" Target="footnotes.xml"/></Relationships>')
    .file("word/document.xml", `<w:document ${ns}><w:body>${p("Routes")}<w:tbl><w:tr>${cell("Route", "restart")}${cell("Old route", "continue")}${cell("Status")}</w:tr><w:tr>${cell("A12")}${cell("North")}${cell("Open")}</w:tr></w:tbl><w:p><w:r><w:t>Seal check</w:t><w:footnoteReference w:id="1"/></w:r></w:p></w:body></w:document>`)
    .file("word/footnotes.xml", `<w:footnotes ${ns}><w:footnote w:id="1">${p("Inspect the seals.")}<w:tbl><w:tr>${cell("Do not reopen.", "restart")}${cell("Old instruction", "continue")}</w:tr></w:tbl></w:footnote></w:footnotes>`)
    .generateAsync({ type: "uint8array", compression: "DEFLATE" });
}

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

test("Legacy Word covered cells are omitted from uploaded attachment text", WEB, async ({ t3, app, browser, screen }) => {
  const bytes = await fixture();
  const project = await t3.project("routes", { "legacy-merge-routes.docx": bytes });
  const thread = await t3.thread({ project, title: "Inspect uploaded route document", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").tap();
  await browser.evaluate((data) => {
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([new Uint8Array(data)], "legacy-merge-routes.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
    return null;
  }, Array.from(bytes));
  await screen.getByRole("button", "File attachment, legacy-merge-routes.docx", { exact: false }).waitFor();
  // The upload handler publishes this sidecar before acknowledging the upload. Read its actual
  // output and show a verbatim copy in the app's text viewer; no model interprets the document.
  let extracted = "";
  await expect.poll(async () => {
    const files = await sidecars(join(T3_HOME, "userdata", "attachments"));
    if (!files[0]) return false;
    extracted = await readFile(files[0], "utf8");
    await copyFile(files[0], join(project, "server-extracted-attachment.txt"));
    return true;
  }, { timeout: 30000 }).toBe(true);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("server-extracted-attachment.txt");
  await screen.getByRole("option", "server-extracted-attachment.txt", { exact: false }).tap();
  await screen.getByText("Inspect the seals.", { exact: false }).first().waitFor();
  await app.screenshot("server-extracted-attachment");
  await expect(extracted).toBe("Routes\nRoute\t\tStatus\nA12\tNorth\tOpen\nSeal check[Note: Inspect the seals.\nDo not reopen.]");
});
