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


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


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


def _ctx(cfg):
    if cfg.get("insecure"):
        c = ssl.create_default_context()
        c.check_hostname = False
        c.verify_mode = ssl.CERT_NONE
        return c
    return None


def obfuscate_api_key(api_key):
    now = str(int(time.time() * 1000))
    n = now[-6:]
    r = str(int(n) >> 1).zfill(6)
    key = ""
    for i in range(len(n)):
        key += api_key[int(n[i])]
    for j in range(len(r)):
        key += api_key[int(r[j]) + 2]
    return now, key


class Client:
    def __init__(self, cfg):
        self.cfg = cfg
        self.base = str(cfg.get("cloud", "")).rstrip("/") + "/api/v1"
        self.ctx = _ctx(cfg)
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),
            urllib.request.HTTPSHandler(context=self.ctx) if self.ctx else urllib.request.HTTPSHandler(),
        )

    def call(self, method, path, body=None, params=None):
        url = self.base + path
        if params:
            url += "?" + urllib.parse.urlencode(params)
        data = json.dumps(body).encode("utf-8") if body is not None else None
        headers = {"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 login(self):
        ts, obf = obfuscate_api_key(str(self.cfg.get("api_key", "")))
        body = {
            "apiKey": obf,
            "username": self.cfg.get("username", ""),
            "password": self.cfg.get("password", ""),
            "timestamp": ts,
        }
        return self.call("POST", "/authenticatedSession", body=body)

    def logout(self):
        try:
            self.call("DELETE", "/authenticatedSession")
        except Exception:
            pass


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


def main(client, inputs):
    result = client.call("POST", "/status/activate")
    if not result:
        return {"ok": True}
    return result


_run(main)
