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

API = "https://analyze.intezer.com/api/v2-0"


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


def _token():
    data = json.dumps({"api_key": str(_cfg().get("api_key") or "")}).encode("utf-8")
    req = urllib.request.Request(API + "/get-access-token", data=data,
                                 headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST")
    with urllib.request.urlopen(req, timeout=60) as r:
        tok = json.loads(r.read())
    if not tok.get("result"):
        raise Exception("Token request failed: " + json.dumps(tok))
    return tok["result"]


def request(method, path, body=None, token=None):
    url = API + path
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Accept": "application/json", "Authorization": "Bearer " + (token or _token())}
    if data is not None:
        headers["Content-Type"] = "application/json"
    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", "{}"))
    analysis_id = args.get("analysis_id")
    if not analysis_id:
        raise Exception("analysis_id is required")
    result = request("GET", "/analyses/" + q(analysis_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)
