#!/usr/bin/env python3
"""Fetch one Jira bug and print normalized JSON the agent can triage.

Usage: python fetch_jira.py VWO-48 > bug.json

Reads JIRA_BASE_URL / JIRA_EMAIL / JIRA_API_TOKEN from the environment. Never
hard-code the token. Stdlib only.
"""
import os, sys, json, base64, urllib.request


def adf_to_text(node):
    """Atlassian Document Format -> plain text (recursive, best-effort)."""
    if node is None:
        return ""
    if isinstance(node, str):
        return node
    out = []
    if node.get("text"):
        out.append(node["text"])
    for ch in node.get("content", []) or []:
        out.append(adf_to_text(ch))
    sep = "\n" if node.get("type") in ("paragraph", "listItem", "heading") else ""
    return sep.join(p for p in out if p)


def main():
    if len(sys.argv) < 2:
        sys.exit("usage: python fetch_jira.py <BUG-KEY>")
    key = sys.argv[1]
    base = os.environ["JIRA_BASE_URL"].rstrip("/")     # https://your.atlassian.net
    email = os.environ["JIRA_EMAIL"]
    token = os.environ["JIRA_API_TOKEN"]
    auth = base64.b64encode(f"{email}:{token}".encode()).decode()

    fields = "summary,description,issuetype,priority,status,labels,components,reporter,created"
    url = f"{base}/rest/api/3/issue/{key}?fields={fields}"
    req = urllib.request.Request(url, headers={
        "Authorization": f"Basic {auth}", "Accept": "application/json"})
    with urllib.request.urlopen(req) as r:
        data = json.load(r)

    f = data.get("fields", {})
    bug = {
        "id": data.get("key", key),
        "title": f.get("summary", ""),
        "reporter": (f.get("reporter") or {}).get("displayName", ""),
        "status": (f.get("status") or {}).get("name", ""),
        "reported_priority": (f.get("priority") or {}).get("name", ""),
        "type": (f.get("issuetype") or {}).get("name", ""),
        "labels": f.get("labels", []),
        "components": [c.get("name") for c in (f.get("components") or [])],
        "description": adf_to_text(f.get("description")),
        "url": f"{base}/browse/{data.get('key', key)}",
    }
    print(json.dumps(bug, indent=2))


if __name__ == "__main__":
    main()
