"""AmbiLED serial LED client — sends pixel data using the AmbiLED protocol.

Protocol: raw RGB bytes (values clamped to 0–250) followed by 0xFF show command.
No header or checksum — simpler than Adalight.
Reference: https://github.com/flytron/ambiled-hd
"""

import numpy as np

from wled_controller.core.devices.adalight_client import AdalightClient
from wled_controller.utils import get_logger

logger = get_logger(__name__)

# AmbiLED command byte — triggers display update
AMBILED_SHOW_CMD = b"\xff"


class AmbiLEDClient(AdalightClient):
    """LED client for AmbiLED serial devices."""

    def __init__(self, url: str, led_count: int = 0, baud_rate=None, **kwargs):
        super().__init__(url, led_count=led_count, baud_rate=baud_rate, **kwargs)
        # AmbiLED has no header — clear the Adalight header
        self._header = b""

    async def connect(self) -> bool:
        result = await super().connect()
        if result:
            logger.info(
                f"AmbiLED connected: {self._port} @ {self._baud_rate} baud "
                f"({self._led_count} LEDs)"
            )
        return result

    def _build_frame(self, pixels, brightness: int) -> bytes:
        """Build an AmbiLED frame: brightness-scaled RGB data + 0xFF show command."""
        if isinstance(pixels, np.ndarray):
            arr = pixels.astype(np.uint16)
        else:
            arr = np.array(pixels, dtype=np.uint16)

        # Note: brightness already applied by processor loop (_cached_brightness)
        # Clamp to 0–250: values >250 are command bytes in AmbiLED protocol
        np.clip(arr, 0, 250, out=arr)
        rgb_bytes = arr.astype(np.uint8).tobytes()
        return rgb_bytes + AMBILED_SHOW_CMD
