/// <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 extraction omits paragraph-style-hidden text and keeps explicit visibility", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip();
  zip.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/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>`);
  zip.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>`);
  zip.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/styles" Target="styles.xml"/></Relationships>`);
  zip.file("word/styles.xml", `<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Retired"><w:basedOn w:val="Normal"/><w:rPr><w:vanish/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="RetiredChild"><w:basedOn w:val="Retired"/></w:style><w:style w:type="character" w:styleId="Emphasis"><w:rPr><w:i/></w:rPr></w:style></w:styles>`);
  zip.file("word/document.xml", `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:pPr><w:pStyle w:val="Retired"/></w:pPr><w:r><w:t>Old routing</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="RetiredChild"/></w:pPr><w:r><w:rPr><w:rStyle w:val="Emphasis"/></w:rPr><w:t>Old badge rules</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Retired"/></w:pPr><w:r><w:rPr><w:vanish w:val="0"/></w:rPr><w:t>Visible run override</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Normal"/></w:pPr><w:r><w:t>Current instructions</w:t></w:r></w:p></w:body></w:document>`);
  const bytes = await zip.generateAsync({type:"base64"});
  const project = await t3.project("handbook-review");
  const thread = await t3.thread({project, title:"Handbook extraction", messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("textbox").fill("Quote the extracted text of the attached handbook exactly, line by line, in a code block. Do not open the .docx itself; read only the extracted text file.");
  await browser.evaluate((payload) => {
    const clipboardData = new DataTransfer();
    clipboardData.items.add(new File([Uint8Array.from(atob(payload), c => c.charCodeAt(0))], "support-handbook.docx", {type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}));
    document.querySelector('[contenteditable="true"]')?.dispatchEvent(new ClipboardEvent("paste", {clipboardData, bubbles:true, cancelable:true}));
    return null;
  }, bytes);
  await screen.getByRole("button", "File attachment, support-handbook.docx", {exact:false}).waitFor();
  await screen.getByRole("button", "Submit message", {exact:true}).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  const attachments = join(T3_HOME, "userdata", "attachments");
  let extracted = "";
  await expect.poll(async () => {
    const files = await readdir(attachments, {recursive:true});
    const file = files.find(f => f.endsWith(".docx.txt"));
    if (!file) return false;
    extracted = await readFile(join(attachments,file), "utf8");
    return true;
  }).toBe(true);
  // Display an unchanged copy of the server's sidecar in the real file viewer.
  await writeFile(join(project,"support-handbook.extracted.txt"), extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("support-handbook.extracted.txt");
  await screen.getByRole("option", "support-handbook.extracted.txt", {exact:false}).tap();
  await screen.getByText("Visible run override", {exact:false}).waitFor();
  await app.screenshot("handbook-extracted-text");
  await expect(extracted.trim()).toBe("Visible run override\nCurrent instructions");
});
