import json, os, sys, base64, 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 _base(cfg):
    return "https://" + str(cfg.get("subdomain", "")) + ".zendesk.com/api/v2"


def _auth(cfg):
    raw = str(cfg.get("email", "")) + "/token:" + str(cfg.get("api_token", ""))
    return "Basic " + base64.b64encode(raw.encode("utf-8")).decode("utf-8")


def request(method, path, cfg, body=None, params=None):
    url = _base(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(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 urllib.request.urlopen(req, timeout=60) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


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):
    subject = str(inputs.get("subject", "")).strip()
    if not subject:
        raise Exception("subject is required")
    comment = str(inputs.get("comment", "")).strip()
    if not comment:
        raise Exception("comment is required")

    ticket = {"subject": subject, "comment": {"body": comment}}

    priority = inputs.get("priority")
    if priority:
        ticket["priority"] = priority

    ticket_type = inputs.get("type")
    if ticket_type:
        ticket["type"] = ticket_type

    tags = inputs.get("tags")
    if tags:
        tags_list = [s.strip() for s in str(tags).split(",") if s.strip()]
        if tags_list:
            ticket["tags"] = tags_list

    requester_email = inputs.get("requester_email")
    if requester_email:
        ticket["requester"] = {"email": requester_email}

    return request("POST", "/tickets.json", cfg, body={"ticket": ticket})


_run(main)
