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 "").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 {}


def main():
    args = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    file_name = args.get("file_name")
    content_base64 = args.get("content_base64")
    tags = args.get("tags")
    if not file_name:
        raise Exception("file_name is required")
    if not content_base64:
        raise Exception("content_base64 is required")

    boundary = "----riposte" + uuid.uuid4().hex
    parts = []

    fields = {"tags": tags}
    for name, value in fields.items():
        if value not in (None, ""):
            parts.append(
                (
                    "--" + boundary + "\r\n"
                    + 'Content-Disposition: form-data; name="' + name + '"\r\n\r\n'
                    + str(value) + "\r\n"
                ).encode("utf-8")
            )

    file_bytes = base64.b64decode(content_base64)
    file_header = (
        "--" + boundary + "\r\n"
        + 'Content-Disposition: form-data; name="sample_file"; filename="' + file_name + '"\r\n'
        + "Content-Type: application/octet-stream\r\n\r\n"
    ).encode("utf-8")
    parts.append(file_header + file_bytes + b"\r\n")
    parts.append(("--" + boundary + "--\r\n").encode("utf-8"))

    body = b"".join(parts)
    url = _base() + "/sample/submit"
    headers = _headers({"Content-Type": "multipart/form-data; boundary=" + boundary})
    req = urllib.request.Request(url, data=body, headers=headers, 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)
