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


def request(method, url, headers, body=None):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=60) 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
        if isinstance(v, bool):
            v = "true" if v else "false"
        clean[k] = v
    return ("?" + urllib.parse.urlencode(clean)) if clean else ""


def csv(v):
    return [x.strip() for x in str(v or "").split(",") if x.strip()]


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",
    }

    hostname = inputs.get("hostname")
    fd = inputs.get("from_date")
    td = inputs.get("to_date")
    limit = int(inputs.get("limit") or 3)
    counts = {}
    for (system, path, extra) in [
        ("windows", "/api/data/telemetry/authentication/AuthenticationWindows/", {"windows.logon_type": 2}),
        ("linux", "/api/data/telemetry/authentication/AuthenticationLinux/", {}),
        ("macos", "/api/data/telemetry/authentication/AuthenticationMacos/", {}),
    ]:
        params = {
            "agent.hostname": hostname,
            "@event_create_date__gte": fd,
            "@event_create_date__lte": td,
        }
        params.update(extra)
        data = request("GET", base + path + qs(params), headers)
        for a in data.get("results", []):
            u = a.get("target_username")
            if u:
                counts[(system, u)] = counts.get((system, u), 0) + 1
    ranked = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)
    out = [{"Username": u, "System": s, "Authentication attempts": c} for (s, u), c in ranked[:limit]]
    print(json.dumps(out))


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)
