"""Open Pixel Control device provider — Fadecandy and OPC-compatible receivers."""

from __future__ import annotations

from typing import TYPE_CHECKING, List

from ledgrab.core.devices.led_client import (
    DeviceHealth,
    DiscoveredDevice,
    LEDClient,
    LEDDeviceProvider,
    ProviderDeps,
)
from ledgrab.core.devices.opc_client import OPCClient, parse_opc_url
from ledgrab.utils import get_logger

if TYPE_CHECKING:
    from ledgrab.core.devices.device_config import OPCConfig

logger = get_logger(__name__)


class OPCDeviceProvider(LEDDeviceProvider):
    """Provider for Open Pixel Control receivers (Fadecandy, OPC bridges, etc.).

    OPC has no native discovery protocol — users supply an IP. The channel
    field (default 0 = broadcast to all OPC channels) routes pixel data to
    a specific output on multi-channel servers.
    """

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

    @property
    def capabilities(self) -> set:
        # OPC has no reply channel; no power / brightness query.
        # Software brightness still applies client-side before the frame is sent.
        return {"manual_led_count", "health_check"}

    def create_client(self, config: "OPCConfig", *, deps: ProviderDeps) -> LEDClient:
        return OPCClient(
            config.device_url,
            led_count=config.led_count,
            channel=config.opc_channel,
        )

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

    async def validate_device(self, url: str) -> dict:
        try:
            host, port = parse_opc_url(url)
        except ValueError as exc:
            raise ValueError(f"Invalid OPC URL: {exc}") from exc
        logger.info("OPC device URL validated: host=%s port=%d", host, port)
        return {}

    async def discover(self, timeout: float = 3.0) -> List[DiscoveredDevice]:
        """OPC has no discovery protocol — returns empty list."""
        return []
