"""Kpi1 RPC wrappers — thin service layer (proto only)."""

from __future__ import annotations

from typing import TYPE_CHECKING

import grpc

from radiens_core._generated import allegoserver_pb2_grpc, common_pb2
from radiens_core._transport._errors import handle_grpc_error
from radiens_core.models.common import ClientType

if TYPE_CHECKING:
    from radiens_core._transport._channel_pool import ChannelPool


def kpi_get_metrics_allego_proto(
    pool: ChannelPool,
    addr: str,
    request: common_pb2.KpiMetricsReq,
) -> common_pb2.SignalMetricsPacketReply:
    """Send ``KpiGetMetrics`` RPC to Kpi1, return raw proto response."""
    channel = pool.get_channel(addr)
    stub = allegoserver_pb2_grpc.Kpi1Stub(channel)
    try:
        return stub.KpiGetMetrics(request)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, ClientType.ALLEGO)
        raise  # unreachable, but satisfies mypy


def get_kpi_status_allego_proto(
    pool: ChannelPool,
    addr: str,
    request: common_pb2.GetKpiStatusRequest,
) -> common_pb2.KpiStatusReply:
    """Send ``GetKpiStatus`` RPC to Kpi1, return raw proto response."""
    channel = pool.get_channel(addr)
    stub = allegoserver_pb2_grpc.Kpi1Stub(channel)
    try:
        return stub.GetKpiStatus(request)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, ClientType.ALLEGO)
        raise  # unreachable, but satisfies mypy


def set_kpi_update_period_proto(
    pool: ChannelPool,
    addr: str,
    request: common_pb2.SetKpiParamRequest,
) -> common_pb2.StandardReply:
    """Send ``SetKpiUpdatePeriod`` RPC to Kpi1, return raw proto response."""
    channel = pool.get_channel(addr)
    stub = allegoserver_pb2_grpc.Kpi1Stub(channel)
    try:
        return stub.SetKpiUpdatePeriod(request)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, ClientType.ALLEGO)
        raise  # unreachable, but satisfies mypy


def set_kpi_packet_dur_allego_proto(
    pool: ChannelPool,
    addr: str,
    request: common_pb2.SetKpiParamRequest,
) -> common_pb2.StandardReply:
    """Send ``SetKpiPacketDur`` RPC to Kpi1, return raw proto response."""
    channel = pool.get_channel(addr)
    stub = allegoserver_pb2_grpc.Kpi1Stub(channel)
    try:
        return stub.SetKpiPacketDur(request)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, ClientType.ALLEGO)
        raise  # unreachable, but satisfies mypy
