"""WiZ Connected device provider — LAN-discoverable Philips budget-tier 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.wiz_client import (
    WiZClient,
    discover_wiz_bulbs,
    parse_wiz_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 WiZConfig

logger = get_logger(__name__)


class WiZDeviceProvider(LEDDeviceProvider):
    """Provider for WiZ Connected (Philips budget-tier) bulbs.

    Single-pixel device, identical adaptation shape as Yeelight/Hue.
    """

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

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

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

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

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

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

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