from typing import ClassVar, List, Optional

from google.protobuf.json_format import MessageToDict
from google.protobuf.message import Message
from pydantic import UUID4, BaseModel, validate_call

from .api_constants import (
    SUCCESS_CODE,
    RequestMessages,
    RPCMethodNames,
    Stubs,
)
from .config import grpc_settings


class ValidationError(Exception):
    pass


class ResponseCodeError(Exception):
    pass


class RPCClient(BaseModel):
    _instances: ClassVar[dict] = {}
    stub: ClassVar

    def __new__(cls, *args, **kwargs):
        # Ensure that each subclass has its own singleton instance
        if cls not in cls._instances:
            cls._instances[cls] = super().__new__(cls)
        return cls._instances[cls]

    @validate_call(config=dict(arbitrary_types_allowed=True))
    async def perform_rpc(
        self,
        rpc_method_name: str,
        request_message: Optional[Message] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Perform the remote-precedure-call.

        Parameters:
            rpc_method_name: The name of the RPC method (e.g., `Retrieve`).
            request_message: The request message instance.
            timeout: RPC timeout.
            wait_for_ready: Wait for Channel to be ready in case is not.
        """
        RPCMethod = getattr(self.stub, rpc_method_name, None)

        if RPCMethod:
            metadata = [("api-key", grpc_settings.API_KEY)]
            response = await RPCMethod(
                request_message,
                metadata=metadata,
                timeout=grpc_settings.TIMEOUT if timeout is None else timeout,
                wait_for_ready=grpc_settings.WAIT_FOR_READY
                if wait_for_ready is None
                else wait_for_ready,
            )

            # Raise error if response is not successful
            if response.code != SUCCESS_CODE:
                raise ResponseCodeError(response.code)

            return MessageToDict(response, preserving_proto_field_name=True)
        else:
            raise ValidationError("Invalid RPC method name.")


class Media(RPCClient):
    stub = Stubs.MEDIA

    @validate_call
    async def fetch_one(
        self,
        identifier: str | UUID4,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Fetch a media's info."""
        request = RequestMessages.FETCH_ONE_MEDIA(uuid_id=str(identifier))
        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.FETCH_ONE,
            request_message=request,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )

    @validate_call
    async def fetch_bulk(
        self,
        identifiers: List[str | UUID4],
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Fetch medias' info."""
        request = RequestMessages.FETCH_BULK_MEDIA(uuid_id=map(str, identifiers))
        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.FETCH_BULK,
            request_message=request,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )
