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

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 multipart(fields, file_field, file_name, file_bytes):
    boundary = "----riposte" + uuid.uuid4().hex
    parts = []
    for name, value in fields.items():
        parts.append(("--" + boundary + "\r\n"
                      + 'Content-Disposition: form-data; name="' + name + '"\r\n\r\n'
                      + str(value) + "\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 boundary, b"".join(parts)


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_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")
    env_os = inputs.get("os") or "windows"
    env_bitness = inputs.get("env_bitness") or 64

    fields = {"obj_type": "file", "env_os": env_os, "env_bitness": str(env_bitness)}
    boundary, body = multipart(fields, "file", file_name, base64.b64decode(content_base64))
    req = urllib.request.Request(
        API + "/analysis",
        data=body,
        headers=_headers({"Content-Type": "multipart/form-data; boundary=" + boundary}),
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read()
        result = json.loads(raw) if raw else {}
    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)
