import requests
from .exceptions import WhatsAppAPIError

class WhatsAppClient:
    """
    A client for sending WhatsApp messages using the Meta Cloud API.
    """
    def __init__(self, access_token: str, phone_number_id: str, business_account_id: str):
        """
        Initialize the WhatsAppClient.

        Args:
            access_token (str): Meta API access token.
            phone_number_id (str): WhatsApp phone number ID.
            business_account_id (str): WhatsApp business account ID.
        """
        self.access_token = access_token
        self.phone_number_id = phone_number_id
        self.business_account_id = business_account_id
        self.api_url = f"https://graph.facebook.com/v17.0/{self.phone_number_id}/messages"
        self.headers = {
            "Authorization": f"Bearer {self.access_token}",
            "Content-Type": "application/json"
        }

    def send_message(self, to: str, message: str):
        """
        Send a WhatsApp message.

        Args:
            to (str): Recipient's WhatsApp number (e.g., '+1234567890').
            message (str): The message text to send.

        Returns:
            dict: API response.

        Raises:
            ValueError: If input is invalid.
            WhatsAppAPIError: If the API call fails.
        """
        if not isinstance(to, str) or not to.startswith('+') or not to[1:].isdigit():
            raise ValueError("Recipient number must be in international format, e.g., '+1234567890'")
        if not isinstance(message, str) or not message.strip():
            raise ValueError("Message body cannot be empty.")
        payload = {
            "messaging_product": "whatsapp",
            "to": to,
            "type": "text",
            "text": {"body": message}
        }
        try:
            response = requests.post(self.api_url, headers=self.headers, json=payload)
            response.raise_for_status()
        except requests.RequestException as e:
            raise WhatsAppAPIError(f"Request failed: {e}") from e
        data = response.json()
        if 'error' in data:
            raise WhatsAppAPIError(f"API Error: {data['error']}")
        return data 