"""Tests for compact binary controller envelopes (host util)."""

import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT / "src"))

from util.binary_envelope import (  # noqa: E402
    BINARY_ENVELOPE_VERSION_2,
    brightness_wire_from_0_255,
    brightness_0_255_from_wire,
    pack_binary_envelope_v2,
    parse_binary_envelope,
    parse_binary_envelope_v2,
    parse_binary_envelope_v1,
)


def test_brightness_round_trip_extremes():
    assert brightness_0_255_from_wire(brightness_wire_from_0_255(0)) == 0
    assert brightness_0_255_from_wire(brightness_wire_from_0_255(255)) == 255


def test_pack_parse_v2_brightness_only():
    raw = pack_binary_envelope_v2(brightness_0_255=128)
    assert raw[0] == BINARY_ENVELOPE_VERSION_2
    data = parse_binary_envelope_v2(raw)
    assert data == {"v": "1", "b": 128}


def test_pack_parse_v2_full():
    raw = pack_binary_envelope_v2(
        presets={
            "a": {
                "p": "on",
                "c": ["#ffffff"],
                "d": 10,
                "b": 255,
                "a": True,
                "n1": 1,
                "n2": -2,
                "n3": 3,
                "n4": 4,
                "n5": 5,
                "n6": 6,
            }
        },
        select={"dev": ["a"]},
        default="a",
        default_targets=["dev"],
        brightness_0_255=64,
    )
    assert len(raw) <= 250
    data = parse_binary_envelope_v2(raw)
    assert data["v"] == "1"
    assert data["b"] == 64
    assert data["presets"]["a"]["p"] == "on"
    assert data["presets"]["a"]["n2"] == -2
    assert data["select"]["dev"] == ["a"]
    assert data["default"] == "a"
    assert data["targets"] == ["dev"]

    merged = parse_binary_envelope(raw)
    assert merged == data


def test_v2_wire_not_utf8_json():
    raw = pack_binary_envelope_v2(
        presets={"x": {"p": "blink", "c": ["#112233"]}},
        brightness_0_255=None,
    )
    assert raw[0] == BINARY_ENVELOPE_VERSION_2
    assert parse_binary_envelope_v1(raw) is None


def test_dont_change_brightness_v2():
    raw = pack_binary_envelope_v2(brightness_0_255=None)
    data = parse_binary_envelope_v2(raw)
    assert "b" not in data


def test_json_wire_not_v2():
    assert parse_binary_envelope_v2(b'{"v":"1"}') is None


def test_legacy_v1_parse_via_dispatcher():
    import json

    inner = json.dumps({"x": {"p": "on"}}, separators=(",", ":")).encode()
    raw = bytes([1, 255, len(inner), 0, 0]) + inner
    d = parse_binary_envelope(raw)
    assert d["presets"]["x"]["p"] == "on"
