# doja_sdk/email_client.py
import requests
import base64
import os

from .base import DojaBase
from .exceptions import DojaAPIError


class DojaEmailClient(DojaBase):
    """
    DoJa Email Client - Send emails via Resend API, protected by DoJa License validation.

    Usage:
        from doja_sdk import DojaEmailClient

        email = DojaEmailClient(
            doja_token="your-doja-license",
            resend_api_key="re_123456789",
            from_address="no-reply@tuempresa.com"
        )

        email.send(
            to="cliente@empresa.com",
            subject="Bienvenido",
            body="Gracias por registrarte."
        )
    """

    RESEND_API_URL = "https://api.resend.com/emails"

    def __init__(
        self,
        doja_token: str,
        from_address: str,
    ):
        """
        Initialize the DoJa Email Client.

        Args:
            doja_token:      Your DoJa license key (which also serves as the Resend API Key).
            from_address:    Default sender address (must be verified in Resend).
        """
        # Validate DoJa license
        super().__init__(doja_token)

        # Verify this license includes Email access
        self._check_channel_access("email")

        self.from_address = from_address
        self._headers = {
            "Authorization": f"Bearer {self._doja_token}",
            "Content-Type": "application/json"
        }

    def send(
        self,
        to: str,
        subject: str,
        body: str,
        html: bool = False,
        from_address: str = None,
        cc: list = None,
        bcc: list = None,
        reply_to: str = None,
        attachments: list = None,
    ) -> dict:
        """
        Send an email via Resend API.

        Args:
            to:            Recipient email (string or comma-separated for multiple).
            subject:       Email subject line.
            body:          Email body content (plain text or HTML).
            html:          If True, body is treated as HTML. Default: False.
            from_address:  Override the default sender address.
            cc:            List of CC email addresses.
            bcc:           List of BCC email addresses.
            reply_to:      Reply-To email address.
            attachments:   List of file paths to attach.

        Returns:
            dict with Resend response (includes message id).

        Raises:
            DojaQuotaExceeded: If the license has no remaining messages.
            DojaAPIError: If Resend rejects the email.
        """
        # Re-validate quota before sending
        self._validate_license()

        sender = from_address or self.from_address

        # Build recipients
        if isinstance(to, str):
            to_list = [addr.strip() for addr in to.split(",")]
        else:
            to_list = to

        # Build Resend payload
        payload = {
            "from": sender,
            "to": to_list,
            "subject": subject,
        }

        # Body type
        if html:
            payload["html"] = body
        else:
            payload["text"] = body

        # Optional fields
        if cc:
            payload["cc"] = cc if isinstance(cc, list) else [cc]
        if bcc:
            payload["bcc"] = bcc if isinstance(bcc, list) else [bcc]
        if reply_to:
            payload["reply_to"] = reply_to

        # Attachments (Resend accepts base64 encoded files)
        if attachments:
            file_attachments = []
            for filepath in attachments:
                if not os.path.isfile(filepath):
                    raise DojaAPIError(f"Attachment not found: {filepath}")
                filename = os.path.basename(filepath)
                with open(filepath, "rb") as f:
                    content = base64.b64encode(f.read()).decode("utf-8")
                file_attachments.append({
                    "filename": filename,
                    "content": content,
                })
            payload["attachments"] = file_attachments

        # Send via Resend API
        try:
            response = requests.post(
                self.RESEND_API_URL,
                headers=self._headers,
                json=payload,
                timeout=10
            )

            if response.status_code not in [200, 201]:
                err_msg = f"Resend API Error {response.status_code}: {response.text}"
                raise DojaAPIError(err_msg, response.status_code, response.json())

            res_json = response.json()

        except requests.exceptions.RequestException as e:
            raise DojaAPIError(f"Email send failed: {str(e)}")

        # Consume 1 credit after successful send
        resend_id = res_json.get("id", None)
        self._consume_license(resend_id)

        return {
            "status": "sent",
            "id": resend_id,
            "to": to_list,
            "subject": subject,
            "from": sender
        }
