from typing import ClassVar, List, Optional, Type, TypeVar
from uuid import UUID

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

from dmdc.grpc.discount_pb2 import ItemRequest
from dmdc.schemas import CouponCalculateResult, Item

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

M = TypeVar("M", bound=BaseModel)


class ValidationError(Exception):
    pass


class ResponseCodeError(Exception):
    pass


class RPCClient(BaseModel):
    _instances: ClassVar[dict] = {}
    stub_cls: 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,
        response_model: Optional[Type[M]] = None,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ) -> list[M] | dict:
        """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.
        """
        if config.CHANNEL is None:
            await config.construct_channel()

        RPCMethod = getattr(self.stub_cls(config.CHANNEL), rpc_method_name, None)
        if not RPCMethod:
            raise ValidationError("Invalid RPC method name.")

        metadata = [("api-key", config.grpc_settings.API_KEY)]
        if request_id:
            metadata.append(("x-request-id", str(request_id)))

        response = await RPCMethod(
            request_message,
            metadata=metadata,
            timeout=config.grpc_settings.TIMEOUT if timeout is None else timeout,
            wait_for_ready=config.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)

        response_dict = MessageToDict(response, preserving_proto_field_name=True)
        data = response_dict.get("data", [])

        if not response_model:
            return data

        return [response_model.model_validate(item) for item in data]


class Discount(RPCClient):
    stub_cls = Stubs.DISCOUNT

    @validate_call
    async def retrieve(
        self,
        token_identifier: str,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Retrieve discount using its `token_identifier`."""

        # Assign attributes
        request = RequestMessages.RETRIEVE(token_identifier=token_identifier)

        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.RETRIEVE,
            request_message=request,
            request_id=request_id,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )

    @validate_call
    async def validate(
        self,
        token_identifier: str,
        user_identifier: Optional[str] = None,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Validate if a discount token is valid."""

        # Assign attributes
        request = RequestMessages.VALIDATE(token_identifier=token_identifier)
        if user_identifier:
            request.user_identifier = user_identifier

        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.VALIDATE,
            request_message=request,
            request_id=request_id,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )

    @validate_call
    async def calculate_by_token(
        self,
        amount: int,
        token_identifier: str,
        user_identifier: Optional[str] = None,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate the discounted amount for provided token"""

        # Assign attributes
        request = RequestMessages.CALCULATE_BY_TOKEN(
            amount=amount, token_identifier=token_identifier
        )
        if user_identifier:
            request.user_identifier = user_identifier

        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.CALCULATE_BY_TOKEN,
            request_message=request,
            request_id=request_id,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )

    @validate_call
    async def calculate_by_item(
        self,
        amount: int,
        discount_type: str,
        item_identifier: str,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate the lowest discounted amount for an item."""

        # Assign attributes
        request = RequestMessages.CALCULATE_BY_ITEM(
            amount=amount, discount_type=discount_type, item_identifier=item_identifier
        )

        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.CALCULATE_BY_ITEM,
            request_message=request,
            request_id=request_id,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )

    @validate_call
    async def calculate_by_coupon(
        self,
        coupon_code: str,
        items: List[Item],
        owner_id: Optional[str] = None,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate and return detailed discount data for provided coupon.

        An overal and per item discount amount/percentage is returned."""

        # Assign attributes
        request = RequestMessages.CALCULATE_BY_COUPON(
            coupon_code=coupon_code,
            owner_id=owner_id,
            items=[ItemRequest(**item.model_dump()) for item in items],
        )

        return await self.perform_rpc(
            rpc_method_name=RPCMethodNames.CALCULATE_BY_COUPON,
            request_message=request,
            response_model=CouponCalculateResult,
            request_id=request_id,
            timeout=timeout,
            wait_for_ready=wait_for_ready,
        )
