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

TOKEN_URL = "https://oauth2.googleapis.com/token"
API = "https://gmail.googleapis.com/gmail/v1/users/me"


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


def _token():
    cfg = _cfg()
    refresh = str(cfg.get("refresh_token") or "")
    if not refresh:
        raise Exception("refresh_token is not set — run gmail-single-user-exchange-code and paste it into the config")
    data = urllib.parse.urlencode({
        "client_id": str(cfg.get("client_id") or ""),
        "client_secret": str(cfg.get("client_secret") or ""),
        "refresh_token": refresh,
        "grant_type": "refresh_token",
    }).encode("utf-8")
    req = urllib.request.Request(TOKEN_URL, 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("Token refresh failed: " + json.dumps(tok))
    return tok["access_token"]


def request(method, path, params=None, body=None, token=None):
    url = API + 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": "Bearer " + (token or _token())}
    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:
        raw = r.read()
        return json.loads(raw) if raw else {}


def collect_attachments(payload, out):
    for part in payload.get("parts", []) or []:
        collect_attachments(part, out)
    if payload.get("filename") and payload.get("body", {}).get("attachmentId"):
        out.append({
            "id": payload["body"]["attachmentId"],
            "name": payload.get("filename", ""),
            "mime_type": payload.get("mimeType", ""),
        })


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    mid = str(inputs.get("message_id") or "")
    if not mid:
        raise Exception("message_id is required")
    token = _token()
    full = request("GET", "/messages/" + urllib.parse.quote(mid), params={"format": "full"}, token=token)
    metas = []
    collect_attachments(full.get("payload", {}), metas)
    attachments = []
    for meta in metas:
        att = request("GET", "/messages/" + urllib.parse.quote(mid) + "/attachments/" + urllib.parse.quote(meta["id"]), token=token)
        raw = att.get("data", "")
        content = base64.urlsafe_b64decode((raw + "=" * (-len(raw) % 4)).encode("ascii")) if raw else b""
        attachments.append({
            "name": meta["name"],
            "mime_type": meta["mime_type"],
            "size": len(content),
            "content_base64": base64.b64encode(content).decode("ascii"),
        })
    print(json.dumps({"message_id": mid, "attachments": attachments}))


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)
