"""
Peers client for Daisi SDK.
"""

from typing import Optional

import grpc

from protos.v1 import Peers_pb2, Peers_pb2_grpc
from protos.v1.models import PeerModels_pb2

from ..base_client import BaseClient
from ..config import DaisiConfig
from ..exceptions import DaisiError


class PeerClient(BaseClient):
    """Client for peer operations."""

    def __init__(self, config: Optional[DaisiConfig] = None) -> None:
        """Initialize peer client.

        Args:
            config: Daisi configuration.
        """
        super().__init__(config)
        self._stub: Optional[Peers_pb2_grpc.PeersProtoStub] = None

    @property
    def stub(self) -> Peers_pb2_grpc.PeersProtoStub:
        """Get or create the gRPC stub."""
        if self._stub is None:
            self._stub = Peers_pb2_grpc.PeersProtoStub(self._get_channel())
        return self._stub

    def get_peers(self) -> PeerModels_pb2.GetPeersResponse:
        """Get list of available peers.

        Returns:
            Response containing peer information.

        Raises:
            DaisiError: If request fails.
        """
        request = PeerModels_pb2.GetPeersRequest()

        try:
            return self.stub.GetPeers(request, metadata=self._get_metadata())
        except grpc.RpcError as e:
            raise DaisiError(f"Failed to get peers: {e.details()}") from e
