# Parametrized flasher: app -> bootloader -> program (code-46 retry) -> verify.
# usage: py flash_variant.py <path-to.beyondfw> <expected-version-substr>
import sys, os, time
QBU = r"C:\Users\decid\Documents\projects\quick-beyond-updater"
sys.path.insert(0, QBU); os.chdir(QBU)
import hid
import bs_hmd_tools as t

FW = sys.argv[1]
EXPECT = sys.argv[2] if len(sys.argv) > 2 else "0.4.4"

payload = t.load_beyondfw_file(FW)
print(f"flashing {os.path.basename(FW)} -> {len(payload[0])} bytes @ 0x{payload[1]:08X}, expect {EXPECT}")

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

# pre-flash version
ap = app_path()
print("pre-flash version:", t.get_hmd_fw_version(device_path=ap) if ap else "NO APP DEV")

ok = False
for attempt in range(1, 6):
    bp = boot_path()
    if bp is None:
        ap = app_path()
        if ap:
            print(f"attempt {attempt}: app->bootloader")
            try:
                bp = t.enter_hmd_bootloader(device_path=ap)
            except Exception as e:
                print(f"  enter_bootloader err: {e}"); time.sleep(2); continue
        if bp is None:
            print(f"attempt {attempt}: no bootloader; wait"); time.sleep(2); continue
    print(f"attempt {attempt}: programming via {bp.decode('utf-8','ignore')[:46]}")
    try:
        ok = t.update_hmd_firmware(firmware_payload=payload, bootloader_path=bp, reset_when_done=True)
        if ok:
            print(f"attempt {attempt}: programming OK"); break
    except Exception as e:
        print(f"attempt {attempt}: {e} (code-46 transient expected on 1st)")
        time.sleep(1.5)

print("=== verify ===")
ver = None
for _ in range(25):
    time.sleep(1)
    ap = app_path()
    if ap:
        try:
            ver = t.get_hmd_fw_version(device_path=ap)
            if ver:
                break
        except Exception:
            pass
print("post-flash version:", ver)
good = bool(ver and EXPECT in str(ver))
print("RESULT:", "OK" if good else f"CHECK ({ver})")
sys.exit(0 if good else 5)
