# SteamVR session wedge test. Launch SteamVR, let addons co-drive the MCU,
# quit, then check MCU liveness. Wedge = MCU stops ACKing (version -> None).
import sys, os, time, subprocess
QBU = r"C:\Users\decid\Documents\projects\quick-beyond-updater"
sys.path.insert(0, QBU)
import hid
import bs_hmd_tools as t

STEAM = r"C:\Program Files (x86)\Steam\steam.exe"
SVR_PROCS = ["vrserver.exe", "vrcompositor.exe", "vrmonitor.exe", "vrdashboard.exe", "vrwebhelper.exe"]

def app_path():
    return next((d['path'] for d in hid.enumerate(vendor_id=0x35BD, product_id=0x0101)), None)

def mcu_alive(tries=4):
    """Return version string if MCU ACKs within retries, else None (=wedged)."""
    for _ in range(tries):
        ap = app_path()
        if ap:
            try:
                v = t.get_hmd_fw_version(device_path=ap)
                if v:
                    return v
            except Exception as e:
                pass
        time.sleep(1)
    return None

def procs_up():
    out = subprocess.run(["tasklist"], capture_output=True, text=True).stdout.lower()
    return [p for p in SVR_PROCS if p in out]

print("PRE-SESSION MCU:", mcu_alive())

print("launching SteamVR (appid 250820)...")
subprocess.Popen([STEAM, "-applaunch", "250820"])
# wait for vrserver up
for i in range(40):
    time.sleep(2)
    up = procs_up()
    if "vrserver.exe" in up:
        print(f"  SteamVR up after ~{(i+1)*2}s: {up}")
        break
else:
    print("  WARN: vrserver never appeared; procs:", procs_up())

# let the session run + addons drive the MCU
print("session running 45s (addons co-driving MCU)...")
time.sleep(45)
print("MID-SESSION MCU:", mcu_alive())

print("session running another 30s...")
time.sleep(30)

# quit SteamVR (graceful: close vrmonitor, then ensure vrserver gone)
print("quitting SteamVR...")
subprocess.run(["taskkill", "/IM", "vrmonitor.exe"], capture_output=True, text=True)
time.sleep(3)
still = procs_up()
if still:
    print("  force-killing remaining:", still)
    for p in still:
        subprocess.run(["taskkill", "/F", "/IM", p], capture_output=True, text=True)
time.sleep(5)
print("  post-quit procs:", procs_up())

# decisive: after SteamVR released the HMD, is the MCU still alive?
print("waiting 6s for addons to release 0101...")
time.sleep(6)
v1 = mcu_alive(tries=6)
print("POST-EXIT MCU (attempt 1):", v1)
time.sleep(4)
v2 = mcu_alive(tries=6)
print("POST-EXIT MCU (attempt 2):", v2)

verdict = "ALIVE - NO WEDGE" if (v1 or v2) else "WEDGED - MCU UNRESPONSIVE"
print("=== VERDICT:", verdict, "===")
sys.exit(0 if (v1 or v2) else 7)
