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

const physical = (code: number, count = 1) => execFileSync("python3", ["-c", `
import ctypes
x=ctypes.CDLL('libX11.so.6'); t=ctypes.CDLL('libXtst.so.6')
x.XOpenDisplay.restype=ctypes.c_void_p
x.XFlush.argtypes=[ctypes.c_void_p]
x.XSync.argtypes=[ctypes.c_void_p,ctypes.c_int]
t.XTestFakeKeyEvent.argtypes=[ctypes.c_void_p,ctypes.c_uint,ctypes.c_int,ctypes.c_ulong]
d=x.XOpenDisplay(None)
for _ in range(${count}):
 t.XTestFakeKeyEvent(d,${code},1,0); t.XTestFakeKeyEvent(d,${code},0,0)
x.XSync(d,0)
`]);
const read = (path: string) => { try { return readFileSync(path,"utf8"); } catch { return ""; } };

test("OS remapped Escape reaches cat and leaves vim insert mode", {...WEB, video:"off"}, async ({t3,app,browser,screen}) => {
 const capture = async (label:string) => {
  let previous=await app.screenshot(`${label}-settling-0`);
  for(let i=1;i<=10;i++) {
   await browser.evaluate(()=>new Promise(resolve=>setTimeout(()=>resolve(null),500)));
   const current=await app.screenshot(`${label}-settling-${i}`);
   if(readFileSync(previous).equals(readFileSync(current))) {
    console.log("STABLE_CAPTURE",label,i);
    await app.screenshot(label); return;
   }
   previous=current;
  }
  throw new Error(`Capture did not settle: ${label}`);
 };

 const project = await t3.project("keyboard-demo", {"key-probe.mjs": String.raw`import {appendFileSync,writeFileSync} from 'node:fs';
const out = new URL('received',import.meta.url);
writeFileSync(out,''); process.stdin.setRawMode(true);
process.stdin.on('data',chunk=>{
 if(chunk.toString()==='x'){process.stdin.setRawMode(false);process.exit(0);}
 const hex=chunk.toString('hex'); appendFileSync(out,hex+'\n');
 process.stdout.write('PTY bytes: '+hex+'\r\n');
});
process.stdout.write('Real PTY raw input: Delete/Backspace and navigation remaps\r\n');
writeFileSync(new URL('probe-ready',import.meta.url),'ready');
`});
 const thread = await t3.thread({project,title:"OS keyboard remaps",messages:["hello"]});
 await t3.open(thread);
 await screen.getByRole("button", "Toggle terminal drawer").tap();
 await screen.getByRole("button", "Toggle main sidebar").tap();
 const input = screen.getByLabel("Terminal input");
 await expect.poll(async () => {
  await input.focus(); await browser.keyboard.type(`echo ready > '${project}/ready'`); await browser.keyboard.press("Enter");
  return read(`${project}/ready`);
 }).toBe("ready\n");
 // Use a neutral prompt to keep environment paths out of the captures.
 await browser.keyboard.type("export PS1='$ '; printf '\\033[?12l'; clear"); await browser.keyboard.press("Enter");
 await browser.evaluate(() => { (window as any).keyEvents=[]; document.addEventListener('keydown',e => (window as any).keyEvents.push({code:e.code,key:e.key,keyCode:e.keyCode,isTrusted:e.isTrusted}),true); return null; });
 const pressPhysical = async (code:number,count=1) => {
  const n = await browser.evaluate(()=> (window as any).keyEvents.length);
  physical(code,count);
  await expect.poll(()=>browser.evaluate(()=> (window as any).keyEvents.length)).toBe(n+count);
 };
 const command = async (s:string) => { await input.focus(); await browser.keyboard.type(s); await browser.keyboard.press("Enter"); };
 await capture("ready");
 await app.startRecording({name:"terminal-os-remaps"});
 await command("cat -v | tee caps-output.txt");
 execFileSync("setxkbmap",["-option","","-option","caps:swapescape"]);
 await pressPhysical(66,3);
 await browser.keyboard.press("Shift+A"); await browser.keyboard.press("Enter");
 await expect.poll(()=>read(`${project}/caps-output.txt`)).toContain("A\n");
 await capture("caps-as-escape");
 await pressPhysical(9);
 await pressPhysical(56); await browser.keyboard.press("Enter");
 await expect.poll(()=>read(`${project}/caps-output.txt`)).toContain("B\n");
 await capture("escape-as-caps");
 await pressPhysical(9); // Caps off.
 execFileSync("setxkbmap",["-option",""]);
 await pressPhysical(9);
 await browser.keyboard.type("c"); await browser.keyboard.press("Enter");
 await expect.poll(()=>read(`${project}/caps-output.txt`)).toContain("c\n");
 await capture("ordinary-escape-control");
 await browser.keyboard.press("Control+c");
 await command("clear; node key-probe.mjs");
 await expect.poll(()=>read(`${project}/probe-ready`)).toBe("ready");
 const remaps = [
  {physical:119,symbol:"BackSpace",label:"Delete-as-Backspace"},
  {physical:22,symbol:"Delete",label:"Backspace-as-Delete"},
  {physical:111,symbol:"Prior",label:"Up-as-PageUp"},
  {physical:116,symbol:"Next",label:"Down-as-PageDown"},
  {physical:113,symbol:"Home",label:"Left-as-Home"},
  {physical:114,symbol:"End",label:"Right-as-End"},
 ];
 for (const [i,k] of remaps.entries()) {
  execFileSync("xmodmap",["-e",`keycode ${k.physical} = ${k.symbol}`]);
  // Chromium reloads XKB on the full map notification, rather than xmodmap's core mapping event.
  execFileSync("xkbcomp",["-xkb",process.env.DISPLAY!,`${project}/keymap.xkb`],{stdio:"ignore"});
  execFileSync("xkbcomp",[`${project}/keymap.xkb`,process.env.DISPLAY!],{stdio:"ignore"});
  await pressPhysical(k.physical);
  await expect.poll(()=>read(`${project}/received`).trim().split("\n").length).toBe(i+1);
  await capture(k.label);
 }
 execFileSync("setxkbmap",["-layout","us","-option",""]);
 await browser.keyboard.type("x");
 await command("vim -Nu NONE -n -i NONE -c 'call writefile([\"ready\"],\"vim-ready\")' -c 'set laststatus=0 showmode guicursor=a:block-blinkon0' vim-output.txt; printf '\\nSaved file: '; cat vim-output.txt");
 await expect.poll(()=>read(`${project}/vim-ready`)).toBe("ready\n");
 await browser.keyboard.type("ihello");
 await capture("vim-insert-mode");
 execFileSync("setxkbmap",["-option","","-option","caps:swapescape"]);
 await pressPhysical(66);
 await browser.keyboard.type(":wq"); await browser.keyboard.press("Enter");
 // Give the PTY a round trip without adding a keyboard event.
 await browser.evaluate(() => new Promise(resolve=>setTimeout(()=>resolve(null),1000)));
 await capture("vim-caps-leaves-insert-mode");
 execFileSync("setxkbmap",["-option",""]);
 const events = await browser.evaluate(()=> (window as any).keyEvents.filter((e:any)=>/^(CapsLock|Escape|Delete|Backspace|Arrow)/.test(e.code)));
 console.log("OS_EVENTS",JSON.stringify(events));
 const output = read(`${project}/caps-output.txt`);
 console.log("CAT_OUTPUT",JSON.stringify(output),"VIM_OUTPUT",JSON.stringify(read(`${project}/vim-output.txt`)));
 await app.stopRecording();
 expect({remaps:read(`${project}/received`),cat:output,vim:read(`${project}/vim-output.txt`)}).toEqual({remaps:"7f\n1b5b337e\n1b5b357e\n1b5b367e\n1b5b48\n1b5b46\n",cat:"^[^[^[A\nB\n^[c\n",vim:"hello\n"});
});
