"""
SMS via Twilio REST API.
Credentials are read from CMS Settings (DB) first, then .env fallback.
"""
import logging
import requests
from django.conf import settings

log = logging.getLogger(__name__)


def _credentials():
    """Twilio credentials from Settings. Never .env."""
    account_sid = auth_token = sms_from = ''
    try:
        from apps.pages.models import SiteSettings
        from apps.tenants.models import Tenant
        site = SiteSettings.load(Tenant.objects.filter(is_master=True).first())
        if site:
            account_sid = site.twilio_account_sid or ''
            auth_token  = site.twilio_auth_token or ''
            sms_from    = getattr(site, 'twilio_sms_from', '') or ''
    except Exception:
        pass
    return {
        'account_sid': account_sid,
        'auth_token':  auth_token,
        'sms_from':    sms_from,
    }


def send_sms(to: str, message: str) -> bool:
    """
    Send an SMS 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['sms_from']:
        log.warning('Twilio SMS credentials not configured — message skipped.')
        return False

    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': creds['sms_from'],
                'To':   to,
                'Body': message,
            },
            timeout=10,
        )
        if resp.status_code in (200, 201):
            return True
        log.error('Twilio SMS error: HTTP %s — %s', resp.status_code, resp.text)
        return False
    except Exception as exc:
        log.error('Twilio SMS exception: %s', exc)
        return False
