import json, os, sys, time, base64, http.cookiejar
import urllib.parse, urllib.request, urllib.error


def _cfg():
    return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))


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


def _auth(cfg):
    raw = str(cfg.get("access_id", "")) + ":" + str(cfg.get("access_key", ""))
    return "Basic " + base64.b64encode(raw.encode("utf-8")).decode("utf-8")


def _base(cfg):
    return str(cfg.get("base_url", "")).rstrip("/") + "/api/v1"


class Client:
    def __init__(self, cfg):
        self.cfg = cfg
        self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))

    def call(self, method, path, body=None, params=None):
        url = _base(self.cfg) + path
        if params:
            clean = {k: v for k, v in params.items() if v not in (None, "")}
            if clean:
                url += "?" + urllib.parse.urlencode(clean)
        data = json.dumps(body).encode("utf-8") if body is not None else None
        headers = {"Authorization": _auth(self.cfg), "Accept": "application/json"}
        if data is not None:
            headers["Content-Type"] = "application/json"
        req = urllib.request.Request(url, data=data, headers=headers, method=method)
        with self.opener.open(req, timeout=60) as r:
            raw = r.read()
            return json.loads(raw) if raw else {}


def _run(fn):
    try:
        client = Client(_cfg())
        print(json.dumps(fn(client, _inputs())))
    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)


q = lambda v: urllib.parse.quote(str(v), safe="")


def main(client, inputs):
    query = inputs.get("query")
    if not query:
        raise Exception("query is required")
    from_time = inputs.get("from_time")
    if not from_time:
        raise Exception("from_time is required")
    to_time = inputs.get("to_time")
    if not to_time:
        raise Exception("to_time is required")
    limit = inputs.get("limit")
    limit = int(limit) if limit not in (None, "") else 100

    job = client.call("POST", "/search/jobs", body={"query": query, "from": from_time, "to": to_time, "timeZone": "UTC"})
    job_id = job.get("id")
    if not job_id:
        raise Exception("failed to create search job: " + json.dumps(job))

    state = None
    for _ in range(60):
        status = client.call("GET", "/search/jobs/" + q(job_id))
        state = status.get("state")
        if state == "DONE GATHERING RESULTS":
            break
        if state == "CANCELLED":
            raise Exception("search job cancelled")
        time.sleep(2)

    messages = client.call("GET", "/search/jobs/" + q(job_id) + "/messages", params={"offset": 0, "limit": limit})

    try:
        client.call("DELETE", "/search/jobs/" + q(job_id))
    except Exception:
        pass

    return {"job_id": job_id, "state": state, "messages": messages}


_run(main)
