import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Terminal retains early numbered output within its byte budget", { ...WEB, video: "off" }, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("scrollback-demo");
  await t3.thread({ project, title: "Scrollback evidence", messages: ["ready"] });
  await t3.open();
  await screen.getByRole("button", "Scrollback evidence, Done, scrollback-demo").tap();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = browser.locator('textarea[aria-label="Terminal input"]');
  await input.waitFor({ state: "attached" });
  const results: number[] = [];
  for (const width of [1280, 680]) {
    await browser.setViewport({ width, height: 800 });
    if (width === 680) await screen.getByRole("button", "New Terminal (Ctrl+N)").tap();
    await browser.evaluate(() => { const el = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement; el.focus(); });
    const readBuffer = async () => {
      await browser.keyboard.press("Control+Shift+A");
      return await browser.evaluate(() => {
        const el = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement;
        const data = new DataTransfer();
        el.dispatchEvent(new ClipboardEvent("copy", { clipboardData: data, bubbles: true, cancelable: true }));
        return data.getData("text/plain");
      });
    };
    // Wait for the shell prompt before submitting the reproduction as one paste.
    for (let attempt = 0; attempt < 100; attempt++) {
      if (/[>$]/.test(await readBuffer())) break;
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    await browser.evaluate((command) => {
      const el = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement;
      el.focus();
      const data = new DataTransfer();
      data.setData("text/plain", command);
      el.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }));
    }, String.raw`PS1='> '; printf '\033c'; i=1; while [ "$i" -le 12000 ]; do printf 'T3-SCROLLBACK-%05d\n' "$i"; i=$((i+1)); done; printf 'T3-END\n'`);
    await browser.keyboard.press("Enter");
    await expect.poll(async () => (await readBuffer()).includes("T3-END\n")).toBe(true);
    const text = await readBuffer();
    const first = Number(text.match(/T3-SCROLLBACK-(\d+)/)?.[1] ?? 12001);
    results.push(first);
    await app.startRecording({ name: `scrollback-${width}` });
    // Clear the selection using a real pointer interaction, then jump to oldest retained output.
    await browser.locator('canvas').last().tap();
    await browser.keyboard.press("Control+Shift+Home");
    await app.screenshot(`oldest-retained-${width}`);
    await browser.keyboard.press("Control+Shift+End");
    await browser.keyboard.press("Control+Shift+Home");
    await app.stopRecording();
  }
  expect(results[0]).toBeLessThan(10000);
  expect(results[1]).toBeLessThan(10000);
});
