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

API = "https://api.any.run/v1"


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


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 = API + 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 {}


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    url = inputs.get("url")
    if not url:
        raise Exception("url is required")
    env_os = inputs.get("os") or "windows"
    env_bitness = inputs.get("env_bitness") or 64

    result = request("POST", "/analysis", form={"obj_type": "url", "obj_url": url, "env_os": env_os, "env_bitness": env_bitness})
    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)
