"""Govee LAN device provider — LAN-discoverable Govee Wi-Fi bulbs and kits."""

from __future__ import annotations

from typing import TYPE_CHECKING, List

from ledgrab.core.devices.govee_client import (
    GoveeClient,
    discover_govee_devices,
    parse_govee_url,
)
from ledgrab.core.devices.led_client import (
    DeviceHealth,
    DiscoveredDevice,
    LEDClient,
    LEDDeviceProvider,
    ProviderDeps,
)
from ledgrab.utils import get_logger

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

logger = get_logger(__name__)


class GoveeDeviceProvider(LEDDeviceProvider):
    """Provider for Govee LAN-enabled Wi-Fi smart bulbs and ambient kits.

    Single-pixel adapter (averaging shape). Note that **per-device LAN
    Control toggle must be enabled in the Govee Home app** before the bulb
    will respond to discovery or commands — the UI hint copy reminds users.
    """

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

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

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

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

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

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

        results: List[DiscoveredDevice] = []
        for bulb in bulbs:
            ip = bulb.get("ip", "")
            if not ip:
                continue
            url = f"govee://{ip}"
            sku = bulb.get("sku") or "Govee"
            mac_like = bulb.get("device", "")
            results.append(
                DiscoveredDevice(
                    name=f"Govee {sku}".strip(),
                    url=url,
                    device_type="govee",
                    ip=ip,
                    mac=mac_like,
                    led_count=None,
                    version=bulb.get("version") or None,
                )
            )
        logger.info("Govee multicast scan found %d device(s)", len(results))
        return results
