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


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


def _base():
    return str(_cfg().get("server_url") or "").rstrip("/") + "/rest"


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


def request(method, path, params=None, form=None):
    url = _base() + path
    p = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
    if p:
        url += ("&" if "?" in url else "?") + urllib.parse.urlencode(p)
    data = None
    headers = _headers()
    if form is not None:
        data = urllib.parse.urlencode({k: str(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=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


q = lambda v: urllib.parse.quote(str(v), safe="")


def main():
    args = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    submission_id = args.get("submission_id")
    if not submission_id:
        raise Exception("submission_id is required")
    result = request("GET", "/submission/" + q(submission_id))
    print(json.dumps(result))


try:
    main()
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)
