/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const PROGRAM = String.raw`import sys,time,pathlib
sys.stdout.buffer.write(b"\x1b[2J\x1b[Hprompt\x1b[31" + 4096*b"\0" + b"\r")
sys.stdout.buffer.flush()
pathlib.Path('paused').write_text('yes')
time.sleep(120)
sys.stdout.buffer.write(b"mX\x1b[0m\r\n")
sys.stdout.buffer.flush()
pathlib.Path('finished').write_text('yes')
time.sleep(300)
`;

test("Joining during a split oversized CSI preserves the red X at column zero", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("split-output", { "split-csi.py": PROGRAM });
  const thread = await t3.thread({ project, title: "Split terminal output", messages: ["hello"] });
  const read = (file: string) => readFile(`${project}/${file}`, "utf8").catch(() => "");
  await t3.open(thread);
  await browser.evaluate(() => {
    const frame = document.createElement("iframe");
    frame.id = "joining-client";
    frame.src = location.href;
    frame.style.cssText = "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647";
    document.body.append(frame);
    return null;
  });
  const joining = browser.frameLocator("#joining-client");
  await joining.getByRole("button", "Toggle terminal drawer").waitFor();
  const showJoining = (show: boolean) => browser.evaluate((show) => {
    document.querySelector<HTMLIFrameElement>("#joining-client")!.style.display = show ? "" : "none";
    return null;
  }, show);
  await showJoining(false);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await input.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return read("shell-ready");
  }, { timeout: 30000 }).toBe("ready\n");
  await input.focus();
  await browser.keyboard.type("clear; python3 split-csi.py");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("paused"), { timeout: 15000 }).toBe("yes");
  await app.screenshot("original-during-pause");
  await showJoining(true);
  await joining.getByRole("button", "Toggle terminal drawer").tap();
  await joining.getByLabel("Terminal input").waitFor();
  await app.screenshot("joining-during-pause");
  await expect.poll(() => read("finished"), { timeout: 140000 }).toBe("yes");
  await showJoining(false);
  await app.screenshot("original-completed");
  await showJoining(true);
  const redPixels = () => browser.evaluate(() => {
    const doc = document.querySelector<HTMLIFrameElement>("#joining-client")!.contentDocument!;
    const canvas = doc.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
    const pixels = canvas.getContext("2d")!.getImageData(0, 0, Math.min(10, canvas.width), Math.min(24, canvas.height)).data;
    let count = 0;
    for (let i = 0; i < pixels.length; i += 4) if (pixels[i]! > 150 && pixels[i+1]! < 90 && pixels[i+2]! < 90) count++;
    return count;
  });
  try {
    await expect.poll(redPixels, { timeout: 5000 }).toBeGreaterThan(5);
  } finally {
    await app.screenshot("joining-completed");
  }
});
