"""Send checkout OTPs through the pharmacy's HTTPS SMS relay."""
import json
import os
from urllib.parse import urlsplit
from urllib.request import Request, build_opener
from core import Invalid
from gateway import NoRedirect

def configuration():
    address=os.environ.get('ASTHA_SMS_RELAY','')
    secret=os.environ.get('ASTHA_SMS_TOKEN','')
    try:
        parts=urlsplit(address)
        if parts.scheme=='https' and parts.hostname and not (parts.username or parts.password or parts.fragment) and secret:
            return address,secret
    except ValueError:
        pass
    return None

def send(phone,code):
    address,secret=configuration()
    payload=json.dumps({'to':'+88'+phone,'message':f'Astha Pharmacy verification code: {code}. Valid for 5 minutes.'}).encode()
    request=Request(address,data=payload,headers={'Content-Type':'application/json','Authorization':'Bearer '+secret})
    try:
        with build_opener(NoRedirect()).open(request,timeout=7) as response:
            if 200<=response.status<300:
                return
    except OSError:
        pass
    raise Invalid('SMS could not be sent. Try again shortly.')
