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


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 resolve_project_by_name(name):
    if _is_cloud():
        res = request("GET", "/rest/api/3/project/search", params={"query": name})
        candidates = res.get("values") or []
    else:
        res = request("GET", "/rest/api/2/project")
        candidates = [p for p in (res or []) if str(p.get("name") or "").lower() == name.lower()]
    if len(candidates) == 0:
        raise Exception("no project found with name " + name)
    if len(candidates) > 1:
        raise Exception("multiple projects match name " + name)
    return candidates[0]


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    fields = {}

    summary = str(inputs.get("summary") or "").strip()
    if not summary:
        raise Exception("summary is required")
    fields["summary"] = summary

    project_key = str(inputs.get("project_key") or "").strip()
    project_name = str(inputs.get("project_name") or "").strip()
    if project_key:
        fields["project"] = {"key": project_key}
    elif project_name:
        proj = resolve_project_by_name(project_name)
        fields["project"] = {"key": proj.get("key")}
    else:
        raise Exception("project_key or project_name is required")

    issue_type_id = str(inputs.get("issue_type_id") or "").strip()
    issue_type_name = str(inputs.get("issue_type_name") or "").strip()
    if issue_type_id:
        fields["issuetype"] = {"id": issue_type_id}
    elif issue_type_name:
        fields["issuetype"] = {"name": issue_type_name}
    else:
        raise Exception("issue_type_name or issue_type_id is required")

    description = str(inputs.get("description") or "").strip()
    if description:
        fields["description"] = adf(description)

    priority = str(inputs.get("priority") or "").strip()
    if priority:
        fields["priority"] = {"name": priority}

    labels = str(inputs.get("labels") or "").strip()
    if labels:
        fields["labels"] = [x.strip() for x in labels.split(",") if x.strip()]

    components = str(inputs.get("components") or "").strip()
    if components:
        fields["components"] = [{"name": c.strip()} for c in components.split(",") if c.strip()]

    due_date = str(inputs.get("due_date") or "").strip()
    if due_date:
        fields["duedate"] = due_date

    assignee_id = str(inputs.get("assignee_id") or "").strip()
    assignee = str(inputs.get("assignee") or "").strip()
    if assignee_id:
        fields["assignee"] = {"accountId": assignee_id}
    elif assignee:
        fields["assignee"] = {"name": assignee}

    fields_json = str(inputs.get("fields_json") or "").strip()
    if fields_json:
        extra = json.loads(fields_json)
        if not isinstance(extra, dict):
            raise Exception("fields_json must be a JSON object")
        fields.update(extra)

    res = request("POST", "/rest/api/" + _api() + "/issue", body={"fields": fields})
    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)
