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

async function sidecars(dir: string): Promise<string[]> {
  const found: string[] = [];
  for (const item of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, item.name);
    if (item.isDirectory()) found.push(...await sidecars(path));
    else if (/\.(docx|odt)\.txt$/.test(path)) found.push(path);
  }
  return found;
}

test("Leading empty table cells survive attachment extraction", WEB, async ({t3, app, browser, screen}) => {
  const docx = await new JSZip().file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml"/></Types>').file("word/document.xml", '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>\n\t<w:tbl><w:tr><w:tc><w:p/></w:tc><w:tc><w:p><w:r><w:t>USD</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t>Revenue</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>900</w:t></w:r></w:p></w:tc></w:tr></w:tbl>\n</w:body></w:document>').generateAsync({type:"uint8array"});
  const odt = await new JSZip().file("mimetype", "application/vnd.oasis.opendocument.text").file("content.xml", '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:text>\n\t<table:table><table:table-row><table:table-cell><text:p/></table:table-cell><table:table-cell><text:p>USD</text:p></table:table-cell></table:table-row><table:table-row><table:table-cell><text:p>Revenue</text:p></table:table-cell><table:table-cell><text:p>900</text:p></table:table-cell></table:table-row></table:table>\n</office:text></office:body></office:document-content>').generateAsync({type:"uint8array"});
  const project = await t3.project("demo");
  const thread = await t3.thread({project, title:"Leading table extraction", messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("textbox").fill("Read both attached tables. Verify the empty first column before USD.");
  await browser.evaluate((files) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("No attachment input");
    const data = new DataTransfer();
    for (const f of files) data.items.add(new File([new Uint8Array(f.bytes)], f.name, {type:f.type}));
    input.files = data.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  }, [{name:"table.docx", bytes:Array.from(docx),type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {name:"table.odt",bytes:Array.from(odt),type:"application/vnd.oasis.opendocument.text"}]);
  await screen.getByRole("button", "File attachment, table.docx", {exact:false}).waitFor();
  await screen.getByRole("button", "File attachment, table.odt", {exact:false}).waitFor();
  await screen.getByRole("textbox").press("Enter");
  // Upload and claim each use the real server extraction service. Read only its persisted output.
  let paths: string[] = [];
  await expect.poll(async () => { paths = await sidecars(join(T3_HOME,"userdata")); return paths.length; }, {timeout:60000}).toBeGreaterThanOrEqual(2);
  const values = await Promise.all(paths.map(p => readFile(p,"utf8")));
  const report = paths.map((p,i) => `${p.endsWith(".docx.txt") ? "DOCX" : "ODT"}: ${JSON.stringify(values[i])}`).filter((v,i,a)=>a.indexOf(v)===i).sort().join("\n");
  await writeFile(join(project,"extraction.txt"), "Actual server-generated sidecars (JSON escapes show tabs):\n" + report + "\nExpected for both: \"\\tUSD\\nRevenue\\t900\"\n");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("PS1='' PS2=''; printf '\\033[2J\\033[H'; cat extraction.txt; touch shown\n");
    return readFile(join(project,"shown"),"utf8").then(()=>true,()=>false);
  },{timeout:30000}).toBe(true);
  await app.screenshot("leading-table-sidecars");
  expect(values.every(value => value === "\tUSD\nRevenue\t900")).toBe(true);
});
