"""Tests for CoreConfig converters."""

from __future__ import annotations

from radiens_core._converters._core_config import (
    core_config_from_proto,
    set_core_config_to_proto,
)
from radiens_core._generated import allegoserver_pb2, common_pb2
from radiens_core.models.core_config import CableDelay, CoreConfig, SetCoreConfigRequest
from radiens_core.models.ports import Port
from radiens_core.models.status import BackboneMode


def test_core_config_from_proto() -> None:
    proto = allegoserver_pb2.ConfigCore(
        allegoCoreServerPort="8888",
        baseSampFreq=30000.0,
        streamLoopDurMs=1000,
        backboneMode=allegoserver_pb2.SMARTBOX_PRO,
        hasXDAQGPIOExpander=True,
    )
    # Add a cable delay
    cd = proto.cableDelays.cableDelays[0]
    cd.port = common_pb2.A
    cd.cableDelay = 10
    cd.isAuto = True

    model = core_config_from_proto(proto)

    assert isinstance(model, CoreConfig)
    assert model.allego_core_server_port == "8888"
    assert model.base_samp_freq == 30000.0
    assert model.stream_loop_dur_ms == 1000
    assert model.backbone_mode == BackboneMode.SMARTBOX_PRO
    assert model.has_xdaq_gpio_expander is True
    assert len(model.cable_delays) == 1
    assert model.cable_delays[0].port == Port.A
    assert model.cable_delays[0].cable_delay == 10
    assert model.cable_delays[0].is_auto is True


def test_set_core_config_to_proto() -> None:
    req = SetCoreConfigRequest(
        samp_freq=30000.0,
        loop_dur=1000.0,
        pcache_persistence=60.0,
        cable_delay=CableDelay(port=Port.A, cable_delay=10, is_auto=True),
    )

    proto = set_core_config_to_proto(req)

    assert isinstance(proto, allegoserver_pb2.SetConfigCoreRequest)
    assert proto.sampFreq == 30000.0
    assert proto.loopDur == 1000.0
    assert proto.pcachePersistence == 60.0
    assert proto.cableDelay.port == common_pb2.A
    assert proto.cableDelay.cableDelay == 10
    assert proto.cableDelay.isAuto is True


def test_set_core_config_to_proto_empty() -> None:
    req = SetCoreConfigRequest()
    proto = set_core_config_to_proto(req)

    assert isinstance(proto, allegoserver_pb2.SetConfigCoreRequest)
    assert not proto.HasField("sampFreq")
    assert not proto.HasField("loopDur")
    assert not proto.HasField("pcachePersistence")
    assert not proto.HasField("cableDelay")
