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

SEVERITIES = ["low", "medium", "high", "critical"]


def request(method, url, headers):
    req = urllib.request.Request(url, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=90) as resp:
        raw = resp.read()
        return json.loads(raw) if raw else {}


def qs(params):
    clean = {}
    for k, v in params.items():
        if v is None or v == "" or v == []:
            continue
        clean[k] = v
    return ("?" + urllib.parse.urlencode(clean)) if clean else ""


def main():
    secrets = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    base = secrets.get("url", "").rstrip("/")
    headers = {
        "Authorization": "Token " + secrets.get("api_token", ""),
        "Accept": "application/json",
        "Content-Type": "application/json",
    }
    min_sev = str(inputs.get("min_severity") or "low").lower()
    level = ",".join(SEVERITIES[SEVERITIES.index(min_sev):]) if min_sev in SEVERITIES else ",".join(SEVERITIES)
    params = {
        "ordering": "-last_seen",
        "level": level,
        "limit": int(inputs.get("limit") or 100),
        "offset": 0,
        "status": inputs.get("status"),
        "creation_date__gte": inputs.get("created_after"),
    }
    url = base + "/api/data/alert/alert/Threat/" + qs(params)
    print(json.dumps(request("GET", url, headers)))


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)
