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"}
    if cfg.get("api_token"):
        h["Authorization"] = "Bearer " + str(cfg["api_token"])
    if extra:
        h.update(extra)
    return h


def request(method, path, cfg, body=None, form=None):
    url = str(cfg.get("base_url", "")).rstrip("/") + path
    data = None
    extra = {}
    if body is not None:
        data = json.dumps(body).encode("utf-8")
        extra["Content-Type"] = "application/json"
    elif 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):
    file_name = inputs.get("file_name")
    if not file_name:
        raise Exception("file_name is required")
    content_base64 = inputs.get("content_base64")
    if not content_base64:
        raise Exception("content_base64 is required")
    file_bytes = base64.b64decode(content_base64)
    return request_multipart("/tasks/create/file", cfg, {}, "file", file_name, file_bytes)


_run(main)
