import json, os, sys, urllib.parse, urllib.request, urllib.error, ssl
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape, quoteattr


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 _base(cfg):
    server = str(cfg.get("server", "")).rstrip("/")
    port = cfg.get("port") or 443
    return server + ":" + str(port) + "/api/"


def _vsys(cfg):
    return cfg.get("vsys") or "vsys1"


def _xpath_addr_prefix(cfg):
    return ("/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='"
            + _vsys(cfg) + "']")


def api(cfg, params):
    p = dict(params)
    p["key"] = str(cfg.get("api_key", ""))
    url = _base(cfg) + "?" + urllib.parse.urlencode(p)
    req = urllib.request.Request(url, method="GET")
    with urllib.request.urlopen(req, timeout=90, context=_ctx(cfg)) as r:
        raw = r.read()
    text = raw.decode("utf-8", "replace")
    try:
        root = ET.fromstring(raw)
    except Exception:
        raise Exception("Invalid XML response: " + text[:500])
    if root.attrib.get("status") != "success":
        raise Exception("PAN-OS error: " + text[:800])
    return root, text


def _to_dict(elem):
    # Shallow XML→dict for returning results
    d = dict(elem.attrib)
    children = list(elem)
    if not children:
        if elem.text and elem.text.strip():
            d["_text"] = elem.text.strip()
        return d
    for c in children:
        cd = _to_dict(c)
        if c.tag in d:
            if not isinstance(d[c.tag], list):
                d[c.tag] = [d[c.tag]]
            d[c.tag].append(cd)
        else:
            d[c.tag] = cd
    return d


def _run(fn):
    try:
        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):
    ip = str(inputs.get("ip") or "").strip()
    if not ip:
        raise Exception("ip is required")

    tags = [s.strip() for s in str(inputs.get("tags") or "").split(",") if s.strip()]
    if not tags:
        raise Exception("tags is required")

    timeout_attr = ""
    timeout = inputs.get("timeout")
    if timeout not in (None, ""):
        try:
            t = int(timeout)
        except (TypeError, ValueError):
            t = 0
        if t > 0:
            timeout_attr = ' timeout="' + str(t) + '"'

    members = "".join(
        "<member" + timeout_attr + ">" + escape(tag) + "</member>" for tag in tags
    )

    uid_xml = (
        "<uid-message><version>1.0</version><type>update</type><payload><register>"
        "<entry ip=" + quoteattr(ip) + ' persistent="1"><tag>' + members + "</tag>"
        "</entry></register></payload></uid-message>"
    )

    api(cfg, {"type": "user-id", "vsys": _vsys(cfg), "cmd": uid_xml})

    return {"ok": True, "ip": ip, "tags": tags}


_run(main)
