"""Razer Chroma SDK device provider — control Razer RGB peripherals."""

from typing import List

from wled_controller.core.devices.led_client import (
    DeviceHealth,
    DiscoveredDevice,
    LEDClient,
    LEDDeviceProvider,
)
from wled_controller.core.devices.chroma_client import (
    ChromaClient,
    CHROMA_DEVICES,
    CHROMA_SDK_URL,
)
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class ChromaDeviceProvider(LEDDeviceProvider):
    """Provider for Razer Chroma SDK RGB peripherals.

    URL format: chroma://device_type (e.g. chroma://keyboard, chroma://chromalink)
    Requires Razer Synapse with Chroma SDK enabled.
    """

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

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

    def create_client(self, url: str, **kwargs) -> LEDClient:
        chroma_device_type = _parse_chroma_url(url)
        return ChromaClient(
            url=CHROMA_SDK_URL,
            led_count=kwargs.get("led_count", 0),
            chroma_device_type=chroma_device_type,
        )

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

    async def validate_device(self, url: str) -> dict:
        """Validate Chroma SDK is reachable."""
        chroma_type = _parse_chroma_url(url)
        if chroma_type not in CHROMA_DEVICES:
            raise ValueError(
                f"Unknown Chroma device type '{chroma_type}'. "
                f"Supported: {', '.join(CHROMA_DEVICES.keys())}"
            )

        import httpx

        try:
            async with httpx.AsyncClient(timeout=3.0) as client:
                resp = await client.get(CHROMA_SDK_URL)
                if resp.status_code >= 500:
                    raise ValueError("Chroma SDK returned server error")
        except httpx.ConnectError:
            raise ValueError(
                "Cannot connect to Chroma SDK. "
                "Ensure Razer Synapse is running with Chroma SDK enabled."
            )

        _, max_leds = CHROMA_DEVICES[chroma_type]
        return {"led_count": max_leds}

    async def discover(self, timeout: float = 3.0) -> List[DiscoveredDevice]:
        """Discover available Chroma device types if SDK is running."""
        import httpx

        try:
            async with httpx.AsyncClient(timeout=timeout) as client:
                resp = await client.get(CHROMA_SDK_URL)
                if resp.status_code >= 500:
                    return []
        except Exception:
            return []

        # SDK is running — offer all device types
        results = []
        for dev_type, (_, max_leds) in CHROMA_DEVICES.items():
            results.append(
                DiscoveredDevice(
                    name=f"Razer {dev_type.title()}",
                    url=f"chroma://{dev_type}",
                    device_type="chroma",
                    ip="127.0.0.1",
                    mac="",
                    led_count=max_leds,
                    version=None,
                )
            )
        return results


def _parse_chroma_url(url: str) -> str:
    """Parse 'chroma://device_type' → device_type string."""
    return url.replace("chroma://", "").strip().lower()
