"""No console provider: production OTPs are never printed or returned."""
import requests
from rest_framework.exceptions import APIException, ValidationError
from .security_config import value


class SMSUnavailable(APIException):
    status_code=503
    default_detail='SMS is unavailable. Configure a provider first.'


def configured():
    return bool(value('ACCOUNT_SMS_PROVIDER')=='twilio' and value('ACCOUNT_TWILIO_SID')
        and value('ACCOUNT_TWILIO_TOKEN') and value('ACCOUNT_SMS_FROM'))


def normalize(phone):
    import re
    if not isinstance(phone,str) or not re.fullmatch(r'\+[1-9][0-9]{7,14}',phone):
        raise ValidationError('Use an international phone number such as +989121234567.')
    return phone


def send(phone, code):
    if not configured():
        raise SMSUnavailable()
    sid=value('ACCOUNT_TWILIO_SID')
    try:
        response=requests.post(f'https://api.twilio.com/2010-04-01/Accounts/{sid}/Messages.json',
            auth=(sid,value('ACCOUNT_TWILIO_TOKEN')),
            data={'To':phone,'From':value('ACCOUNT_SMS_FROM'),'Body':f'FTG login verification: {code}. Expires in 5 minutes. Never share this code.'},timeout=10)
        if response.status_code not in (200,201):
            raise SMSUnavailable()
    except requests.RequestException as exc:
        raise SMSUnavailable() from exc
