import logging
from typing import ClassVar

from google.protobuf.struct_pb2 import Struct
from grpc.aio import insecure_channel
from pydantic import (
    BaseModel,
    EmailStr,
    HttpUrl,
    StringConstraints,
    validate_call,
)
from typing_extensions import Annotated

from .api_constants import (
    CONTROLLER_STUB,
    REQUEST_MESSAGE,
    RPC_METHOD_NAME,
    SUCCESS_CODE,
    EventProTypes,
    NotificationTypes,
)

logger = logging.getLogger(__name__)

IranianPhoneNumber = Annotated[
    str,
    StringConstraints(
        strip_whitespace=True, pattern=r"^(?:\+98|098|98|0098|)0?9\d{9}$"
    ),
]


class ResponseCodeError(Exception):
    pass


class ValidationError(Exception):
    pass


class Notify(BaseModel):
    """
    Configures the host and port of the notification server.

    Parameters:
        host (str): The host address of the notification server.
        port (int): The port number of the notification server.
        sender_unit (str): The name of the service utilizing this library.
    """

    host: str = "127.0.0.1"
    port: str | int = "50051"
    sender_unit: str = "notify client"

    __instance: ClassVar = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    @staticmethod
    def determine_send_type(recipient):
        """Determine the send_type based on recipient."""
        # Check if recipient is an email or phone number
        if "@" in recipient:
            send_type = NotificationTypes.EMAIL_NOTIFICATION
        else:
            send_type = NotificationTypes.SMS_NOTIFICATION

        return send_type

    async def perform_send(self, send_type, data, pro_type, recipient, extra_data):
        """Perform the actual sending of the `data`."""
        async with insecure_channel(f"{self.host}:{self.port}") as channel:
            CONTROLLER_STUB.channel = channel
            CONTROLLER_STUB.ready()
            RPCMethod = getattr(CONTROLLER_STUB, RPC_METHOD_NAME, None)
            if RPCMethod:
                # Convert `data` to proto struct
                data_struct = Struct()
                data_struct.update(data)

                # Assign attributes to request message
                REQUEST_MESSAGE.send_type = send_type
                REQUEST_MESSAGE.sender_unit = self.sender_unit
                REQUEST_MESSAGE.data.update(data_struct)
                REQUEST_MESSAGE.pro_type = pro_type
                REQUEST_MESSAGE.recipient = recipient
                REQUEST_MESSAGE.extra_data = extra_data

                # Call rpc method
                response = await RPCMethod(REQUEST_MESSAGE)

                # Clear the request message for future use
                REQUEST_MESSAGE.Clear()

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

                return response
            else:
                raise ValidationError("Invalid RPC method name.")

    @validate_call
    async def send_message(
        self,
        *,
        data: dict,
        recipient: IranianPhoneNumber | EmailStr,
        extra_data: str,
        pro_type: str,
    ):
        """Send a particular message containing `data` to the recipient.

        If the `recipient` is a valid email/mobile number, an email/sms will be sent."""

        # Determine the send type based on the recipient
        send_type = self.determine_send_type(recipient)

        # Perform send
        return await self.perform_send(send_type, data, pro_type, recipient, extra_data)

    @validate_call
    async def send_login(self, *, otp: str, recipient: IranianPhoneNumber | EmailStr):
        logger.debug(f"sending login otp to {recipient}")
        data = {"otp": otp}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Login OTP To User",
            pro_type=EventProTypes.LOGIN,
        )

    @validate_call
    async def send_register(
        self, *, otp: str, recipient: IranianPhoneNumber | EmailStr
    ):
        logger.debug(f"sending register otp to {recipient}")
        data = {"otp": otp}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Register OTP To User",
            pro_type=EventProTypes.REGISTER,
        )

    @validate_call
    async def send_welcome(
        self,
        *,
        recipient: IranianPhoneNumber | EmailStr,
        user_name: str,
        discount_code: str,
        discount_percentage: int,
    ):
        logger.debug(f"sending welcome notify to {recipient}")
        data = {
            "user": user_name,
            "discount_code": discount_code,
            "discount_percent": discount_percentage,
        }
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Welcome Notify to User",
            pro_type=EventProTypes.WELCOME,
        )

    @validate_call
    async def send_discount_1mo_after_reg(
        self,
        *,
        recipient: IranianPhoneNumber | EmailStr,
        user_name: str,
        discount_code: str,
        validity_duration: str,
    ):
        logger.debug(f"sending discount 1 month after registration to {recipient}")
        data = {
            "user": user_name,
            "discount_code": discount_code,
            "validity_duration": validity_duration,
        }
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Discount 1 month after registration to User",
            pro_type=EventProTypes.DISCOUNT_1MO_AFTER_REG,
        )

    @validate_call
    async def send_hbd(
        self,
        *,
        recipient: IranianPhoneNumber | EmailStr,
        user_name: str,
        discount_code: str,
        discount_percentage: int,
    ):
        logger.debug(f"sending happy birthday to {recipient}")
        data = {
            "user": user_name,
            "discount_code": discount_code,
            "discount_percent": discount_percentage,
        }
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Happy birthday to User",
            pro_type=EventProTypes.HAPPY_BIRTHDAY,
        )

    @validate_call
    async def send_cert_submit(
        self, *, recipient: IranianPhoneNumber | EmailStr, user_name: str, date: str
    ):
        logger.debug(f"sending certificate submit to {recipient}")
        data = {"user": user_name, "date": date}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending certificate submit to User",
            pro_type=EventProTypes.CERTIFICATE_SUBMIT,
        )

    @validate_call
    async def send_cert_edit(
        self, *, recipient: IranianPhoneNumber | EmailStr, user_name: str
    ):
        logger.debug(f"sending certificate edit to {recipient}")
        data = {"user": user_name}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending certificate edit to User",
            pro_type=EventProTypes.CERTIFICATE_EDIT,
        )

    @validate_call
    async def send_edu_sup_inform(
        self, *, recipient: IranianPhoneNumber | EmailStr, user_name: str, course: str
    ):
        logger.debug(f"sending master course to {recipient}")
        data = {"user": user_name, "course": course}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Master Course to User",
            pro_type=EventProTypes.MASTER_COURSE_INFORM,
        )

    @validate_call
    async def send_init_course_reg(
        self,
        *,
        recipient: IranianPhoneNumber | EmailStr,
        user_name: str,
        support_phone_number: str | int,
    ):
        logger.debug(f"sending init course register to {recipient}")
        data = {"user": user_name, "support_phone_number": support_phone_number}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Init Course Register to User",
            pro_type=EventProTypes.INITIAL_REGISTER,
        )

    @validate_call
    async def send_roadmap(
        self, *, recipient: IranianPhoneNumber | EmailStr, link: HttpUrl, course: str
    ):
        logger.debug(f"sending roadmap to {recipient}")
        data = {"link": link, "course": course}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending RoadMap to User",
            pro_type=EventProTypes.ROAD_MAP,
        )

    @validate_call
    async def send_success_consult_req(
        self, *, recipient: IranianPhoneNumber | EmailStr, user_name: str, course: str
    ):
        logger.debug(f"sending successful consult request notify to {recipient}")
        data = {"user": user_name, "course": course}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Successful Consult Request Notify to User",
            pro_type=EventProTypes.CONSULT_REQUEST,
        )

    @validate_call
    async def send_discount(
        self,
        *,
        recipient: IranianPhoneNumber | EmailStr,
        user_name: str,
        course: str,
        support_phone_number: str,
        discount_code: str,
        discount_percentage: int,
    ):
        logger.debug(f"sending dicount notify to {recipient}")
        data = {
            "user": user_name,
            "course": course,
            "support_phone_number": support_phone_number,
            "discount_code": discount_code,
            "discount_percent": discount_percentage,
        }
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending Discount Notify to User",
            pro_type=EventProTypes.DISCOUNT,
        )

    @validate_call
    async def send_master_course_reg_form(
        self, *, recipient: IranianPhoneNumber | EmailStr, link: HttpUrl
    ):
        logger.debug(f"sending master course register form to {recipient}")
        data = {"link": str(link)}
        return await self.send_message(
            data=data,
            recipient=recipient,
            extra_data="Sending master course register form to User",
            pro_type=EventProTypes.MASTER_COURSE_REGISTER_FORM,
        )
