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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d1f304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
from __future__ import annotations

import asyncio
import random
import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

import httpx

from app.config import get_settings
from app.core.logger import get_logger
from app.models.schemas import (
    GmailComposeMessageRequest,
    GmailFilterCreateRequest,
    GmailLabelRequest,
    GmailParsedMessage,
)
from app.utils.gmail_utils import (
    GmailMessageValidationError,
    build_mime_message,
    parse_message,
)
from app.utils.http_utils import SharedAsyncClient

_logger = get_logger(__name__)
_settings = get_settings()

_RETRYABLE_STATUS = frozenset({
    int(code)
    for code in _settings.gmail_retryable_statuses.split(",")
    if code.strip().isdigit()
})


class GmailAPIError(Exception):
    """Raised for upstream Gmail API failures that map to a client-facing error."""

    def __init__(self, message: str, status_code: int = 400, *, reason: str = "") -> None:
        super().__init__(message)
        self.message = message
        self.status_code = status_code
        self.reason = reason


@dataclass
class GmailCredentials:
    """Client-supplied OAuth credentials (never persisted by this backend).

    ``refreshed_access_token`` is populated whenever the service transparently
    refreshes the access token, so the stateless client can persist it itself.
    """

    access_token: str
    refresh_token: Optional[str] = None
    client_id: Optional[str] = None
    client_secret: Optional[str] = None
    expires_at: Optional[float] = None
    refreshed_access_token: Optional[str] = field(default=None, repr=False)

    @property
    def can_refresh(self) -> bool:
        return bool(self.refresh_token and self.client_id and self.client_secret)

    @property
    def needs_proactive_refresh(self) -> bool:
        if self.expires_at is None:
            return False
        return time.time() >= self.expires_at - _settings.gmail_refresh_buffer_seconds


class GmailService:
    """Stateless, fully-async abstraction over the Gmail REST API.

    Credentials are supplied by the caller on every invocation. Access tokens
    are transparently refreshed against Google's token endpoint when a
    ``refresh_token`` + ``client_id`` + ``client_secret`` are provided, and the
    resulting token is surfaced via ``GmailCredentials.refreshed_access_token``.
    """

    def __init__(self) -> None:
        self._http = SharedAsyncClient(
            timeout=httpx.Timeout(_settings.gmail_timeout),
            follow_redirects=False,
        )

    async def _get_client(self) -> httpx.AsyncClient:
        return await self._http.get()

    async def close(self) -> None:
        await self._http.close()

    # ------------------------------------------------------------------
    # Core request pipeline: auth, retry, backoff, error mapping
    # ------------------------------------------------------------------

    async def _request(
        self,
        creds: GmailCredentials,
        method: str,
        path: str,
        *,
        params: Optional[Dict[str, Any]] = None,
        json_body: Optional[Any] = None,
    ) -> Any:
        """Send a Gmail API request with proactive + on-401 refresh and retries."""
        if creds.needs_proactive_refresh:
            await self._refresh(creds, context=f"{method} {path}")

        refresh_done = False
        attempt = 0
        while True:
            response = await self._send(
                creds, method, path, params=params, json_body=json_body
            )
            if 200 <= response.status_code < 300:
                return self._decode(response)

            if response.status_code == 401 and creds.can_refresh and not refresh_done:
                _logger.warning(
                    "Gmail 401 for %s %s; refreshing access token once",
                    method,
                    path,
                )
                await self._refresh(creds, context=f"{method} {path}")
                refresh_done = True
                continue

            if response.status_code in _RETRYABLE_STATUS and attempt < _settings.gmail_max_retries:
                await self._backoff(response, attempt)
                attempt += 1
                continue

            raise self._map_error(response, creds)

    async def _send(
        self,
        creds: GmailCredentials,
        method: str,
        path: str,
        *,
        params: Optional[Dict[str, Any]] = None,
        json_body: Optional[Any] = None,
    ) -> httpx.Response:
        client = await self._get_client()
        url = f"{_settings.gmail_api_base_url}{path}"
        headers = {
            "Authorization": f"Bearer {creds.access_token}",
            "Accept": "application/json",
        }
        try:
            return await client.request(
                method,
                url,
                params=params,
                json=json_body,
                headers=headers,
            )
        except httpx.TimeoutException as exc:
            raise GmailAPIError(
                f"Gmail API request timed out for {method} {path}.", status_code=504
            ) from exc
        except httpx.RequestError as exc:
            raise GmailAPIError(
                f"Failed to reach Gmail API: {exc}", status_code=502
            ) from exc

    @staticmethod
    def _decode(response: httpx.Response) -> Any:
        if not response.content:
            return None
        try:
            return response.json()
        except ValueError:
            return response.text

    async def _backoff(self, response: httpx.Response, attempt: int) -> None:
        retry_after = response.headers.get("Retry-After")
        delay: Optional[float] = None
        if retry_after:
            try:
                delay = float(retry_after)
            except (TypeError, ValueError):
                delay = None
        if delay is None:
            base = _settings.gmail_base_backoff_seconds * (2 ** attempt)
            delay = min(base, _settings.gmail_max_backoff_seconds) * (0.5 + random.random())
        delay = min(delay, _settings.gmail_max_backoff_seconds + 5.0)
        _logger.warning(
            "Gmail transient HTTP %s; retrying in %.2fs (attempt %d/%d)",
            response.status_code,
            delay,
            attempt + 1,
            _settings.gmail_max_retries,
        )
        await asyncio.sleep(delay)

    def _map_error(self, response: httpx.Response, creds: GmailCredentials) -> GmailAPIError:
        status = response.status_code
        reason = ""
        detail = ""
        try:
            body = response.json()
            error = body.get("error") or {}
            if isinstance(error, dict):
                detail = error.get("message", "")
                errors = error.get("errors") or []
                if errors and isinstance(errors[0], dict):
                    reason = errors[0].get("reason", "")
        except Exception:
            body = {}
            detail = response.text[:500]

        _logger.error(
            "Gmail API error: HTTP %s reason=%s detail=%s", status, reason, detail
        )

        if status == 401:
            if creds.can_refresh:
                return GmailAPIError(
                    "Access token is invalid or expired and could not be refreshed. "
                    "Re-authorize via POST /api/v1/google/oauth/auth-url.",
                    status_code=401,
                    reason=reason,
                )
            return GmailAPIError(
                "Access token is invalid or expired. Refresh it via "
                "POST /api/v1/google/oauth/refresh (or /api/v1/gmail/token/refresh) "
                "and retry, or supply a fresh access token.",
                status_code=401,
                reason=reason,
            )
        if status == 403 and reason == "PERMISSION_DENIED":
            return GmailAPIError(
                "Permission denied. The access token may be missing the required "
                "Gmail scope (see /api/v1/google/gmail/scopes).",
                status_code=403,
                reason=reason,
            )
        if status == 429:
            return GmailAPIError(
                "Gmail API rate limit exceeded. Please retry after a short delay.",
                status_code=429,
                reason=reason,
            )
        if status in _RETRYABLE_STATUS:
            return GmailAPIError(
                detail or f"Gmail API service error (HTTP {status}).",
                status_code=status,
                reason=reason,
            )
        return GmailAPIError(
            detail or f"Gmail API error (HTTP {status}).",
            status_code=status,
            reason=reason,
        )

    # ------------------------------------------------------------------
    # Token lifecycle
    # ------------------------------------------------------------------

    async def refresh_access_token(
        self,
        *,
        client_id: str,
        client_secret: str,
        refresh_token: str,
    ) -> Dict[str, Any]:
        """Refresh an access token without touching the mailbox (standalone)."""
        tokens = await self._refresh(
            creds=None,
            client_id=client_id,
            client_secret=client_secret,
            refresh_token=refresh_token,
            context="standalone refresh",
        )
        return tokens

    async def _refresh(
        self,
        creds: Optional[GmailCredentials],
        *,
        context: str,
        client_id: Optional[str] = None,
        client_secret: Optional[str] = None,
        refresh_token: Optional[str] = None,
    ) -> Dict[str, Any]:
        if creds is not None:
            client_id = creds.client_id
            client_secret = creds.client_secret
            refresh_token = creds.refresh_token

        if not (client_id and client_secret and refresh_token):
            raise GmailAPIError(
                "Token refresh requires refresh_token, client_id and client_secret.",
                status_code=400,
            )

        client = await self._get_client()
        data = {
            "client_id": client_id,
            "client_secret": client_secret,
            "refresh_token": refresh_token,
            "grant_type": "refresh_token",
        }
        try:
            response = await client.post(_settings.google_oauth_token_url, data=data)
        except httpx.TimeoutException as exc:
            raise GmailAPIError(
                "Google token refresh timed out.", status_code=504
            ) from exc
        except httpx.RequestError as exc:
            raise GmailAPIError(
                f"Failed to reach Google token endpoint: {exc}", status_code=502
            ) from exc

        if response.status_code == 200:
            tokens = response.json()
            new_token = tokens.get("access_token")
            if not new_token:
                raise GmailAPIError(
                    "Google did not return an access token.", status_code=502
                )
            expires_in = int(tokens.get("expires_in", 3600))
            if creds is not None:
                creds.access_token = new_token
                creds.expires_at = time.time() + expires_in
                creds.refreshed_access_token = new_token
            _logger.info("Gmail access token refreshed (%s)", context)
            return tokens

        try:
            body = response.json()
            error = body.get("error", "")
            description = body.get("error_description", "")
        except Exception:
            error = ""
            description = ""
            body = {}

        if error == "invalid_grant":
            raise GmailAPIError(
                description or "Refresh token is invalid, expired, or revoked. "
                "Re-authorize via POST /api/v1/google/oauth/auth-url.",
                status_code=401,
                reason=error,
            )
        if error == "invalid_client":
            raise GmailAPIError(
                description or "Invalid client_id or client_secret.",
                status_code=401,
                reason=error,
            )
        raise GmailAPIError(
            description or f"Google token refresh failed (HTTP {response.status_code}).",
            status_code=response.status_code if response.status_code >= 400 else 502,
            reason=error,
        )

    # ------------------------------------------------------------------
    # Users profile & scopes
    # ------------------------------------------------------------------

    async def get_profile(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/profile")

    async def list_available_scopes(self) -> List[Dict[str, Any]]:
        from app.models.schemas import GmailScope

        return [
            {
                "name": scope.name,
                "uri": scope.value,
                "permission_level": scope.permission_level,
            }
            for scope in GmailScope
        ]

    # ------------------------------------------------------------------
    # Messages
    # ------------------------------------------------------------------

    async def list_messages(
        self,
        creds: GmailCredentials,
        user_id: str = "me",
        *,
        q: Optional[str] = None,
        label_ids: Optional[List[str]] = None,
        max_results: Optional[int] = None,
        page_token: Optional[str] = None,
        include_spam_trash: bool = False,
        batch_size: Optional[int] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {}
        if q is not None:
            params["q"] = q
        if label_ids:
            params["labelIds"] = label_ids
        if max_results is not None:
            params["maxResults"] = max_results
        if page_token:
            params["pageToken"] = page_token
        if include_spam_trash:
            params["includeSpamTrash"] = "true"
        if batch_size is not None:
            params["batchSize"] = batch_size
        return await self._request(
            creds, "GET", f"/users/{user_id}/messages", params=params or None
        )

    async def get_message(
        self,
        creds: GmailCredentials,
        message_id: str,
        user_id: str = "me",
        *,
        format: str = "full",
        metadata_headers: Optional[List[str]] = None,
        headers: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"format": format}
        if metadata_headers:
            params["metadataHeaders"] = metadata_headers
        if headers:
            params["headers"] = headers
        return await self._request(
            creds, "GET", f"/users/{user_id}/messages/{message_id}", params=params
        )

    async def get_parsed_message(
        self,
        creds: GmailCredentials,
        message_id: str,
        user_id: str = "me",
        *,
        format: str = "full",
    ) -> GmailParsedMessage:
        data = await self.get_message(creds, message_id, user_id=user_id, format=format)
        return parse_message(data)

    async def send_raw(
        self,
        creds: GmailCredentials,
        raw: str,
        user_id: str = "me",
        *,
        thread_id: Optional[str] = None,
        labels: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"raw": raw}
        if thread_id:
            body["threadId"] = thread_id
        if labels:
            body["labelIds"] = labels
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages/send", json_body=body
        )

    async def send_composed(
        self,
        creds: GmailCredentials,
        request: GmailComposeMessageRequest,
        user_id: str = "me",
    ) -> Dict[str, Any]:
        try:
            raw = build_mime_message(request)
        except GmailMessageValidationError as exc:
            raise GmailAPIError(str(exc), status_code=400) from exc
        return await self.send_raw(
            creds,
            raw,
            user_id=user_id,
            thread_id=request.thread_id,
            labels=request.labels,
        )

    async def insert_message(
        self,
        creds: GmailCredentials,
        raw: str,
        user_id: str = "me",
        *,
        label_ids: Optional[List[str]] = None,
        internal_date_source: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"raw": raw}
        if label_ids:
            body["labelIds"] = label_ids
        if internal_date_source:
            body["internalDateSource"] = internal_date_source
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages", json_body=body
        )

    async def import_message(
        self,
        creds: GmailCredentials,
        raw: str,
        user_id: str = "me",
        *,
        label_ids: Optional[List[str]] = None,
        internal_date_source: Optional[str] = None,
        never_mark_spam: bool = False,
        process_for_calendar: bool = False,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"raw": raw}
        if label_ids:
            body["labelIds"] = label_ids
        if internal_date_source:
            body["internalDateSource"] = internal_date_source
        if never_mark_spam:
            body["neverMarkSpam"] = True
        if process_for_calendar:
            body["processForCalendar"] = True
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages/import", json_body=body
        )

    async def modify_message(
        self,
        creds: GmailCredentials,
        message_id: str,
        user_id: str = "me",
        *,
        add_label_ids: Optional[List[str]] = None,
        remove_label_ids: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {}
        if add_label_ids:
            body["addLabelIds"] = add_label_ids
        if remove_label_ids:
            body["removeLabelIds"] = remove_label_ids
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages/{message_id}/modify", json_body=body
        )

    async def batch_modify(
        self,
        creds: GmailCredentials,
        ids: List[str],
        user_id: str = "me",
        *,
        add_label_ids: Optional[List[str]] = None,
        remove_label_ids: Optional[List[str]] = None,
    ) -> None:
        body: Dict[str, Any] = {"ids": ids}
        if add_label_ids:
            body["addLabelIds"] = add_label_ids
        if remove_label_ids:
            body["removeLabelIds"] = remove_label_ids
        await self._request(creds, "POST", f"/users/{user_id}/messages/batchModify", json_body=body)

    async def batch_delete(
        self, creds: GmailCredentials, ids: List[str], user_id: str = "me"
    ) -> None:
        await self._request(
            creds, "POST", f"/users/{user_id}/messages/batchDelete", json_body={"ids": ids}
        )

    async def trash_message(
        self, creds: GmailCredentials, message_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages/{message_id}/trash"
        )

    async def untrash_message(
        self, creds: GmailCredentials, message_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/messages/{message_id}/untrash"
        )

    async def delete_message(
        self, creds: GmailCredentials, message_id: str, user_id: str = "me"
    ) -> None:
        await self._request(creds, "DELETE", f"/users/{user_id}/messages/{message_id}")

    async def get_attachment(
        self,
        creds: GmailCredentials,
        message_id: str,
        attachment_id: str,
        user_id: str = "me",
    ) -> Dict[str, Any]:
        return await self._request(
            creds,
            "GET",
            f"/users/{user_id}/messages/{message_id}/attachments/{attachment_id}",
        )

    # ------------------------------------------------------------------
    # Push notifications (watch / stop)
    # ------------------------------------------------------------------

    async def watch(
        self,
        creds: GmailCredentials,
        user_id: str = "me",
        *,
        topic_name: str,
        label_ids: Optional[List[str]] = None,
        label_filter_action: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"topicName": topic_name}
        if label_ids:
            body["labelIds"] = label_ids
        if label_filter_action:
            body["labelFilterAction"] = label_filter_action
        return await self._request(creds, "POST", f"/users/{user_id}/watch", json_body=body)

    async def stop_watch(self, creds: GmailCredentials, user_id: str = "me") -> None:
        await self._request(creds, "POST", f"/users/{user_id}/stop")

    # ------------------------------------------------------------------
    # History
    # ------------------------------------------------------------------

    async def list_history(
        self,
        creds: GmailCredentials,
        user_id: str = "me",
        *,
        start_history_id: int,
        label_id: Optional[str] = None,
        history_types: Optional[List[str]] = None,
        max_results: Optional[int] = None,
        page_token: Optional[str] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"startHistoryId": start_history_id}
        if label_id:
            params["labelId"] = label_id
        if history_types:
            params["historyTypes"] = history_types
        if max_results is not None:
            params["maxResults"] = max_results
        if page_token:
            params["pageToken"] = page_token
        return await self._request(creds, "GET", f"/users/{user_id}/history", params=params)

    # ------------------------------------------------------------------
    # Drafts
    # ------------------------------------------------------------------

    async def list_drafts(
        self,
        creds: GmailCredentials,
        user_id: str = "me",
        *,
        max_results: Optional[int] = None,
        page_token: Optional[str] = None,
        q: Optional[str] = None,
        include_spam_trash: bool = False,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {}
        if max_results is not None:
            params["maxResults"] = max_results
        if page_token:
            params["pageToken"] = page_token
        if q:
            params["q"] = q
        if include_spam_trash:
            params["includeSpamTrash"] = "true"
        return await self._request(creds, "GET", f"/users/{user_id}/drafts", params=params or None)

    async def get_draft(
        self,
        creds: GmailCredentials,
        draft_id: str,
        user_id: str = "me",
        *,
        format: str = "full",
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "GET", f"/users/{user_id}/drafts/{draft_id}", params={"format": format}
        )

    async def create_draft(
        self,
        creds: GmailCredentials,
        raw: str,
        user_id: str = "me",
        *,
        thread_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"message": {"raw": raw}}
        if thread_id:
            body["message"]["threadId"] = thread_id
        return await self._request(creds, "POST", f"/users/{user_id}/drafts", json_body=body)

    async def update_draft(
        self,
        creds: GmailCredentials,
        draft_id: str,
        raw: str,
        user_id: str = "me",
        *,
        thread_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"message": {"raw": raw}}
        if thread_id:
            body["message"]["threadId"] = thread_id
        return await self._request(
            creds, "PUT", f"/users/{user_id}/drafts/{draft_id}", json_body=body
        )

    async def send_draft(
        self, creds: GmailCredentials, draft_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/drafts/send", json_body={"id": draft_id}
        )

    async def delete_draft(
        self, creds: GmailCredentials, draft_id: str, user_id: str = "me"
    ) -> None:
        await self._request(creds, "DELETE", f"/users/{user_id}/drafts/{draft_id}")

    # ------------------------------------------------------------------
    # Threads
    # ------------------------------------------------------------------

    async def list_threads(
        self,
        creds: GmailCredentials,
        user_id: str = "me",
        *,
        q: Optional[str] = None,
        label_ids: Optional[List[str]] = None,
        max_results: Optional[int] = None,
        page_token: Optional[str] = None,
        include_spam_trash: bool = False,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {}
        if q:
            params["q"] = q
        if label_ids:
            params["labelIds"] = label_ids
        if max_results is not None:
            params["maxResults"] = max_results
        if page_token:
            params["pageToken"] = page_token
        if include_spam_trash:
            params["includeSpamTrash"] = "true"
        return await self._request(creds, "GET", f"/users/{user_id}/threads", params=params or None)

    async def get_thread(
        self,
        creds: GmailCredentials,
        thread_id: str,
        user_id: str = "me",
        *,
        format: str = "full",
        metadata_headers: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        params: Dict[str, Any] = {"format": format}
        if metadata_headers:
            params["metadataHeaders"] = metadata_headers
        return await self._request(
            creds, "GET", f"/users/{user_id}/threads/{thread_id}", params=params
        )

    async def modify_thread(
        self,
        creds: GmailCredentials,
        thread_id: str,
        user_id: str = "me",
        *,
        add_label_ids: Optional[List[str]] = None,
        remove_label_ids: Optional[List[str]] = None,
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {}
        if add_label_ids:
            body["addLabelIds"] = add_label_ids
        if remove_label_ids:
            body["removeLabelIds"] = remove_label_ids
        return await self._request(
            creds, "POST", f"/users/{user_id}/threads/{thread_id}/modify", json_body=body
        )

    async def trash_thread(
        self, creds: GmailCredentials, thread_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/threads/{thread_id}/trash"
        )

    async def untrash_thread(
        self, creds: GmailCredentials, thread_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/threads/{thread_id}/untrash"
        )

    async def delete_thread(
        self, creds: GmailCredentials, thread_id: str, user_id: str = "me"
    ) -> None:
        await self._request(creds, "DELETE", f"/users/{user_id}/threads/{thread_id}")

    # ------------------------------------------------------------------
    # Labels
    # ------------------------------------------------------------------

    async def list_labels(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/labels")

    async def get_label(
        self, creds: GmailCredentials, label_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/labels/{label_id}")

    async def create_label(
        self, creds: GmailCredentials, label: GmailLabelRequest, user_id: str = "me"
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"name": label.name}
        if label.label_list_visibility:
            body["labelListVisibility"] = label.label_list_visibility
        if label.message_list_visibility:
            body["messageListVisibility"] = label.message_list_visibility
        if label.color:
            body["color"] = label.color
        return await self._request(creds, "POST", f"/users/{user_id}/labels", json_body=body)

    async def update_label(
        self,
        creds: GmailCredentials,
        label_id: str,
        label: GmailLabelRequest,
        user_id: str = "me",
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"name": label.name}
        if label.label_list_visibility:
            body["labelListVisibility"] = label.label_list_visibility
        if label.message_list_visibility:
            body["messageListVisibility"] = label.message_list_visibility
        if label.color:
            body["color"] = label.color
        return await self._request(
            creds, "PUT", f"/users/{user_id}/labels/{label_id}", json_body=body
        )

    async def patch_label(
        self,
        creds: GmailCredentials,
        label_id: str,
        payload: Dict[str, Any],
        user_id: str = "me",
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PATCH", f"/users/{user_id}/labels/{label_id}", json_body=payload
        )

    async def delete_label(
        self, creds: GmailCredentials, label_id: str, user_id: str = "me"
    ) -> None:
        await self._request(creds, "DELETE", f"/users/{user_id}/labels/{label_id}")

    # ------------------------------------------------------------------
    # Settings: auto-forwarding / vacation / filters / forwarding / send-as / delegates
    # ------------------------------------------------------------------

    async def get_auto_forwarding(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/autoForwarding")

    async def update_auto_forwarding(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PUT", f"/users/{user_id}/settings/autoForwarding", json_body=payload
        )

    async def get_vacation(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/vacation")

    async def update_vacation(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PUT", f"/users/{user_id}/settings/vacation", json_body=payload
        )

    async def get_imap(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/imap")

    async def update_imap(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PUT", f"/users/{user_id}/settings/imap", json_body=payload
        )

    async def get_pop(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/pop")

    async def update_pop(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PUT", f"/users/{user_id}/settings/pop", json_body=payload
        )

    async def get_language(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/language")

    async def update_language(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PUT", f"/users/{user_id}/settings/language", json_body=payload
        )

    async def list_filters(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/filters")

    async def get_filter(
        self, creds: GmailCredentials, filter_id: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/filters/{filter_id}")

    async def create_filter(
        self, creds: GmailCredentials, req: GmailFilterCreateRequest, user_id: str = "me"
    ) -> Dict[str, Any]:
        body: Dict[str, Any] = {"criteria": req.criteria or {}, "action": req.action or {}}
        return await self._request(creds, "POST", f"/users/{user_id}/settings/filters", json_body=body)

    async def delete_filter(
        self, creds: GmailCredentials, filter_id: str, user_id: str = "me"
    ) -> None:
        await self._request(creds, "DELETE", f"/users/{user_id}/settings/filters/{filter_id}")

    async def list_forwarding_addresses(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/forwardingAddresses")

    async def get_forwarding_address(
        self, creds: GmailCredentials, forwarding_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "GET", f"/users/{user_id}/settings/forwardingAddresses/{forwarding_email}"
        )

    async def create_forwarding_address(
        self, creds: GmailCredentials, forwarding_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds,
            "POST",
            f"/users/{user_id}/settings/forwardingAddresses",
            json_body={"forwardingEmail": forwarding_email},
        )

    async def delete_forwarding_address(
        self, creds: GmailCredentials, forwarding_email: str, user_id: str = "me"
    ) -> None:
        await self._request(
            creds, "DELETE", f"/users/{user_id}/settings/forwardingAddresses/{forwarding_email}"
        )

    async def list_send_as(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/sendAs")

    async def get_send_as(
        self, creds: GmailCredentials, send_as_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "GET", f"/users/{user_id}/settings/sendAs/{send_as_email}"
        )

    async def create_send_as(
        self, creds: GmailCredentials, payload: Dict[str, Any], user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "POST", f"/users/{user_id}/settings/sendAs", json_body=payload
        )

    async def update_send_as(
        self,
        creds: GmailCredentials,
        send_as_email: str,
        payload: Dict[str, Any],
        user_id: str = "me",
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "PATCH", f"/users/{user_id}/settings/sendAs/{send_as_email}", json_body=payload
        )

    async def verify_send_as(
        self, creds: GmailCredentials, send_as_email: str, user_id: str = "me"
    ) -> None:
        await self._request(
            creds, "POST", f"/users/{user_id}/settings/sendAs/{send_as_email}/verify"
        )

    async def delete_send_as(
        self, creds: GmailCredentials, send_as_email: str, user_id: str = "me"
    ) -> None:
        await self._request(
            creds, "DELETE", f"/users/{user_id}/settings/sendAs/{send_as_email}"
        )

    async def list_delegates(self, creds: GmailCredentials, user_id: str = "me") -> Dict[str, Any]:
        return await self._request(creds, "GET", f"/users/{user_id}/settings/delegates")

    async def get_delegate(
        self, creds: GmailCredentials, delegate_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "GET", f"/users/{user_id}/settings/delegates/{delegate_email}"
        )

    async def create_delegate(
        self, creds: GmailCredentials, delegate_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds,
            "POST",
            f"/users/{user_id}/settings/delegates",
            json_body={"delegateEmail": delegate_email},
        )

    async def delete_delegate(
        self, creds: GmailCredentials, delegate_email: str, user_id: str = "me"
    ) -> None:
        await self._request(
            creds, "DELETE", f"/users/{user_id}/settings/delegates/{delegate_email}"
        )

    async def list_smime_info(
        self, creds: GmailCredentials, send_as_email: str, user_id: str = "me"
    ) -> Dict[str, Any]:
        return await self._request(
            creds, "GET", f"/users/{user_id}/settings/sendAs/{send_as_email}/smimeInfo"
        )

    async def get_smime_info(
        self,
        creds: GmailCredentials,
        send_as_email: str,
        smime_info_id: str,
        user_id: str = "me",
    ) -> Dict[str, Any]:
        return await self._request(
            creds,
            "GET",
            f"/users/{user_id}/settings/sendAs/{send_as_email}/smimeInfo/{smime_info_id}",
        )

    async def insert_smime_info(
        self,
        creds: GmailCredentials,
        send_as_email: str,
        payload: Dict[str, Any],
        user_id: str = "me",
    ) -> Dict[str, Any]:
        return await self._request(
            creds,
            "POST",
            f"/users/{user_id}/settings/sendAs/{send_as_email}/smimeInfo",
            json_body=payload,
        )

    async def delete_smime_info(
        self,
        creds: GmailCredentials,
        send_as_email: str,
        smime_info_id: str,
        user_id: str = "me",
    ) -> None:
        await self._request(
            creds,
            "DELETE",
            f"/users/{user_id}/settings/sendAs/{send_as_email}/smimeInfo/{smime_info_id}",
        )

    async def set_default_smime_info(
        self,
        creds: GmailCredentials,
        send_as_email: str,
        smime_info_id: str,
        user_id: str = "me",
    ) -> None:
        await self._request(
            creds,
            "POST",
            f"/users/{user_id}/settings/sendAs/{send_as_email}/smimeInfo/{smime_info_id}/setDefault",
        )