# Headless doze-firmware flasher: drives the canonical quick-beyond-updater
# bs_hmd_tools API to flash dist/latest.beyondfw, then reads the version back.
import sys, os, time

QBU = r"C:\Users\decid\Documents\projects\quick-beyond-updater"
sys.path.insert(0, QBU)
os.chdir(QBU)  # so hidapi.dll loads
import hid
import bs_hmd_tools as t

FW = r"C:\Users\decid\Documents\projects\beyond_synaptics\dist\latest.beyondfw"

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

print("=== load + verify .beyondfw ===")
payload = t.load_beyondfw_file(FW)  # raises on SHA512 mismatch
print(f"payload: {len(payload[0])} bytes @ 0x{payload[1]:08X}")

ap = app_path()
if ap is None:
    print("FAIL: no Beyond app device (35BD:0101) found"); sys.exit(2)
print(f"app device: {ap.decode('utf-8','ignore')[:60]}")
try:
    print("pre-flash version:", t.get_hmd_fw_version(device_path=ap))
except Exception as e:
    print("pre-flash version read failed (non-fatal):", e)

print("=== enter bootloader ===")
bl = t.enter_hmd_bootloader(device_path=ap)
if not bl:
    print("FAIL: did not reach bootloader"); sys.exit(3)
print("bootloader path:", bl.decode('utf-8','ignore')[:60])

print("=== flash ===")
ok = t.update_hmd_firmware(firmware_payload=payload, bootloader_path=bl, reset_when_done=True)
print("update_hmd_firmware ->", ok)
if not ok:
    print("FAIL: update returned False"); sys.exit(4)

print("=== verify (wait for app re-enumerate) ===")
ver = None
for _ in range(20):
    time.sleep(1)
    ap2 = app_path()
    if ap2:
        try:
            ver = t.get_hmd_fw_version(device_path=ap2)
            if ver: break
        except Exception:
            pass
print("post-flash version:", ver)
print("RESULT:", "OK 0.4.0" if ver and "0.4.0" in str(ver) else f"CHECK ({ver})")
