#!/usr/bin/env python3
# probeFire.py - find the key VICE's numpad joystick uses for the fire button, by watching the
# zero-page copies the raster IRQ makes of joystick port 2: zp_5D = direction, zp_5F/zp_61 = fire.
import os
import re
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from viceHarness import ViceSession, aciaArgs, SCRATCH


def dump(session, addr, count):
    out = session.mon(f"m {addr:04x} {addr+count-1:04x}")
    m = re.search(r"C:%04x\s+((?:[0-9a-f]{2}[ ]*)+)" % addr, out)
    return m.group(1).split() if m else []


def main():
    disk = os.path.abspath(sys.argv[1])
    session = ViceSession(disk, f"{SCRATCH}/probefire.vice.log", aciaArgs(), label="fire")
    try:
        session.connect()
        session.bootPastLoader()
        session.findWindow()
        session.focus()
        time.sleep(8)
        for key in ("KP_0", "KP_5", "KP_Insert", "Return", "space", "KP_Enter", "Control_R"):
            import subprocess
            subprocess.run(["xdotool", "keydown", key], env=session.env, check=False)
            time.sleep(0.5)
            session.enterMonitor()
            zp = dump(session, 0x005D, 6)
            row = dump(session, 0x91D5, 1)
            session.sock.sendall(b"x\n")
            session.recv(3)
            subprocess.run(["xdotool", "keyup", key], env=session.env, check=False)
            print(f"KEY {key}: zp5D..62 = {zp}  row={row}", flush=True)
            time.sleep(0.5)
    finally:
        session.close()


main()
