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

const RTF = String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`;
const EXPECTED = "North quota: 120\nSouth quota: 240\nEast quota: 360\nWest quota: 480";
async function until<T>(read: () => Promise<T | undefined>): Promise<T> {
  const deadline = Date.now() + 30_000;
  while (Date.now() < deadline) {
    const value = await read().catch(() => undefined);
    if (value !== undefined) return value;
    await setTimeout(100);
  }
  throw new Error("STEP_TIMEOUT: waiting for upload or terminal output");
}

test("Fresh RTF upload preserves explicit column, page and section breaks", WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.emulateMedia({ colorScheme: "dark" });
    const project = await t3.project("RTF report", { "report.rtf": RTF });
    const thread = await t3.thread({ project, title: "RTF document breaks", messages: ["Inspect attachment extraction"] });
    await t3.open(thread);
    await screen.getByRole("button", "Attach files").setInputFiles(`${project}/report.rtf`);
    const sidecar = await until(async () => {
      const files = await readdir(`${T3_HOME}/userdata/attachments`, { recursive: true });
      const file = files.find((name) => name.endsWith(".rtf.txt"));
      return file ? `${T3_HOME}/userdata/attachments/${file}` : undefined;
    });
    const text = await readFile(sidecar, "utf8");
    // Display the real upload sidecar in the real app terminal, without a model reformatting it.
    await writeFile(`${project}/show-extracted.mjs`, `
      import {readFileSync,writeFileSync} from 'node:fs';
      const text=readFileSync(${JSON.stringify(sidecar)},'utf8');
      process.stdin.setRawMode(true); process.stdin.resume();
      process.stdout.write('\\x1b[2J\\x1b[HRTF ATTACHMENT: report.rtf\\r\\n'+
        'Fresh upload / server-generated extracted-text sidecar\\r\\n'+
        'Controls in source: \\\\column, \\\\page, \\\\sect\\r\\n\\r\\n'+
        '--- Extracted text (verbatim) ---\\r\\n'+text.replaceAll('\\n','\\r\\n')+
        '\\r\\n--- End extracted text ---\\r\\n\\r\\n'+
        'JSON (line breaks shown as \\\\n):\\r\\n'+JSON.stringify(text)+'\\r\\n');
      writeFileSync('display-ready','ready');
    `);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const input = screen.getByLabel("Terminal input");
    await input.waitFor();
    await until(async () => {
      await input.focus();
      await browser.keyboard.type("node show-extracted.mjs\n");
      return await readFile(`${project}/display-ready`, "utf8").catch(() => undefined);
    });
    // Two identical captures 500 ms apart ensure the terminal has finished painting.
    let previous = await app.screenshot("extracted-text-settling");
    for (let attempt = 0; attempt < 10; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot("extracted-text");
      if ((await readFile(previous)).equals(await readFile(current))) break;
      previous = current;
    }
    expect(text).toBe(EXPECTED);
  });
