import json, os, sys, base64, urllib.parse, urllib.request, urllib.error


def _cfg():
    return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))


def _inputs():
    return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))


def _base(cfg):
    return "https://api.twilio.com/2010-04-01/Accounts/" + str(cfg.get("account_sid", ""))


def _auth(cfg):
    raw = str(cfg.get("account_sid", "")) + ":" + str(cfg.get("auth_token", ""))
    return "Basic " + base64.b64encode(raw.encode("utf-8")).decode("utf-8")


def request(method, path, cfg, form=None, params=None):
    url = _base(cfg) + path
    if params:
        clean = {k: v for k, v in params.items() if v not in (None, "")}
        if clean:
            url += "?" + urllib.parse.urlencode(clean)
    data = None
    headers = {"Authorization": _auth(cfg), "Accept": "application/json"}
    if form is not None:
        data = urllib.parse.urlencode({k: v for k, v in form.items() if v not in (None, "")}).encode("utf-8")
        headers["Content-Type"] = "application/x-www-form-urlencoded"
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=60) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def _run(fn):
    try:
        print(json.dumps(fn(_cfg(), _inputs())))
    except urllib.error.HTTPError as e:
        print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
        sys.exit(1)
    except Exception as e:
        print(json.dumps({"error": str(e)}))
        sys.exit(1)


q = lambda v: urllib.parse.quote(str(v), safe="")
_from = lambda cfg, inputs: (inputs.get("from_number") or cfg.get("from_number"))


def main(cfg, inputs):
    to = inputs.get("to")
    if not to:
        raise Exception("to is required")
    frm = _from(cfg, inputs)
    if not frm:
        raise Exception("from_number is required (set a default or pass one)")
    twiml = inputs.get("twiml")
    url = inputs.get("url")
    if not twiml and not url:
        raise Exception("twiml or url is required")
    form = {"From": frm, "To": to}
    if twiml:
        form["Twiml"] = twiml
    elif url:
        form["Url"] = url
    return request("POST", "/Calls.json", cfg, form=form)


_run(main)
