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


def _cfg():
    s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    base = str(s.get("url") or "https://api.sekoia.io").rstrip("/")
    headers = {"Authorization": "Bearer " + s.get("api_key", ""), "Content-Type": "application/json", "Accept": "application/json"}
    return base, headers


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


def request(method, path, body=None):
    base, headers = _cfg()
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(base + "/" + path.lstrip("/"), 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():
    inp = _inputs()
    body = {"earliest_time": inp.get("earliest_time"), "latest_time": inp.get("latest_time"), "term": inp.get("query")}
    if inp.get("max_last_events"):
        body["max_last_events"] = inp["max_last_events"]
    job = request("POST", "/v1/sic/conf/events/search/jobs", body=body)
    job_uuid = job.get("uuid")
    # Poll the job until it finishes (status == 2), bounded to stay within the run timeout.
    for _ in range(24):
        status = request("GET", "/v1/sic/conf/events/search/jobs/" + urllib.parse.quote(job_uuid, safe=""))
        if status.get("status") == 2:
            events = request("GET", "/v1/sic/conf/events/search/jobs/" + urllib.parse.quote(job_uuid, safe="") + "/events")
            print(json.dumps(events))
            return
        time.sleep(2)
    # Still running: hand back the job UUID so the caller can retrieve results later.
    print(json.dumps({"pending": True, "job_uuid": job_uuid, "message": "Event search still running; retrieve with events_results_query."}))


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)
