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

const fixtureDir = process.env.XLSX_FIXTURE_DIR ?? process.cwd();

test("Fresh XLSX attachments decode carriage returns and preserve literal escapes", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Workbook evidence", { "extraction-results.txt": "Waiting for fresh uploads" });
  const thread = await t3.thread({ project, title: "XLSX attachment extraction", messages: ["Prepare to inspect workbook attachments"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Read the generated .xlsx.txt sidecars and quote the cell contents of both attached workbooks.");
  for (const name of ["shared-strings", "inline-strings"]) {
    const bytes = Array.from(await readFile(`${fixtureDir}/${name}.xlsx`));
    await browser.evaluate(({ bytes, name }) => {
      const data = new DataTransfer();
      data.items.add(new File([new Uint8Array(bytes)], `${name}.xlsx`, { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }));
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    }, { bytes, name });
  }
  await composer.press("Enter");
  const sidecars = async () => (await readdir(`${T3_HOME}/userdata/attachments`, { recursive: true })).filter(p => p.endsWith(".xlsx.txt"));
  await expect.poll(async () => (await sidecars()).length).toBe(2);
  const contents = await Promise.all((await sidecars()).sort().map(p => readFile(`${T3_HOME}/userdata/attachments/${p}`, "utf8")));
  await writeFile(`${project}/extraction-results.txt`, "ACTUAL SERVER-GENERATED XLSX SIDECARS\n\nInput cells (both workbooks):\nA1: first [carriage return] second\nA2: literal _x0041_\nA3: literal _x005F_x0041_\n\n" + contents.map((text, i) => `Workbook ${i + 1} — fresh extraction\n${text}`).join("\n\n"));
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="extraction-results.txt"]');
      if (row) { row.click(); return true; }
    }
    return false;
  })).toBe(true);
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  await expect.poll(editorText).toContain("ACTUAL SERVER-GENERATED");
  await app.screenshot("xlsx-sidecar-text");
  expect(contents.map(s => s.trim())).toEqual(["## Sheet: Escapes\nfirst second\n_x0041_\n_x005F_x0041_", "## Sheet: Escapes\nfirst second\n_x0041_\n_x005F_x0041_"]);
});
