import base64, json, mimetypes, os, sys, urllib.parse, urllib.request, urllib.error


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


def _headers(cfg):
    h = {"Accept": "application/json", "Content-Type": "application/json"}
    if str(cfg.get("auth_type") or "basic").lower() == "oauth":
        data = urllib.parse.urlencode({
            "grant_type": "password",
            "client_id": cfg.get("client_id", ""),
            "client_secret": cfg.get("client_secret", ""),
            "username": cfg.get("username", ""),
            "password": cfg.get("password", ""),
        }).encode("utf-8")
        req = urllib.request.Request(
            cfg.get("url", "").rstrip("/") + "/oauth_token.do", data=data,
            headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}, method="POST")
        with urllib.request.urlopen(req, timeout=60) as r:
            tok = json.loads(r.read())
        if not tok.get("access_token"):
            raise Exception("OAuth token request failed: " + json.dumps(tok))
        h["Authorization"] = "Bearer " + tok["access_token"]
    else:
        cred = (cfg.get("username", "") + ":" + cfg.get("password", "")).encode("utf-8")
        h["Authorization"] = "Basic " + base64.b64encode(cred).decode("ascii")
    return h


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    ticket_id = str(inputs.get("id") or "")
    if not ticket_id:
        raise Exception("id is required")
    cfg = _cfg()
    table = str(inputs.get("table_name") or cfg.get("ticket_type") or "incident")
    file_name = str(inputs.get("file_name") or "")
    if not file_name:
        raise Exception("file_name is required")
    url = cfg.get("url", "").rstrip("/") + "/api/now/attachment/file?" + urllib.parse.urlencode({
        "table_name": table,
        "table_sys_id": ticket_id,
        "file_name": file_name,
    })
    headers = _headers(cfg)
    headers["Content-Type"] = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
    body = base64.b64decode(inputs["content_base64"])
    req = urllib.request.Request(url, data=body, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read()
    print(json.dumps(json.loads(raw) if raw else {}))


try:
    main()
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)
