import ctypes, os, sys, time, json, subprocess
from datetime import datetime, timezone
run, mode = sys.argv[1:]
x11=ctypes.CDLL('libX11.so.6'); xtst=ctypes.CDLL('libXtst.so.6')
x11.XOpenDisplay.argtypes=[ctypes.c_char_p];x11.XOpenDisplay.restype=ctypes.c_void_p
x11.XStringToKeysym.argtypes=[ctypes.c_char_p];x11.XStringToKeysym.restype=ctypes.c_ulong
x11.XKeysymToKeycode.argtypes=[ctypes.c_void_p,ctypes.c_ulong];x11.XKeysymToKeycode.restype=ctypes.c_uint
x11.XSync.argtypes=[ctypes.c_void_p,ctypes.c_int]
x11.XQueryKeymap.argtypes=[ctypes.c_void_p,ctypes.c_void_p]
xtst.XTestFakeKeyEvent.argtypes=[ctypes.c_void_p,ctypes.c_uint,ctypes.c_int,ctypes.c_ulong]
display=x11.XOpenDisplay(None)
assert display
keys={name:x11.XKeysymToKeycode(display,x11.XStringToKeysym(name.encode())) for name in ['q','Control_L']}
def log(kind, **kw):
    print(json.dumps(dict(at=datetime.now(timezone.utc).isoformat(),monotonic=time.monotonic(),kind=kind,**kw)),flush=True)
def command(*args):
    log('native-command',argv=args)
    subprocess.run(args,check=True)
def key(name,down):
    xtst.XTestFakeKeyEvent(display,keys[name],int(down),0)
    x11.XSync(display,False)
    state=ctypes.create_string_buffer(32);x11.XQueryKeymap(display,state)
    log('XTestFakeKeyEvent',key=name,down=down,physicalDown=bool(state.raw[keys[name]//8]&(1<<(keys[name]%8))))
window=json.load(open(os.path.join(run,'native-ready.json')))['windowId']
command('xdotool','windowfocus','--sync',str(window))
command('xset','r','rate','250','30')
key('Control_L',True);key('q',True)
time.sleep(1.55)
if mode=='quiet-harness':
    with open(os.path.join(run,'quiet-stop.json'),'w') as marker: json.dump({'forcedQuiet':True},marker)
    log('quiet-period-start',qStillPhysicallyDown=True,action='Harness stops forwarding native repeats to installed callback; physical Q remains down')
    time.sleep(1.5)
key('q',False);key('Control_L',False)
if mode=='release-harness':
    with open(os.path.join(run,'release-now.json'),'w') as marker: json.dump({'forcedKeyUp':True},marker)
    log('request-harness-keyup',action='Physical Q keyup sent; ask main process to invoke retained actual listener with missing keyUp')
command('xset','r',str(keys['q']))
log('native-input-complete')
