import { expect } from "e2e";
import { readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const samples = [
  { name: "hidden.rtf", source: String.raw`{\rtf1\ansi Visible {\v HIDDEN-NOTE} end.\par}`, expected: "Visible  end." },
  { name: "hidden2.rtf", source: String.raw`{\rtf1\ansi A {\v B{\v0 C}D} E\v F\v0  G\v1 H\plain  I}`, expected: "A C E G I" },
  { name: "table.rtf", source: String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\v B\u945?\'e9\cell\v0 C\cell\v\row\v0 D\cell}`, expected: "A\tC\t\nD" },
];
async function sidecars(dir: string): Promise<string[]> {
  const result: string[] = [];
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    if (entry.isDirectory()) result.push(...await sidecars(join(dir, entry.name)));
    else if (entry.name.endsWith(".rtf.txt")) result.push(join(dir, entry.name));
  }
  return result;
}

test("RTF upload omits hidden text from agent sidecars and preserves table separators", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("RTF-attachment-proof", Object.fromEntries(samples.map(s => [s.name, s.source])));
  const thread = await t3.thread({ project, title: "RTF hidden text proof", messages: ["Ready for attachment verification"] });
  await t3.open(thread);
  const outputs: string[] = [];
  const seen = new Set<string>();
  for (const sample of samples) {
    await browser.locator('input[type="file"]').setInputFiles(join(project, sample.name));
    let added: string | undefined;
    await expect.poll(async () => {
      const files = await sidecars(T3_HOME);
      added = files.find(file => !seen.has(file));
      return added !== undefined;
    }).toBe(true);
    seen.add(added!);
    outputs.push(await readFile(added!, "utf8"));
  }
  const report = samples.map((sample, i) => `${sample.name}\n  Agent sidecar: ${JSON.stringify(outputs[i])}\n  Expected:      ${JSON.stringify(sample.expected)}`).join("\n\n");
  await writeFile(join(project, "agent-sidecars.txt"), "REAL SERVER RTF UPLOAD: EXTRACTED AGENT TEXT\n\n" + report + "\n");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await input.focus();
  await browser.keyboard.type("export PS1='$ '; clear; cat agent-sidecars.txt\n");
  await app.screenshot("agent-extracted-rtf-text");
  expect(outputs).toEqual(samples.map(s => s.expected));
});
