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

const RTF = String.raw`{\rtf1\ansi The fee is {\deleted\revauthdel1\revdttmdel1 $500}{\revised\revauth1 $700}.}`;
async function sidecars(dir: string): Promise<string[]> {
  const entries = await readdir(dir, { withFileTypes: true });
  return (await Promise.all(entries.map(async (entry) => {
    const path = join(dir, entry.name);
    return entry.isDirectory() ? sidecars(path) : path.endsWith(".rtf.txt") ? [path] : [];
  }))).flat();
}
async function waitFile(path: string, directory: string) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 30000);
  try {
    const events = watch(directory, { signal: controller.signal });
    try { await readFile(path); return; } catch {}
    for await (const _ of events) {
      try { await readFile(path); return; } catch {}
    }
  } finally { clearTimeout(timer); controller.abort(); }
}

test("Fresh RTF upload excludes the tracked deletion", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("RTF proof", { "fee.rtf": RTF });
  const thread = await t3.thread({ project, title: "RTF tracked deletion", messages: ["Ready to inspect fee.rtf"] });
  await t3.open(thread);
  await browser.locator('input[type="file"]').setInputFiles(join(project, "fee.rtf"));
  // The upload response comes after the real server has written its extracted sidecar.
  await screen.getByRole("textbox").fill("Read the extracted text for fee.rtf. Expected: The fee is $700.");
  let extracted: string | undefined;
  for (let attempt = 0; attempt < 100; attempt++) {
    extracted = (await sidecars(join(T3_HOME, "userdata")))[0];
    if (extracted) break;
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  if (!extracted) throw new Error("Upload did not produce an RTF sidecar");
  await symlink(extracted, join(project, "fee.rtf.txt"));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.focus();
  await browser.evaluate(async () => {
    const input = document.querySelector('[aria-label="Terminal input"]');
    if (!input) throw new Error("Terminal input missing");
    if (input.hasAttribute("data-workspace-focus-default")) return;
    await new Promise<void>((resolve) => {
      const observer = new MutationObserver(() => {
        if (input.hasAttribute("data-workspace-focus-default")) { observer.disconnect(); resolve(); }
      });
      observer.observe(input, { attributes: true });
    });
  });
  // A clean prompt keeps environment-local paths out of the public capture.
  await writeFile(join(project, "inspect.sh"), "export PS1='proof> '\nprintf '\\033[2J\\033[H'\nprintf 'Fresh upload: fee.rtf\\nExtracted sidecar (cat fee.rtf.txt):\\n\\n'\ncat fee.rtf.txt\nprintf '\\n\\nExpected: The fee is $700.\\n'\ntouch inspected\n");
  const done = waitFile(join(project, "inspected"), project);
  await browser.keyboard.type(". ./inspect.sh\n");
  await done;
  await app.screenshot("extracted-rtf-text");
  expect(await readFile(extracted, "utf8")).toBe("The fee is $700.");
});
