# doja_sdk/client.py
import requests
import json
from .base import DojaBase
from .exceptions import DojaAPIError


class DojaClient(DojaBase):
    """
    DoJa WhatsApp Client - Send WhatsApp messages protected by DoJa License validation.
    Inherits license validation and consumption from DojaBase.
    """

    def __init__(self, doja_token: str, whatsapp_token: str, phone_id: str):
        """
        Initialize the DoJa WhatsApp Client.
        Validates the DoJa License before allowing access.
        """
        # Validate license via DojaBase
        super().__init__(doja_token)

        # Verify this license includes WhatsApp access
        self._check_channel_access("whatsapp")
        self.whatsapp_token = whatsapp_token
        self.phone_id = phone_id

        # Setup the WhatsApp Base URL
        self.base_url = f"https://graph.facebook.com/v22.0/{self.phone_id}/messages"
        self.headers = {
            "Authorization": f"Bearer {self.whatsapp_token}",
            "Content-Type": "application/json"
        }

    def _send_payload(self, payload: dict) -> dict:
        """Internal method to execute the HTTP POST to WhatsApp and deduct quota"""
        # Re-validate quota right before sending
        self._validate_license()

        try:
            response = requests.post(
                self.base_url,
                headers=self.headers,
                data=json.dumps(payload),
                timeout=10
            )

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

            res_json = response.json()

            # If the payload succeeded, Meta returns a messages array with IDs
            messages = res_json.get("messages", [])
            for msg in messages:
                wamid = msg.get("id")
                if wamid:
                    self._consume_whatsapp(wamid)

            return res_json

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

    def send_text(self, to: str, text: str):
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "text",
            "text": {"body": text}
        }
        return self._send_payload(payload)

    def send_document(self, to: str, url: str, caption: str = "", filename: str = ""):
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "document",
            "document": {
                "link": url,
                "caption": caption,
                "filename": filename
            }
        }
        return self._send_payload(payload)

    def send_image(self, to: str, url: str, caption: str = ""):
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "image",
            "image": {
                "link": url,
                "caption": caption
            }
        }
        return self._send_payload(payload)

    def send_interactive_button(self, to: str, body_text: str, buttons_list: list):
        """buttons_list: list of dicts. Example: [{"id": "b1", "title": "Yes"}]"""
        buttons = []
        for btn in buttons_list:
            buttons.append({
                "type": "reply",
                "reply": {
                    "id": btn["id"],
                    "title": btn["title"]
                }
            })

        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "interactive",
            "interactive": {
                "type": "button",
                "body": {"text": body_text},
                "action": {"buttons": buttons}
            }
        }
        return self._send_payload(payload)

    def send_interactive_list(self, to: str, body_text: str, button_text: str, sections: list):
        """Sends a native WhatsApp list selector."""
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "interactive",
            "interactive": {
                "type": "list",
                "body": {"text": body_text},
                "action": {
                    "button": button_text,
                    "sections": sections
                }
            }
        }
        return self._send_payload(payload)

    def send_location(self, to: str, latitude: float, longitude: float, name: str, address: str):
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "location",
            "location": {
                "latitude": latitude,
                "longitude": longitude,
                "name": name,
                "address": address
            }
        }
        return self._send_payload(payload)

    def send_template(
        self,
        to: str,
        template_name: str,
        language_code: str = "es",
        body_variables: list = None,
        header_image_url: str = None,
        header_text_variables: list = None,
    ):
        """
        Sends a pre-approved WhatsApp template message.

        Args:
            to:                    Recipient phone number (with country code).
            template_name:         The exact name of the approved template in Meta.
            language_code:         Language code registered in Meta (default: 'es').
            body_variables:        List of strings for {{1}}, {{2}}, ... body placeholders.
                                   Example: ["Juan", "10% descuento", "31 de marzo"]
            header_image_url:      URL of the image to use in the header component (optional).
            header_text_variables: List of strings for {{1}}, {{2}} header text placeholders (optional).

        Example (text-only template with body variables):
            client.send_template(
                to="525512345678",
                template_name="confirmacion_pedido",
                language_code="es",
                body_variables=["Juan", "#12345", "mañana"]
            )

        Example (template with image header):
            client.send_template(
                to="525512345678",
                template_name="promo_verano",
                language_code="es",
                header_image_url="https://mi-dominio.com/banner.jpg",
                body_variables=["30%", "31 de marzo"]
            )
        """
        components = []

        # Build header component if provided
        if header_image_url:
            components.append({
                "type": "header",
                "parameters": [
                    {"type": "image", "image": {"link": header_image_url}}
                ]
            })
        elif header_text_variables:
            components.append({
                "type": "header",
                "parameters": [
                    {"type": "text", "text": var} for var in header_text_variables
                ]
            })

        # Build body component if variables are provided
        if body_variables:
            components.append({
                "type": "body",
                "parameters": [
                    {"type": "text", "text": str(var)} for var in body_variables
                ]
            })

        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "template",
            "template": {
                "name": template_name,
                "language": {"code": language_code},
                "components": components
            }
        }
        return self._send_payload(payload)
