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


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


def _is_cloud():
    return bool(str(_cfg().get("cloud_id") or "").strip())


def _api():
    return "3" if _is_cloud() else "2"


def _base():
    cfg = _cfg()
    root = str(cfg.get("server_url") or "https://api.atlassian.com/ex/jira").rstrip("/")
    cloud_id = str(cfg.get("cloud_id") or "").strip()
    return root + "/" + cloud_id if cloud_id else root


def _auth():
    cfg = _cfg()
    pat = str(cfg.get("pat") or "")
    if pat:
        return "Bearer " + pat
    cred = (str(cfg.get("username") or "") + ":" + str(cfg.get("api_key") or "")).encode("utf-8")
    return "Basic " + base64.b64encode(cred).decode("ascii")


def request(method, path, params=None, body=None, full_url=None, raw=False):
    url = full_url or (_base() + path)
    q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
    if q:
        url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Accept": "application/json", "Authorization": _auth()}
    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) as r:
        content = r.read()
        if raw:
            return content
        return json.loads(content) if content else {}


def issue_ref(inputs):
    ref = str(inputs.get("issue_id") or "") or str(inputs.get("issue_key") or "")
    if not ref:
        raise Exception("issue_id or issue_key is required")
    return urllib.parse.quote(ref, safe="")


def adf(text):
    # Jira Cloud (API v3) expects Atlassian Document Format for rich text; On-Prem (v2) takes plain text.
    if not _is_cloud():
        return text
    return {"type": "doc", "version": 1,
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    ref = issue_ref(inputs)
    file_name = str(inputs.get("file_name") or "")
    if not file_name:
        raise Exception("file_name is required")
    content_base64 = str(inputs.get("content_base64") or "")
    if not content_base64:
        raise Exception("content_base64 is required")

    boundary = "----riposte" + uuid.uuid4().hex
    content = base64.b64decode(content_base64)
    mime = mimetypes.guess_type(file_name)[0] or "application/octet-stream"

    body = (
        ("--" + boundary + "\r\n"
         + 'Content-Disposition: form-data; name="file"; filename="' + file_name + '"\r\n'
         + "Content-Type: " + mime + "\r\n\r\n").encode("utf-8")
        + content
        + ("\r\n--" + boundary + "--\r\n").encode("utf-8")
    )

    headers = {
        "Accept": "application/json",
        "Authorization": _auth(),
        # Jira requires this header for attachment uploads (XSRF check bypass).
        "X-Atlassian-Token": "no-check",
        "Content-Type": "multipart/form-data; boundary=" + boundary,
    }

    url = _base() + "/rest/api/" + _api() + "/issue/" + ref + "/attachments"
    req = urllib.request.Request(url, data=body, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read()
    res = json.loads(raw) if raw else {}
    print(json.dumps(res))


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)
