#!/usr/bin/env python3
# probeModemPrompt.py - get to the "PRESS A OR O AND SET MODEM." prompt with the SwiftLink module
# resident, then find out why a typed key does or does not reach the game.
#
# The game records the last typed character in lastTypedKey ($9248) from the raster IRQ, and
# waitForAnswerOriginateKey ($0CBD) spins until it holds $C1 ('A') or $CF ('O').  The keyboard scan
# goes through the comm module's hook at $E012, so this also dumps that vector.
import os
import subprocess
import sys
import time

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

SHOTS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "shots")


def main():
    disk = os.path.abspath(sys.argv[1])
    session = ViceSession(disk, f"{SCRATCH}/prompt.vice.log", aciaArgs(), label="prompt")
    try:
        session.connect()
        session.bootPastLoader()
        session.findWindow()
        session.focus()
        time.sleep(8)
        session.mon("help")

        # highlight COMPETE WITH MODEM OPPONENT and choose it
        for _ in range(3):
            session.enterMonitor()
            row = readByte(session, 0x91D5)
            session.sock.sendall(b"x\n")
            session.recv(3)
            if row == 0:
                break
            session.hold("KP_8", 250)
            time.sleep(0.8)
        print(f"row = {row}", flush=True)
        session.hold("KP_0", 300)
        time.sleep(25)

        session.enterMonitor()
        session.mon("m e000 e017")
        session.mon("m 9248 9248")
        session.mon("m 90e9 90ea")
        session.mon("m 0b7d 0b7e")
        session.mon("r")
        session.sock.sendall(b"x\n")
        session.recv(3)

        for key in ("x", "a", "o", "A"):
            session.hold(key, 500)
            time.sleep(1)
            session.enterMonitor()
            print(f"--- after key {key!r}", flush=True)
            session.mon("m 9248 9248")
            session.mon("m 90e9 90ea")
            session.mon("m e03b e041")
            session.mon("m de00 de03")
            session.sock.sendall(b"x\n")
            session.recv(3)
        session.shot(f"{SHOTS}/promptAfterKeys.png")
    finally:
        session.close()


main()
