/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
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 { rpcClient, runPromise, test, WEB } from "./t3.ts";

async function documents() {
  const makeOdt = (drawing: string) => new JSZip()
    .file("mimetype", "application/vnd.oasis.opendocument.text")
    .file("content.xml", `<?xml version="1.0"?><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" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"><office:body><office:text><text:p>Directions: ${drawing}“Turn left” at the pier.</text:p></office:text></office:body></office:document-content>`)
    .generateAsync({ type: "base64" });
  return [
    { name: "custom-shape.odt", type: "application/vnd.oasis.opendocument.text", data: await makeOdt('<draw:custom-shape text:anchor-type="as-char"><svg:desc>Dock map</svg:desc></draw:custom-shape>') },
    { name: "image-frame.odt", type: "application/vnd.oasis.opendocument.text", data: await makeOdt('<draw:frame text:anchor-type="as-char"><draw:image/><svg:desc>Dock map</svg:desc></draw:frame>') },
    { name: "image-alt.epub", type: "application/epub+zip", data: await new JSZip()
      .file("mimetype", "application/epub+zip")
      .file("META-INF/container.xml", '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>')
      .file("book.opf", '<package><manifest><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
      .file("chapter.xhtml", '<html><body><p>Directions: <img alt="Dock map"/>“Turn left” at the pier.</p></body></html>')
      .generateAsync({ type: "base64" }) },
  ];
}

async function sidecars() {
  const root = join(T3_HOME, "userdata");
  const paths = await readdir(root, { recursive: true });
  const found: string[] = [];
  for (const path of paths.filter(p => /\.(odt|epub)\.txt$/.test(p)).sort()) {
    found.push(await readFile(join(root, path), "utf8"));
  }
  return found;
}

test("Uploaded drawing descriptions keep the separator before an opening quotation", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("document-proof");
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.devReplay.config.customModels = ["multi-turn"];
  await writeFile(settingsPath, JSON.stringify(settings));
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["server.refreshProviders"]({ fresh: true, refreshModels: true, cwd: project });
  })));
  const thread = await t3.thread({ project, title: "Document extraction proof", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("textbox").fill("Inspect the attached documents.");
  await browser.evaluate((files) => {
    const transfer = new DataTransfer();
    for (const file of files) transfer.items.add(new File([Uint8Array.from(atob(file.data), c => c.charCodeAt(0))], file.name, { type: file.type }));
    const input = document.querySelector('input[type="file"][multiple]') as HTMLInputElement;
    if (!input) throw new Error("Attachment file input missing");
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  }, await documents());
  await screen.getByText("custom-shape.odt", { exact: false }).waitFor();
  await browser.keyboard.press("Enter");
  // Read only the real server's generated sidecars; the report preserves their text verbatim.
  let texts: string[] = [];
  await expect.poll(async () => { texts = await sidecars(); return texts.length; }, { timeout: 120_000 }).toBe(3);
  await writeFile(join(project, "extraction-report.txt"), "ATTACHMENT TEXT — exact server sidecar contents\n\n" + texts.map((text, i) => `Document ${i + 1}\n${text}`).join("\n\n"));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extraction-report.txt");
  await screen.getByRole("option", "extraction-report.txt", { exact: false }).tap();
  const shown = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  await expect.poll(shown).toContain("Dock map");
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("extracted-attachment-text");
  for (const text of texts) expect(text).toContain('Dock map “Turn left” at the pier.');
});
