"""Tests for AllegoClient CoreConfig methods."""

from __future__ import annotations

from unittest.mock import patch

from radiens_core._generated import allegoserver_pb2, common_pb2
from radiens_core.allego_client import AllegoClient
from radiens_core.models.core_config import CableDelay, CoreConfig
from radiens_core.models.ports import Port
from radiens_core.models.status import BackboneMode


def test_get_core_config() -> None:
    """get_core_config returns domain model converted from proto."""
    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

    with (
        patch("radiens_core._base_client.AuthInterceptor"),
        patch("radiens_core.allego_client.get_config_proto", return_value=proto) as mock_rpc,
    ):
        client = AllegoClient()
        config = client.get_core_config()

    assert isinstance(config, CoreConfig)
    assert config.base_samp_freq == 30000.0
    assert config.backbone_mode == BackboneMode.SMARTBOX_PRO
    assert config.cable_delays[0].port == Port.A
    mock_rpc.assert_called_once()


def test_update_core_config() -> None:
    """update_core_config sends converted proto request."""
    with (
        patch("radiens_core._base_client.AuthInterceptor"),
        patch("radiens_core.allego_client.set_config_core_proto", return_value=common_pb2.StandardReply()) as mock_rpc,
    ):
        client = AllegoClient()
        client.update_core_config(
            samp_freq=30000.0,
            cable_delay=CableDelay(port=Port.B, cable_delay=5, is_auto=False),
        )

    mock_rpc.assert_called_once()
    args, _ = mock_rpc.call_args
    proto_req: allegoserver_pb2.SetConfigCoreRequest = args[2]
    assert proto_req.sampFreq == 30000.0
    assert proto_req.cableDelay.port == common_pb2.B
    assert proto_req.cableDelay.cableDelay == 5
    assert proto_req.cableDelay.isAuto is False
