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 InstallmentItemRequest, ItemRequest
from dmdc.schemas import (
    CouponCalculateResult,
    DiscountedInstallmentItems,
    DiscountedItems,
    InstallmentItem,
    Item,
    TieredDiscountResult,
)

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 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."""

        # 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,
        )

    @validate_call
    async def calculate_by_basket(
        self,
        items: List[Item],
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate and return discount data for provided items if they're in active baskets."""

        # Assign attributes
        request = RequestMessages.CALCULATE_BY_BASKET(
            items=[ItemRequest(**item.model_dump()) for item in items]
        )

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

    @validate_call
    async def calculate_installment_by_basket(
        self,
        items: List[InstallmentItem],
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate and return discount data for provided installment items if they're in active baskets."""

        # Assign attributes
        request = RequestMessages.CALCULATE_INSTALLMENT_BY_BASKET(
            items=[InstallmentItemRequest(**item.model_dump()) for item in items]
        )

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

    @validate_call
    async def calculate_tiered_discount(
        self,
        amount: int,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Calculate and return tiered discount data for the provided amount."""

        request = RequestMessages.CALCULATE_TIERED_DISCOUNT(amount=amount)

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

    @validate_call
    async def create_usage(
        self,
        user_id: str,
        discount_amount: int,
        coupon: Optional[str] = None,
        baskets: Optional[List[str]] = None,
        request_id: Optional[str | int | UUID] = None,
        timeout: Optional[float] = None,
        wait_for_ready: Optional[bool] = None,
    ):
        """Create discount usage for a user with optional coupon and baskets."""

        baskets = baskets or []

        # build the UsageRequest
        request = RequestMessages.CREATE_USAGE(
            user_id=user_id,
            discount_amount=discount_amount,
            coupon=coupon,
            baskets=baskets,
        )

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