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

async function budget() {
  const cell = (s: string) => `<w:tc><w:p><w:r><w:t>${s}</w:t></w:r></w:p></w:tc>`;
  const row = (values: string[], before = 0) => `<w:tr><w:trPr><w:gridBefore w:val="${before}"/></w:trPr>${values.map(cell).join("")}</w:tr>`;
  return new JSZip()
    .file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
    .file("word/document.xml", `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>Budget</w:t></w:r></w:p><w:tbl><w:tblGrid><w:gridCol/><w:gridCol/><w:gridCol/></w:tblGrid>${row(["Month","Cost","Note"])}${row(["January","400","paid"])}${row(["500"],1)}${row(["late fee"],2)}</w:tbl></w:body></w:document>`)
    .generateAsync({ type: "base64" });
}

test("DOCX extraction preserves skipped leading table columns", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Budget document extraction", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Print the extracted text of the attached document verbatim, run through cat -A so tabs show as ^I. Do not modify any files.");
  await browser.evaluate((base64) => {
    const data = new DataTransfer();
    data.items.add(new File([Uint8Array.from(atob(base64), c => c.charCodeAt(0))], "budget.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }));
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
  }, await budget());
  await screen.getByRole("textbox").press("Enter");
  let extracted = "";
  const find = async () => {
    for (const item of await readdir(join(T3_HOME, "userdata", "attachments"), { recursive: true })) {
      if (item.endsWith(".txt")) {
        const text = await readFile(join(T3_HOME, "userdata", "attachments", item), "utf8");
        if (text.includes("late fee")) { extracted = text; return true; }
      }
    }
    return false;
  };
  await expect.poll(find, { timeout: 60000 }).toBe(true);
  // Display the actual server sidecar using cat -A in the app's real terminal.
  await writeFile(join(project, "extracted.txt"), extracted);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const copy = async () => {
    await browser.evaluate(() => {
      window.addEventListener("copy", e => { document.body.dataset.copy = e.clipboardData?.getData("text/plain") ?? ""; }, { once: true });
    });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.copy ?? "");
  };
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("PS1='$ '; clear; cat -A extracted.txt; printf '\\nEXTRACTION COMPLETE\\n'");
    await browser.keyboard.press("Enter");
    return copy();
  }, { timeout: 30000 }).toContain("Budget$");
  await app.screenshot("budget-extracted-text");
  expect(extracted).toContain("\n\t500\n\t\tlate fee");
});
