    def get_profile(self) -> dict:
        service = self._api()
        prof = service.users().getProfile(userId="me").execute()
        return {"email_address": prof.get("emailAddress"), "history_id": prof.get("historyId"),
                "messages_total": prof.get("messagesTotal"), "threads_total": prof.get("threadsTotal")}

    def verify_connection(self) -> dict:
        try:
            prof = self.get_profile()
            return {"ok": True, "email_address": prof.get("email_address"), "detail": "Gmail API connection verified."}
        except Exception as e:
            return {"ok": False, "detail": str(e)[:400]}


def build_gmail_client_from_account(account, oauth_token, client_config=None) -> GmailClient:
    """Build a GmailClient from DB rows (sync session context - worker uses sync ORM)."""
    cfg = client_config or resolve_client_config_for_account(account)
    return GmailClient(
        account_email=account.email,
        access_token=oauth_token.access_token,       # decrypted
        refresh_token=oauth_token.refresh_token,     # decrypted
        client_config=cfg,
        sending_method=account.sending_method,
        token_expiry=oauth_token.expires_at,
    )


def resolve_client_config_for_account(account) -> dict:
    """Resolve client config for an account: its imported config row or server default."""
    # Called from sync or async context; imports DB lazily.
    from app.db.session import SyncSession
    from app.models import OAuthClientConfig
    if account.oauth_config_id:
        with SyncSession() as s:
            cfg = s.get(OAuthClientConfig, account.oauth_config_id)
            if cfg and cfg.is_active:
