/// <reference lib="dom" />
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const FILES = [
  {name: "libreoffice-footnote.rtf", body: String.raw`{\rtf1\ansi The north region{\super\chftn{\*\footnote\chftn\pard\plain Hold the obsolete value apart.\par Verify the seals.}} is ready.{\v HIDDEN SENTINEL}{\*\unknown Hidden destination.}}`},
  {name: "word-footnote.rtf", body: String.raw`{\rtf1\ansi The north region{\super \chftn}{\footnote \pard\plain {\super \chftn} Hold the obsolete value apart.\par Verify the seals.} is ready.{\v HIDDEN SENTINEL}{\*\unknown Hidden destination.}}`},
];
const walk = (dir: string): string[] => readdirSync(dir, {withFileTypes:true}).flatMap(e => e.isDirectory() ? walk(join(dir,e.name)) : [join(dir,e.name)]);

test("Fresh RTF attachment sidecars preserve visible footnotes and suppress hidden text", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("attachment-proof", {"extraction-report.md":"Pending extraction"});
  const thread = await t3.thread({project, title:"RTF attachment extraction", messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await browser.evaluate((files) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]');
    if (!input) throw new Error("Attachment picker missing");
    const data = new DataTransfer();
    for (const f of files) data.items.add(new File([f.body], f.name, {type:"application/rtf"}));
    input.files = data.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  }, FILES);
  await expect.poll(() => walk(T3_HOME).filter(p => p.endsWith('.rtf.txt')).length).toBe(2);
  await app.screenshot("fresh-rtf-attachments");
  const outputs = FILES.map(f => {
    const source = walk(T3_HOME).find(p => p.endsWith('.rtf') && readFileSync(p,'utf8') === f.body);
    if (!source) throw new Error(`No fresh upload for ${f.name}`);
    return {name:f.name, text:readFileSync(source+'.txt','utf8')};
  });
  writeFileSync(join(project,"extraction-report.md"), "# Fresh attachment extraction\n\nActual .txt sidecars written by the running server.\n\n" + outputs.map(o => `## ${o.name}\n\n\`\`\`text\n${o.text}\n\`\`\`\n`).join('\n'));
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("extraction-report.md");
  await screen.getByRole("option", "extraction-report.md", {exact:false}).tap();
  await screen.getByText("Actual .txt sidecars written by the running server.").waitFor();
  await app.screenshot("extracted-footnote-text");
  for (const output of outputs) {
    expect(output.text).toBe("The north region[Note: Hold the obsolete value apart.\nVerify the seals.] is ready.");
  }
});
