# doja_sdk/client.py
import requests
import json
from .exceptions import DojaAuthError, DojaAPIError

class DojaClient:
    def __init__(self, doja_token: str, whatsapp_token: str, phone_id: str):
        """
        Initialize the DoJa Client.
        Validates the DoJa License before allowing access.
        """
        self._doja_token = doja_token
        self.whatsapp_token = whatsapp_token
        self.phone_id = phone_id
        
        # 1. Validate the license key
        self._validate_license()
        
        # 2. 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 _validate_license(self):
        """
        Synchronous call to DoJa Central Server to validate the license.
        Throws DojaAuthError if validation fails.
        """
        # Note: In production, this points to your real validation server:
        # url = "https://api.dojaconsulting.cloud/v1/license/validate"
        
        # We simulate the API call here. In the future you will replace this with the real POST request.
        # response = requests.post(url, json={"license_key": self._doja_token})
        # For our v0.1.0 demo, we hardcode validation:
        
        if not self._doja_token.startswith("DOJA-SEC-"):
            raise DojaAuthError(
                "❌ DOJA LICENSE INVALID: The provided 'doja_token' is suspended, expired, or invalid. "
                "Contact contact@dojaconsulting.cloud to renew your license."
            )
        
        print(f"✅ DoJa License Validated: {self._doja_token[-4:]} (Active)")

    def _send_payload(self, payload: dict) -> dict:
        """Internal method to execute the HTTP POST to WhatsApp"""
        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())
                
            return response.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)
