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

async function filesBelow(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  return (await Promise.all(entries.map(e => e.isDirectory() ? filesBelow(join(dir, e.name)) : [join(dir, e.name)]))).flat();
}

test("Mac Roman RTF uploads retain readable extracted text for both headers", WEB, async ({ t3, app, browser }) => {
  const fixtures = {
    "mac.rtf": String.raw`{\rtf1\mac Caf\'8e Cr\'8fme}`,
    "mac-cp10000.rtf": String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`,
  };
  const project = await t3.project("RTF attachment proof", fixtures);
  const thread = await t3.thread({ project, title: "Mac Roman attachments", messages: [] });
  await t3.open(thread);
  const results: { name: string; header: string; text: string | null; bytes: string | null }[] = [];
  for (const [name, header] of Object.entries(fixtures)) {
    const before = new Set(await filesBelow(join(T3_HOME, "userdata")));
    await Promise.all([
      browser.waitForResponse(/\/api\/attachments\/upload\//),
      browser.locator('input[type="file"]').setInputFiles(join(project, name)),
    ]);
    const added = (await filesBelow(join(T3_HOME, "userdata"))).filter(p => !before.has(p) && p.endsWith(".rtf"));
    if (added.length !== 1) throw new Error(`Expected one newly stored RTF upload, got ${added.length}`);
    const text = await readFile(added[0] + ".txt", "utf8").catch(error => {
      if (error.code === "ENOENT") return null;
      throw error;
    });
    results.push({ name, header, text, bytes: text === null ? null : Buffer.from(text).toString("hex").match(/../g)!.join(" ") });
  }
  // The app has no extracted-text viewer. This labelled diagnostic reads the real upload sidecars;
  // it does not substitute a renderer or an extraction implementation.
  await browser.evaluate((rows) => {
    const panel = document.createElement("section");
    panel.style.cssText = "position:fixed;top:70px;right:24px;width:760px;z-index:9999;background:#111827;color:#f9fafb;border:2px solid #64748b;border-radius:12px;padding:24px;font:16px/1.6 monospace;box-shadow:0 8px 30px #0008";
    const title = document.createElement("h2");
    title.textContent = "Server extraction evidence (read-only diagnostic)";
    title.style.cssText = "font:600 20px/1.5 sans-serif;margin:0 0 12px";
    panel.append(title);
    for (const row of rows) {
      const pre = document.createElement("pre");
      pre.style.cssText = "white-space:pre-wrap;margin:16px 0;overflow-wrap:anywhere";
      pre.textContent = `${row.name}\n${row.header}\nSidecar: ${row.text === null ? "NOT CREATED" : JSON.stringify(row.text)}\nUTF-8: ${row.bytes ?? "—"}`;
      panel.append(pre);
    }
    const note = document.createElement("p");
    note.textContent = "Expected for both uploads: Café Crème. Files attached in composer; no message sent.";
    panel.append(note);
    document.body.append(panel);
  }, results);
  await app.screenshot("mac-roman-sidecars");
  expect(results.map(row => row.text?.trim() ?? null)).toEqual(["Café Crème", "Café Crème"]);
});
