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


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


def _base():
    return str(_cfg().get("server_url") or "https://jbxcloud.joesecurity.org").rstrip("/") + "/api/v2"


def post_form(path, fields):
    body = dict(fields)
    body["apikey"] = str(_cfg().get("api_key") or "")
    body["accept-tac"] = "1"
    data = urllib.parse.urlencode({k: str(v) for k, v in body.items() if v not in (None, "")}).encode("utf-8")
    req = urllib.request.Request(_base() + path, data=data,
                                 headers={"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"},
                                 method="POST")
    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", "{}"))
    file_name = inputs.get("file_name")
    content_base64 = inputs.get("content_base64")
    if not file_name:
        raise Exception("file_name is required")
    if not content_base64:
        raise Exception("content_base64 is required")
    systems = inputs.get("systems")
    internet_access = inputs.get("internet_access", True)

    fields = {
        "apikey": str(_cfg().get("api_key") or ""),
        "accept-tac": "1",
        "internet-access": "1" if internet_access else "0",
    }
    if systems:
        fields["systems"] = systems

    boundary = "----riposte" + uuid.uuid4().hex
    parts = []
    for name, value in fields.items():
        parts.append((
            "--" + boundary + "\r\n"
            'Content-Disposition: form-data; name="' + str(name) + '"\r\n\r\n' +
            str(value) + "\r\n"
        ).encode("utf-8"))
    parts.append((
        "--" + boundary + "\r\n"
        'Content-Disposition: form-data; name="sample"; filename="' + str(file_name) + '"\r\n'
        "Content-Type: application/octet-stream\r\n\r\n"
    ).encode("utf-8"))
    parts.append(base64.b64decode(content_base64))
    parts.append(("\r\n--" + boundary + "--\r\n").encode("utf-8"))
    data = b"".join(parts)

    req = urllib.request.Request(_base() + "/submission/new", data=data,
                                 headers={"Accept": "application/json",
                                          "Content-Type": "multipart/form-data; boundary=" + boundary},
                                 method="POST")
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read()
        res = json.loads(raw) if raw else {}
    print(json.dumps(res))


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)
