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

const PROGRAM = `import curses
import sys
from pathlib import Path

def main(screen):
    curses.curs_set(2)
    mode = 0
    while True:
        screen.erase()
        screen.addstr(0, 0, "n: normal, c: concealed, u: concealed underline, q: quit")
        for row, attr in enumerate((0, curses.A_INVIS, curses.A_INVIS | curses.A_UNDERLINE), 2):
            screen.addstr(row, 22, "SECRET", attr)
        screen.move(2 + mode, 22)
        screen.refresh()
        sys.stdout.write("\\x1b[2 q")
        sys.stdout.flush()
        Path("state").write_text(str(mode))
        key = screen.getch()
        if key == ord("q"):
            break
        if key in (ord("n"), ord("c"), ord("u")):
            mode = (ord("n"), ord("c"), ord("u")).index(key)

curses.wrapper(main)
`;

test("Concealed curses text stays hidden under the block cursor", WEB, async ({t3, app, screen, browser}) => {
  await browser.emulateMedia({colorScheme: "dark"});
  const project = await t3.project("conceal-demo", {"conceal.py": PROGRAM});
  const thread = await t3.thread({project, title: "Terminal conceal", messages: ["hello"]});
  const read = (name: string) => readFile(`${project}/${name}`, "utf8").catch(() => "");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return read("shell-ready");
  }, {timeout: 30000}).toBe("ready\n");
  await browser.keyboard.type("TERM=xterm-256color python3 conceal.py");
  await browser.keyboard.press("Enter");
  await expect.poll(() => read("state")).toBe("0");
  const pixels = (row: number) => browser.evaluate((row) => {
    const canvas = document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;
    const ctx = canvas.getContext("2d")!;
    const size = Number(ctx.font.match(/([\d.]+)px/)![1]);
    const width = ctx.measureText("M").width;
    const measured = ctx.measureText("Mg");
    const height = Math.max(1, Math.round(size * 1.35), Math.ceil(measured.actualBoundingBoxAscent + measured.actualBoundingBoxDescent));
    const ratio = canvas.width / canvas.getBoundingClientRect().width;
    const colors = new Set<string>();
    for (let y = 3; y < height - 3; y++) for (let x = 2; x < width - 1; x++) {
      colors.add([...ctx.getImageData(Math.floor((4 + 22 * width + x)*ratio), Math.floor((4 + row * height + y)*ratio),1,1).data].join(","));
    }
    const bg = [...ctx.getImageData(Math.floor((4+30*width)*ratio), Math.floor((4+4*height+height-2)*ratio),1,1).data].join(",");
    let underline = 0;
    for (let x = 24*width; x < 28*width; x++) {
      const color = [...ctx.getImageData(Math.floor((4+x)*ratio), Math.floor((4+4*height+height-2)*ratio),1,1).data].join(",");
      if (color !== bg) underline++;
    }
    return {cursorColors: colors.size, cursorVisible: !colors.has(bg), underline, width, height, font: ctx.font};
  }, row);
  await hold(1000);
  await app.screenshot("normal-cursor");
  await browser.keyboard.type("c");
  await expect.poll(() => read("state")).toBe("1");
  await hold(1000);
  await app.screenshot("concealed-cursor");
  const concealed = await pixels(3);
  await browser.keyboard.type("u");
  await expect.poll(() => read("state")).toBe("2");
  await hold(1000);
  await app.screenshot("concealed-underline-cursor");
  const underlined = await pixels(4);
  await browser.keyboard.type("n");
  await expect.poll(() => read("state")).toBe("0");
  await hold(1000);
  await app.screenshot("normal-control");
  expect({concealed: concealed.cursorColors, underlined: underlined.cursorColors, cursorsVisible: concealed.cursorVisible && underlined.cursorVisible, underline: underlined.underline}).toEqual({concealed: 1, underlined: 1, cursorsVisible: true, underline: 0});
  await browser.keyboard.type("q");
});
