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

const PROBE = String.raw`import curses, json, pathlib
root = pathlib.Path(__file__).parent

def main(win):
    curses.start_color()
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
    win.bkgd(" ", curses.color_pair(1))
    curses.noecho()
    curses.cbreak()
    win.keypad(True)
    received = []
    def paint(done=False):
        win.erase()
        win.addstr(0, 2, "NumLock OFF - real ncurses keypad navigation", curses.A_BOLD)
        win.addstr(2, 2, "Dedicated: Up, End, Delete | Keypad: 8, 1, Decimal")
        win.addstr(3, 2, "Application cursor/keypad mode negotiated by ncurses")
        for i, name in enumerate(received):
            win.addstr(5+i, 2, "%d. Received %s" % (i+1, name))
        if done:
            expected = ["KEY_UP", "KEY_END", "KEY_DC"] * 2
            win.addstr(12, 2, "PASS: keypad matches dedicated keys" if received == expected else "FAIL: keypad navigation never reached ncurses", curses.A_BOLD)
            win.addstr(13, 2, "Received %d of 6 navigation keys" % len(received))
        win.refresh()
    paint()
    (root / "probe-ready").write_text("ready")
    while True:
        key = win.getch()
        if key == ord('q'):
            paint(True)
            (root / "result.json").write_text(json.dumps(received))
        elif key == ord('x'):
            break
        else:
            received.append(curses.keyname(key).decode())
            paint()
curses.wrapper(main)
`;

test("NumLock-off keypad Up, End and Delete reach ncurses like dedicated keys", WEB,
 async ({ t3, app, browser, screen }) => {
    const project = await t3.project("keypad-demo", { "keypad.py": PROBE });
    const thread = await t3.thread({project, title: "Keypad navigation", messages: ["hello"]});
    const read = (name: string) => readFile(`${project}/${name}`, "utf8").catch(() => "");
    await browser.emulateMedia({ colorScheme: "dark" });
    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 keypad.py");
    await browser.keyboard.press("Enter");
    await expect.poll(() => read("probe-ready")).toBe("ready");
    await app.screenshot("ncurses-ready");
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1500)));
    // Playwright's Linux layout maps these Numpad codes to navigation keys with location 3.
    await browser.evaluate(() => {
      const input = document.querySelector('[aria-label="Terminal input"]');
      input?.addEventListener("keydown", (event) => {
        const e = event as KeyboardEvent;
        console.log(JSON.stringify({ key: e.key, code: e.code, location: e.location, numLock: e.getModifierState("NumLock"), trusted: e.isTrusted }));
      });
    });
    for (const key of ["ArrowUp", "End", "Delete", "Numpad8", "Numpad1", "NumpadDecimal"]) {
      await browser.keyboard.press(key);
      await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 600)));
    }
    await browser.keyboard.press("q");
    await expect.poll(() => read("result.json")).not.toBe("");
    await app.screenshot("ncurses-keypad-navigation");
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1000)));
    await expect.poll(() => read("result.json")).toBe(JSON.stringify(["KEY_UP", "KEY_END", "KEY_DC", "KEY_UP", "KEY_END", "KEY_DC"]).replaceAll(',', ', '));
 });
