import base64


def _gmail_message_headers(message: dict) -> dict[str, str]:
    normalized: dict[str, str] = {}
    for header in ((message.get("payload") or {}).get("headers") or []):
        raw_name = str(header.get("name") or "").strip()
        if not raw_name:
            continue
        canonical_name = "-".join(part.capitalize() for part in raw_name.split("-"))
        normalized[canonical_name] = str(header.get("value") or "")
    return normalized


def _gmail_decode_body_data(data: str) -> str:
    raw = str(data or "").strip()
    if not raw:
        return ""
    padding = "=" * (-len(raw) % 4)
    try:
        return base64.urlsafe_b64decode((raw + padding).encode("utf-8")).decode("utf-8", errors="replace")
    except Exception:
        return ""


def _gmail_extract_plain_text_body(payload: dict) -> str:
    value = dict(payload or {})
    mime_type = str(value.get("mimeType") or "")
    body = dict(value.get("body") or {})
    data = _gmail_decode_body_data(body.get("data", ""))
    if mime_type.startswith("text/plain") and data:
        return data
    parts = value.get("parts") or []
    for part in parts:
        text = _gmail_extract_plain_text_body(part)
        if text:
            return text
    if data:
        return data
    return ""


def _gmail_find_draft_by_message_id(service, message_id: str) -> dict | None:
    token = None
    target = str(message_id or "").strip()
    while True:
        kwargs = {"userId": "me", "maxResults": 100}
        if token:
            kwargs["pageToken"] = token
        resp = service.users().drafts().list(**kwargs).execute()
        for draft_stub in resp.get("drafts", []):
            draft = service.users().drafts().get(userId="me", id=draft_stub.get("id", ""), format="full").execute()
            message = draft.get("message") or {}
            if str(message.get("id") or "").strip() == target:
                return draft
        token = resp.get("nextPageToken")
        if not token:
            return None