import { expect } from "e2e";
import JSZip from "jszip";
import { readFile, readdir, copyFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("ODF agent sidecars collapse ordinary inline paragraph whitespace", WEB, async ({ t3, app, screen, browser }) => {
  const odt = await new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("content.xml", `<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" office:version="1.3"><office:body><office:text><text:p>Invoice<text:span>\n\t  number</text:span>   AB-42</text:p><text:p>Second paragraph</text:p></office:text></office:body></office:document-content>`)
    .generateAsync({ type: "uint8array" });
  const project = await t3.project("odf-demo", { "invoice.odt": odt });
  const thread = await t3.thread({ project, title: "Inspect ODF sidecar", messages: ["Start"] });
  await t3.open(thread);
  await browser.locator('input[type="file"]').setInputFiles([join(project, "invoice.odt")]);
  await screen.getByRole("textbox").fill("Inspect the attached invoice.");
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete").waitFor({ state: "visible", timeout: 120000 });
  const files = await readdir(join(T3_HOME, "userdata", "attachments"), { recursive: true });
  const name = files.find((name) => name.endsWith(".odt.txt"));
  if (!name) throw new Error(`No generated ODT sidecar: ${files.join(", ")}`);
  const source = join(T3_HOME, "userdata", "attachments", name);
  const content = await readFile(source, "utf8");
  await copyFile(source, join(project, "invoice.odt.txt"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("invoice.odt.txt");
  await screen.getByRole("option", "invoice.odt.txt", { exact: false }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  })).toContain("Second paragraph");
  await app.screenshot("generated-agent-sidecar");
  expect(content).toBe("Invoice number AB-42\nSecond paragraph");
});
