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


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


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


def _ctx():
    cfg = _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 request(method, path, cfg, inputs, body=None, extra_params=None):
    base = str(cfg.get("server", "")).rstrip("/") + "/api/v2"
    url = base + path
    params = {}
    vdom = (inputs.get("vdom") if inputs else None) or cfg.get("vdom")
    if vdom:
        params["vdom"] = vdom
    if extra_params:
        params.update(extra_params)
    if params:
        url += "?" + urllib.parse.urlencode(params)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Authorization": "Bearer " + str(cfg.get("api_key", "")), "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=60, context=_ctx()) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def _run(fn):
    try:
        cfg = _cfg()
        inputs = _inputs()
        print(json.dumps(fn(cfg, 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(cfg, inputs):
    name = inputs.get("name")
    if not name or not str(name).strip():
        raise Exception("name is required")
    raw_members = inputs.get("members")
    if not raw_members or not str(raw_members).strip():
        raise Exception("members is required")
    members_list = [m.strip() for m in str(raw_members).split(",") if m.strip()]
    if not members_list:
        raise Exception("members is required")

    body = {"member": [{"name": m} for m in members_list]}
    path = "/cmdb/firewall/addrgrp/" + urllib.parse.quote(str(name), safe="")
    return request("PUT", path, cfg, inputs, body=body)


_run(main)
