"""USB HID LED device provider — control RGB peripherals via USB HID."""

from typing import List

from wled_controller.core.devices.led_client import (
    DeviceHealth,
    DiscoveredDevice,
    LEDClient,
    LEDDeviceProvider,
)
from wled_controller.core.devices.usbhid_client import USBHIDClient, _parse_hid_url
from wled_controller.utils import get_logger

logger = get_logger(__name__)

# Known RGB peripheral vendor IDs and names
KNOWN_RGB_VENDORS = {
    0x1532: "Razer",
    0x1B1C: "Corsair",
    0x1038: "SteelSeries",
    0x046D: "Logitech",
    0x2516: "Cooler Master",
    0x0951: "HyperX",
    0x3633: "Glorious",
    0x320F: "NZXT",
}


class USBHIDDeviceProvider(LEDDeviceProvider):
    """Provider for USB HID RGB peripheral devices.

    URL format: hid://VID:PID (hex, e.g. hid://1532:0084)
    LED count = number of addressable zones/keys on the device.
    """

    @property
    def device_type(self) -> str:
        return "usbhid"

    @property
    def capabilities(self) -> set:
        return {"manual_led_count", "health_check"}

    def create_client(self, url: str, **kwargs) -> LEDClient:
        return USBHIDClient(
            url,
            led_count=kwargs.get("led_count", 0),
            hid_usage_page=kwargs.get("hid_usage_page", 0),
        )

    async def check_health(self, url: str, http_client, prev_health=None) -> DeviceHealth:
        return await USBHIDClient.check_health(url, http_client, prev_health)

    async def validate_device(self, url: str) -> dict:
        """Validate HID device exists. LED count is manual."""
        try:
            import hid

            vid, pid = _parse_hid_url(url)
            devices = hid.enumerate(vid, pid)
            if not devices:
                raise ValueError(f"No HID device found with VID:PID {vid:04X}:{pid:04X}")
            return {}
        except ImportError:
            raise ValueError("hidapi is required for USB HID devices: pip install hidapi")
        except ValueError:
            raise

    async def discover(self, timeout: float = 3.0) -> List[DiscoveredDevice]:
        """Discover connected USB HID devices with known RGB vendor IDs."""
        try:
            import hid

            results = []
            seen = set()
            for info in hid.enumerate():
                vid = info.get("vendor_id", 0)
                pid = info.get("product_id", 0)
                key = (vid, pid)
                if key in seen or vid == 0:
                    continue
                seen.add(key)

                vendor = KNOWN_RGB_VENDORS.get(vid)
                if not vendor:
                    continue

                product = info.get("product_string", "Unknown Device")
                results.append(
                    DiscoveredDevice(
                        name=f"{vendor} {product}",
                        url=f"hid://{vid:04x}:{pid:04x}",
                        device_type="usbhid",
                        ip="",
                        mac="",
                        led_count=None,
                        version=None,
                    )
                )
            return results
        except ImportError:
            return []
