# doja_sdk/base.py
import requests
import uuid
from .exceptions import DojaAuthError, DojaQuotaExceeded


class DojaBase:
    """
    Base class for all DoJa service clients.
    Handles license validation and message consumption against the DoJa Central Server.
    """

    def __init__(self, doja_token: str):
        self._doja_token = doja_token
        self.account_id = None
        self.account_name = None
        self.plan_tier = None
        self.subscription_status = None
        self.allowed_channels = []

        # Validate the license immediately on creation
        self._validate_license()

    def _validate_license(self):
        """
        Calls DoJa Central Server to validate the license key and quota.
        Raises DojaAuthError or DojaQuotaExceeded if validation fails.
        """
        url = "https://core.dojaconsulting.cloud/v1/license/validate"

        try:
            response = requests.post(
                url,
                json={"license_key": self._doja_token},
                timeout=10
            )

            if response.status_code == 404:
                raise DojaAuthError("DOJA LICENSE INVALID (404): LICENSE_NOT_FOUND. Comprueba que el token sea correcto.")

            elif response.status_code == 409:
                err_text = response.text
                if "MESSAGE_LIMIT_REACHED" in err_text:
                    raise DojaQuotaExceeded("DOJA QUOTA EXCEEDED (409): MESSAGE_LIMIT_REACHED. Renueva tu plan para seguir enviando.")
                elif "EMAIL_LIMIT_REACHED" in err_text:
                    raise DojaQuotaExceeded("DOJA QUOTA EXCEEDED (409): EMAIL_LIMIT_REACHED. Renueva tu plan para seguir enviando correos.")
                else:
                    raise DojaAuthError("DOJA LICENSE INVALID (409): LICENSE_NOT_ACTIVE. Tu licencia esta suspendida o inactiva.")

            elif response.status_code == 422:
                raise DojaAuthError("DOJA VALIDATION ERROR (422): El formato del token es invalido.")

            elif not response.ok:
                raise DojaAuthError(f"HTTP Error {response.status_code} al validar licencia.")

            data = response.json().get("data", {})

            if not data.get("valid", False):
                raise DojaAuthError(
                    "DOJA LICENSE INVALID: The provided 'doja_token' is suspended, expired, or invalid."
                )

            if not data.get("canSend", False):
                raise DojaQuotaExceeded(
                    "DOJA QUOTA EXCEEDED: Your license is valid, but your message quota has been exhausted."
                )

            self.account_id = data.get("accountId")
            self.account_name = data.get("accountName")
            self.plan_tier = data.get("planTier")
            self.subscription_status = data.get("subscriptionStatus")
            self.allowed_channels = data.get("allowedChannels", ["whatsapp", "email"])

            print(f"DoJa License Validated - Account: {self.account_name} | Plan: {self.plan_tier} | Quota: OK")

        except (DojaAuthError, DojaQuotaExceeded):
            raise
        except requests.exceptions.RequestException as e:
            raise DojaAuthError(f"Could not reach DoJa license server: {str(e)}")

    def _check_channel_access(self, channel: str):
        """
        Verifies that the current license includes access to the specified channel.
        Raises DojaAuthError if the channel is not included in the plan.
        """
        if channel not in self.allowed_channels:
            raise DojaAuthError(
                f"DOJA ACCESS DENIED: Your license does not include the '{channel}' channel. "
                f"Your plan covers: {', '.join(self.allowed_channels)}. "
                f"Contact contact@dojaconsulting.cloud to upgrade."
            )

    def _consume_whatsapp(self, message_id: str):
        """
        Calls DoJa Central Server to deduct 1 WhatsApp message.
        Endpoint: /v1/license/consume
        """
        if not message_id:
            message_id = f"wamid-{uuid.uuid4()}"

        url = "https://core.dojaconsulting.cloud/v1/license/consume"
        try:
            requests.post(
                url,
                json={
                    "license_key": self._doja_token,
                    "message_id": message_id,
                    "direction": "OUTBOUND",
                    "quantity": 1
                },
                timeout=5
            )
        except requests.exceptions.RequestException:
            pass

    def _consume_email(self, external_id: str, subject: str = "No Subject"):
        """
        Calls DoJa Central Server to deduct 1 Email.
        Endpoint: /v1/license/consume-email
        """
        if not external_id:
            external_id = f"email-uuid-{uuid.uuid4()}"

        url = "https://core.dojaconsulting.cloud/v1/license/consume-email"
        try:
            requests.post(
                url,
                json={
                    "license_key": self._doja_token,
                    "external_id": external_id,
                    "subject": subject
                },
                timeout=5
            )
        except requests.exceptions.RequestException:
            pass
