"""Triones / HappyLighting / LEDnet BLE controller protocol.

Applies to the large family of cheap single-color BLE RGB(W) controllers
sold under names like ``Triones``, ``LEDnet``, ``HappyLighting``,
``Magic Home BLE``. They share a 9-byte framed protocol:

    ``7E 07 05 03 RR GG BB 10 EF``  — set solid color (RGB)
    ``7E 04 04 RR GG BB 10 EF``      — some LEDnet variants use the shorter form

Power is a separate frame:

    ``7E 04 04 F0 00 01 FF 00 EF``  — ON
    ``7E 04 04 00 00 00 FF 00 EF``  — OFF

Reference implementations:
    * https://github.com/sysofwan/ha-magicfan
    * https://github.com/madhead/saberlight
"""

from __future__ import annotations

from ledgrab.core.devices.ble_protocols import BLEProtocol

_SERVICE_UUID = "0000ffe5-0000-1000-8000-00805f9b34fb"
_WRITE_CHAR_UUID = "0000ffe9-0000-1000-8000-00805f9b34fb"


def _clamp_byte(value: int) -> int:
    if value < 0:
        return 0
    if value > 255:
        return 255
    return value


def encode_color(r: int, g: int, b: int, brightness: int = 255) -> bytes:
    """Build a Triones "set solid color" frame.

    Software brightness is applied to RGB — the on-wire protocol has no
    separate brightness byte.
    """
    r = _clamp_byte(r)
    g = _clamp_byte(g)
    b = _clamp_byte(b)
    brightness = _clamp_byte(brightness)
    if brightness != 255:
        r = (r * brightness) // 255
        g = (g * brightness) // 255
        b = (b * brightness) // 255
    return bytes((0x7E, 0x07, 0x05, 0x03, r, g, b, 0x10, 0xEF))


def encode_power(on: bool) -> bytes:
    """Build a Triones power on/off frame."""
    if on:
        return bytes((0x7E, 0x04, 0x04, 0xF0, 0x00, 0x01, 0xFF, 0x00, 0xEF))
    return bytes((0x7E, 0x04, 0x04, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xEF))


PROTOCOL = BLEProtocol(
    family="triones",
    display_name="Triones / HappyLighting / LEDnet",
    service_uuid=_SERVICE_UUID,
    write_char_uuid=_WRITE_CHAR_UUID,
    write_with_response=False,
    encode_color=encode_color,
    encode_power=encode_power,
    name_prefixes=("Triones", "LEDBLE", "LEDnet", "HappyLighting", "MagicHome"),
)
