/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { readdir, readFile, writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

async function odt() {
  const box = (text: string) => `<draw:frame text:anchor-type="as-char"><draw:text-box>${text}</draw:text-box></draw:frame>`;
  return new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text", { compression: "STORE" })
    .file("META-INF/manifest.xml", '<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.text"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>')
    .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" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" office:version="1.3"><office:body><office:text><text:p>Inspection route</text:p><text:p>${box('<text:p>North loading dock</text:p><text:p>South loading dock</text:p>')}</text:p><text:p>Meeting point: ${box('<text:p>Gate 4</text:p>')} at noon</text:p></office:text></office:body></office:document-content>`)
    .generateAsync({ type: "base64" });
}

test("ODT attachment extraction preserves text-box paragraphs and inline control", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("inspection");
  const thread = await t3.thread({ project, title: "Inspection route attachment", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("Read the attached inspection route.");
  await browser.evaluate((base64: string) => {
    const input = document.querySelector('form[data-chat-composer-form] input[type="file"]') as HTMLInputElement;
    if (!input) throw new Error("Attachment file input missing");
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "dock-route.odt", { type: "application/vnd.oasis.opendocument.text" }));
    input.files = data.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, await odt());
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  const files = await readdir(T3_HOME, { recursive: true });
  const sidecar = files.find(f => f.endsWith(".odt.txt"));
  if (!sidecar) throw new Error("Server did not create the extracted ODT sidecar");
  const extracted = await readFile(`${T3_HOME}/${sidecar}`, "utf8");
  // Show the actual server-produced bytes through the app's file viewer, without a model paraphrase.
  await writeFile(`${project}/extracted-route.txt`, extracted);
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extracted-route.txt");
  await screen.getByRole("option", "extracted-route.txt", { exact: false }).tap();
  await screen.getByText("North loading dock", { exact: false }).waitFor();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await screen.getByText("North loading dock", { exact: false }).waitFor();
  await app.screenshot("extracted-attachment-text");
  expect(extracted).toBe("Inspection route\nNorth loading dock\nSouth loading dock\nMeeting point: Gate 4 at noon");
});
