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

from __future__ import annotations

from typing import TYPE_CHECKING

import grpc

from radiens_core._generated import (
    common_pb2,
    radiensserver_pb2,
    radiensserver_pb2_grpc,
)
from radiens_core._transport._errors import handle_grpc_error
from radiens_core.models.common import ClientType, ServiceEndpoint

if TYPE_CHECKING:
    from radiens_core._transport._channel_pool import ChannelPool


def healthcheck_proto(
    pool: ChannelPool,
    addr: str,
    client_type: ClientType = ClientType.VIDERE,
    service: ServiceEndpoint = ServiceEndpoint.RADIENS_LIFECYCLE,
) -> radiensserver_pb2.RadiensHealthcheckSpec:
    """Send ``Healthcheck`` RPC to a radiens service, return raw proto response.

    *service* selects the stub: ``RADIENS_CORE`` uses ``RadiensCoreStub``,
    anything else defaults to ``RadiensLifecycleStub``.
    """
    channel = pool.get_channel(addr)
    req = radiensserver_pb2.RadiensHealthcheckRequest()
    try:
        if service == ServiceEndpoint.RADIENS_CORE:
            return radiensserver_pb2_grpc.RadiensCoreStub(channel).Healthcheck(req)
        return radiensserver_pb2_grpc.RadiensLifecycleStub(channel).Healthcheck(req)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, client_type)
        raise  # unreachable, but satisfies mypy


def get_radiens_servers_proto(
    pool: ChannelPool,
    addr: str,
    host_ip: str = "localhost",
    client_type: ClientType = ClientType.VIDERE,
) -> common_pb2.RadiensServersReply:
    """Send ``GetRadiensServers`` RPC to RadiensLifecycle, return raw proto response."""
    channel = pool.get_channel(addr)
    stub = radiensserver_pb2_grpc.RadiensLifecycleStub(channel)
    req = common_pb2.GetRadiensServersRequest(hostIPaddress=host_ip)
    try:
        return stub.GetRadiensServers(req)
    except grpc.RpcError as ex:
        handle_grpc_error(ex, client_type)
        raise  # unreachable, but satisfies mypy
