"""LIFX device provider — LAN-discoverable LIFX smart bulbs."""

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.lifx_client import (
    LIFXClient,
    discover_lifx_bulbs,
    parse_lifx_url,
)
from ledgrab.utils.net_classify import validate_lan_host
from ledgrab.utils import get_logger

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

logger = get_logger(__name__)


class LIFXDeviceProvider(LEDDeviceProvider):
    """Provider for LIFX smart bulbs / lightstrips.

    Single-pixel adapter: averages the strip down to one color, encodes as
    HSBK (LIFX's native color model), and broadcasts a SetColor packet.
    """

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

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

    def create_client(self, config: "LIFXConfig", *, deps: ProviderDeps) -> LEDClient:
        return LIFXClient(
            config.device_url,
            led_count=config.led_count,
            min_interval_s=max(0.0, config.lifx_min_interval_ms / 1000.0),
        )

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

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

    async def discover(self, timeout: float = 3.0) -> List[DiscoveredDevice]:
        try:
            bulbs = await discover_lifx_bulbs(timeout=min(timeout, 5.0))
        except (OSError, RuntimeError) as exc:
            logger.warning("LIFX discovery failed: %s", exc)
            return []

        results: List[DiscoveredDevice] = []
        for bulb in bulbs:
            ip = bulb.get("ip", "")
            if not ip:
                continue
            url = f"lifx://{ip}"
            mac = bulb.get("mac", "")
            results.append(
                DiscoveredDevice(
                    name=f"LIFX {mac[-6:]}" if mac else "LIFX bulb",
                    url=url,
                    device_type="lifx",
                    ip=ip,
                    mac=mac,
                    led_count=None,
                    version=None,
                )
            )
        logger.info("LIFX broadcast scan found %d bulb(s)", len(results))
        return results
