import json, os, sys, base64, ssl, uuid, 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 _ctx(cfg):
    if cfg.get("insecure"):
        c = ssl.create_default_context()
        c.check_hostname = False
        c.verify_mode = ssl.CERT_NONE
        return c
    return None


def _headers(cfg, extra=None):
    h = {"Accept": "application/json", "Authorization": "Token " + str(cfg.get("api_token", ""))}
    if extra:
        h.update(extra)
    return h


def request(method, path, cfg, form=None):
    url = str(cfg.get("base_url", "")).rstrip("/") + path
    data = None
    extra = {}
    if form is not None:
        data = urllib.parse.urlencode(form).encode("utf-8")
        extra["Content-Type"] = "application/x-www-form-urlencoded"
    req = urllib.request.Request(url, data=data, headers=_headers(cfg, extra), method=method)
    with urllib.request.urlopen(req, timeout=120, context=_ctx(cfg)) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def multipart(fields, file_field, file_name, file_bytes):
    boundary = "----riposte" + uuid.uuid4().hex
    parts = []
    for k, v in (fields or {}).items():
        parts.append(("--" + boundary + "\r\n"
                      'Content-Disposition: form-data; name="' + k + '"\r\n\r\n' + str(v) + "\r\n").encode("utf-8"))
    parts.append(("--" + boundary + "\r\n"
                  'Content-Disposition: form-data; name="' + file_field + '"; filename="' + file_name + '"\r\n'
                  "Content-Type: application/octet-stream\r\n\r\n").encode("utf-8"))
    parts.append(file_bytes)
    parts.append(("\r\n--" + boundary + "--\r\n").encode("utf-8"))
    return b"".join(parts), "multipart/form-data; boundary=" + boundary


def request_multipart(path, cfg, fields, file_field, file_name, file_bytes):
    url = str(cfg.get("base_url", "")).rstrip("/") + path
    data, content_type = multipart(fields, file_field, file_name, file_bytes)
    req = urllib.request.Request(url, data=data, headers=_headers(cfg, {"Content-Type": content_type}), method="POST")
    with urllib.request.urlopen(req, timeout=180, context=_ctx(cfg)) 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)


def main(cfg, inputs):
    task_id = inputs.get("task_id")
    if not task_id:
        raise Exception("task_id is required")
    q = lambda v: urllib.parse.quote(str(v), safe="")
    return request("GET", "/apiv2/tasks/view/" + q(task_id) + "/", cfg)


_run(main)
