import usb.core
import usb.util
import os
import re

CANALYST_VID = 0x04d8
CANALYST_PID = 0x0053


def _bus_dev_from_symlink(symlink: str):
    """
    /dev/canalyst_left -> /dev/bus/usb/003/004
    return (busnum, devnum)
    """
    real = os.path.realpath(symlink)
    m = re.search(r"/usb/(\d+)/(\d+)$", real)
    if not m:
        raise RuntimeError(f"Cannot parse bus/dev from {real}")
    return int(m.group(1)), int(m.group(2))


def resolve_canalyst_device_index(symlink: str) -> int:
    """
    Resolve canalystii logical device index from udev symlink.
    """
    target_bus, target_dev = _bus_dev_from_symlink(symlink)

    devices = list(
        usb.core.find(
            find_all=True,
            idVendor=CANALYST_VID,
            idProduct=CANALYST_PID,
        )
    )

    if not devices:
        raise RuntimeError("No CANalyst-II device found")

    for idx, dev in enumerate(devices):
        # pyusb 的 bus / address 就是 BUSNUM / DEVNUM
        if dev.bus == target_bus and dev.address == target_dev:
            return idx

    raise RuntimeError(
        f"CANalyst-II {symlink} (bus={target_bus}, dev={target_dev}) not found in pyusb list"
    )


if __name__ == "__main__":
    id0 = resolve_canalyst_device_index("/dev/canalystii_0")
    id1 = resolve_canalyst_device_index("/dev/canalystii_1")

    print(id0)
    print(id1)
