import json, os, sys, base64, ssl, 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 _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


class Client:
    def __init__(self, cfg):
        self.cfg = cfg
        self.base = str(cfg.get("base_url", "")).rstrip("/")
        self.ctx = _ctx(cfg)
        self.token = None
        self.domain_uuid = None

    def authenticate(self):
        creds = str(self.cfg.get("username", "")) + ":" + str(self.cfg.get("password", ""))
        basic = base64.b64encode(creds.encode("utf-8")).decode("utf-8")
        req = urllib.request.Request(self.base + "/api/fmc_platform/v1/auth/generatetoken",
                                     data=b"", headers={"Authorization": "Basic " + basic}, method="POST")
        with urllib.request.urlopen(req, timeout=60, context=self.ctx) as r:
            r.read()
            self.token = r.headers.get("X-auth-access-token")
            self.domain_uuid = r.headers.get("DOMAIN_UUID")
        if not self.token or not self.domain_uuid:
            raise Exception("Authentication failed: missing token or domain UUID")

    def _cfg_base(self):
        return self.base + "/api/fmc_config/v1/domain/" + self.domain_uuid

    def call(self, method, path, body=None, params=None):
        # path is relative to the domain config base, e.g. /object/hosts
        url = self._cfg_base() + 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 = {"X-auth-access-token": self.token, "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 urllib.request.urlopen(req, timeout=90, context=self.ctx) as r:
            raw = r.read()
            return json.loads(raw) if raw else {}


def _run(fn):
    try:
        cfg = _cfg()
        inputs = _inputs()
        client = Client(cfg)
        client.authenticate()
        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)


def main(client, inputs):
    client.call("GET", "/object/hosts", params={"limit": 1})
    return {"ok": True, "domain_uuid": client.domain_uuid}


_run(main)
