"""
WhatsApp messaging via Twilio WhatsApp API.

Credentials come from CMS Settings and from nowhere else. There is no .env
fallback: a file on disk travels into backups and synced folders, and these
are live sending credentials.
"""
import logging
import requests

log = logging.getLogger(__name__)


def _credentials():
    """Twilio credentials from Settings. Blank means WhatsApp is off."""
    from apps.pages.api_keys import get_twilio_credentials
    account_sid, auth_token, from_number = get_twilio_credentials()
    return {
        'account_sid': account_sid,
        'auth_token':  auth_token,
        'from_number': from_number,
    }


def send_whatsapp(to: str, message: str) -> bool:
    """
    Send a WhatsApp message via Twilio.

    Args:
        to:      Recipient phone in E.164 format (+447791065650)
        message: Message body text

    Returns:
        True on success, False on failure.
    """
    creds = _credentials()
    if not creds['account_sid'] or not creds['auth_token'] or not creds['from_number']:
        log.warning('Twilio WhatsApp credentials not configured — message skipped.')
        return False

    from_wa = f"whatsapp:{creds['from_number']}" if not creds['from_number'].startswith('whatsapp:') else creds['from_number']
    to_wa   = f"whatsapp:{to}" if not to.startswith('whatsapp:') else to

    try:
        resp = requests.post(
            f"https://api.twilio.com/2010-04-01/Accounts/{creds['account_sid']}/Messages.json",
            auth=(creds['account_sid'], creds['auth_token']),
            data={
                'From': from_wa,
                'To':   to_wa,
                'Body': message,
            },
            timeout=10,
        )
        if resp.status_code in (200, 201):
            return True
        log.error('Twilio WhatsApp error: HTTP %s — %s', resp.status_code, resp.text)
        return False
    except Exception as exc:
        log.error('Twilio WhatsApp exception: %s', exc)
        return False
