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

CONTAINS = "CONTAINS"
EQUALS = "EQUALS"
# (field, operator) pairs mirrored from the InsightIDR investigation search schema.
SEARCH = [
    ("actor_asset_hostname", CONTAINS),
    ("actor_user_name", CONTAINS),
    ("alert_mitre_t_codes", EQUALS),
    ("alert_rule_rrn", EQUALS),
    ("assignee_id", EQUALS),
    ("organization_id", EQUALS),
    ("priority", EQUALS),
    ("rrn", EQUALS),
    ("source", EQUALS),
    ("status", EQUALS),
    ("title", CONTAINS),
]
SORT_FIELDS = {
    "Created time": "created_time",
    "Priority": "priority",
    "RRN": "rrn",
    "Alert created time": "alerts_most_recent_created_time",
    "Alert detection created time": "alerts_most_recent_detection_created_time",
}


def _cfg():
    s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    region = str(s.get("region") or "us").strip().lower()
    base = "https://" + region + ".api.insight.rapid7.com/"
    headers = {"X-Api-Key": s.get("api_key", ""), "Content-Type": "application/json", "Accept": "application/json"}
    multi = str(s.get("is_multi_customer") or "").strip().lower() in ("1", "true", "yes")
    return base, headers, multi


def _inputs():
    return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))


def _list(v):
    if v in (None, ""):
        return []
    if isinstance(v, list):
        return [str(x).strip() for x in v if str(x).strip()]
    return [p.strip() for p in str(v).split(",") if p.strip()]


def request(method, path, params=None, body=None):
    base, headers, _ = _cfg()
    url = base + path.lstrip("/")
    if params:
        clean = {k: v for k, v in params.items() if v not in (None, "")}
        if clean:
            url += ("&" if "?" in url else "?") + urllib.parse.urlencode(clean, doseq=True)
    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=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def run():
    _, _, multi = _cfg()
    inp = _inputs()
    search = []
    for field, op in SEARCH:
        for value in _list(inp.get(field)):
            search.append({"field": field, "operator": op, "value": value})
    direction = str(inp.get("sort_direction") or "asc").upper()
    sort = [{"field": SORT_FIELDS.get(f, f), "order": direction} for f in _list(inp.get("sort"))]
    body = {"search": search, "sort": sort}
    if inp.get("start_time"):
        body["start_time"] = inp["start_time"]
    if inp.get("end_time"):
        body["end_time"] = inp["end_time"]
    params = {
        "index": inp.get("index") or "0",
        "size": inp.get("page_size") or inp.get("limit") or 50,
        "multi-customer": "true" if multi else None,
    }
    print(json.dumps(request("POST", "idr/v2/investigations/_search", params=params, body=body)))


try:
    run()
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)
