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

test("DOCX attachment omits covered vertical merge text and keeps columns", WEB, async ({t3,app,browser,screen}) => {
  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><w:tcPr><w:tcW w:w="4500" w:type="dxa"/>${merge}</w:tcPr>${p(text)}</w:tc>`;
  const bytes = await 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"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+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/document.xml", `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${p("Visitor instructions")}<w:tbl><w:tblGrid><w:gridCol w:w="4500"/><w:gridCol w:w="4500"/></w:tblGrid><w:tr>${cell("Entrance: use the north entrance.",'<w:vMerge w:val="restart"/>')}${cell("Arrive by 9am.")}</w:tr><w:tr>${cell("Old advice: use the west entrance.","<w:vMerge/>")}${cell("Bring your badge.")}</w:tr></w:tbl>${p("End of instructions")}</w:body></w:document>`)
    .generateAsync({type:"uint8array"});
  const project = await t3.project("visitor-demo");
  const thread = await t3.thread({project,title:"Visitor attachment extraction",messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("first fixture turn complete").waitFor();
  await screen.getByRole("textbox").fill("Read the extracted text of the attached document and quote it verbatim inside a code block. Do not add anything else.");
  await browser.evaluate((data) => {
    const file = new File([new Uint8Array(data)],"visitor-merge.docx",{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
    const clipboardData = new DataTransfer(); clipboardData.items.add(file);
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData,bubbles:true,cancelable:true}));
  },Array.from(bytes));
  await screen.getByRole("button", "Submit message", {exact:true}).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  const files = await readdir(T3_HOME,{recursive:true});
  const sidecar = files.find(f => f.endsWith(".docx.txt"));
  if (!sidecar) throw new Error("No DOCX extracted-text sidecar after attachment turn");
  const text = await readFile(join(T3_HOME,sidecar),"utf8");
  await writeFile(join(project,"attachment-extracted-text.txt"),text);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("attachment-extracted-text.txt");
  await screen.getByRole("option","attachment-extracted-text.txt",{exact:false}).tap();
  await screen.getByText("Entrance: use the north entrance.",{exact:false}).first().waitFor();
  await app.screenshot("docx-attachment-extracted-text");
  expect(text.trim()).toBe("Visitor instructions\nEntrance: use the north entrance.\tArrive by 9am.\n\tBring your badge.\nEnd of instructions");
});
