File size: 56,595 Bytes
07a68d0
 
f462120
07a68d0
 
 
812ec21
f462120
07a68d0
f462120
07a68d0
 
 
 
 
 
 
 
 
812ec21
 
 
07a68d0
812ec21
07a68d0
 
f462120
07a68d0
 
 
 
 
 
 
 
f462120
812ec21
f462120
07a68d0
 
 
 
 
f462120
07a68d0
 
 
 
 
 
 
 
812ec21
 
07a68d0
 
 
812ec21
 
 
 
07a68d0
 
812ec21
 
07a68d0
812ec21
 
 
07a68d0
812ec21
 
 
 
07a68d0
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
07a68d0
 
 
f462120
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
 
 
07a68d0
 
 
 
 
f462120
07a68d0
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
f462120
07a68d0
 
812ec21
 
 
 
 
 
 
 
 
07a68d0
 
 
 
023301a
 
 
 
 
07a68d0
 
 
 
 
 
 
 
812ec21
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
07a68d0
 
f462120
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
07a68d0
 
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
 
f462120
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f462120
 
07a68d0
 
 
 
f462120
07a68d0
 
 
 
f462120
 
 
 
07a68d0
 
 
 
f462120
 
 
 
07a68d0
 
8873406
07a68d0
 
8873406
07a68d0
 
 
 
 
 
 
f462120
 
 
 
 
 
 
 
 
07a68d0
 
 
 
8873406
07a68d0
 
 
812ec21
 
8873406
07a68d0
 
 
 
812ec21
 
 
 
8873406
07a68d0
 
 
8873406
 
 
 
07a68d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8873406
 
07a68d0
812ec21
f462120
 
 
 
07a68d0
 
 
 
812ec21
07a68d0
 
 
 
 
 
 
 
812ec21
 
 
 
07a68d0
 
 
 
 
 
 
 
812ec21
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
812ec21
 
07a68d0
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
023301a
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
023301a
07a68d0
812ec21
07a68d0
812ec21
 
 
 
023301a
812ec21
023301a
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
812ec21
07a68d0
812ec21
 
 
 
 
 
07a68d0
 
 
 
 
812ec21
07a68d0
812ec21
 
07a68d0
 
812ec21
 
 
 
 
07a68d0
 
812ec21
07a68d0
 
 
f462120
 
 
 
 
 
 
 
 
07a68d0
 
 
812ec21
 
07a68d0
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
812ec21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
 
 
 
 
 
812ec21
 
 
 
 
 
07a68d0
 
812ec21
07a68d0
 
 
812ec21
07a68d0
 
 
 
812ec21
07a68d0
 
 
 
 
 
812ec21
 
f462120
 
812ec21
 
 
 
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
"""amazon_ads_client.py: the Amazon Ads API transport (S79-T12, contract C6).

⛔ THE CLIENT READS REPORTS AND SENDS ONLY NAMED WRITES. The Ads API has no
read-only scope: `advertising::campaign_management` can change any campaign (primer F10). So the
refusal lives here, in the request builder, before any credential read, token exchange or socket:

    reports       Reporting v1: create, retrieve, the advertiser account query, and the report files
    streams       create and list subscriptions for the dedicated V1 destination
    named writes  `send_named_write(tenant_key, kind, payload, *, approval_id)`, kind in
                  `bid`, `budget`, `negative_keyword`, `scheduled_change`, each operation one path constant

Every other call raises `AdsWriteRefused`. A named write also needs an approval id that the
Operator App stored as approved for this very item (`APPROVAL_SOURCE`, read lazily, because a
harness module never imports `modules` at load). A missing approval source refuses.

`AMAZON_ADS_FIXTURE=1` routes every call to the recording fixture below. No live Ads call is
made until Royal's Direct Advertiser credential arrives (R7, R17).

NA host `advertising-api.amazon.com`, one profile id per marketplace (F13). The profile id is
stored with the credential. v1 names the account by `advertiserAccountId`, which the client looks
up once per connection from `query/advertiserAccounts`. Every path, header and field comes from
Amazon's saved contracts in `AutoWiki/research/amazon-ads-v1-schema/`.
"""
import gzip
import importlib
import json
import logging
import os
import re
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import contextmanager
from datetime import date, datetime, timedelta, timezone
from typing import NamedTuple
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

KEY = "amazon_ads"
LABEL = "Amazon Ads"
ENTRY_TYPE = "amazon_ads"
FIXTURE_ENV = "AMAZON_ADS_FIXTURE"
_log = logging.getLogger(__name__)

HOSTS = {"na": "https://advertising-api.amazon.com",
         "eu": "https://advertising-api-eu.amazon.com",
         "fe": "https://advertising-api-fe.amazon.com"}
DEFAULT_REGION = "na"
LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"
CREDENTIAL_FIELDS = ("client_id", "client_secret", "refresh_token", "profile_id")

#: Reporting v1 limits (limits.md, dates.md): one report in flight per client ID, about 100 a day,
#: up to 3 hours per report, at most 120 days per request.
REPORT_CONCURRENCY = 1
REPORTS_PER_DAY = 100
REPORT_MAX_WAIT_SECONDS = 3 * 3600
MAX_DAYS_PER_REQUEST = 120
REPORT_POLL_SECONDS = 60.0
#: Amazon's error text reaches the sync report verbatim, up to this many characters.
ERROR_TEXT_LIMIT = 600
_TIMEOUT = 60

#: The only non-write calls: the Reporting v1 operations, each a POST to one literal path from the
#: Reports and AdvertiserAccounts contracts. Every other `adsApi` path refuses, a GET included.
REPORT_OPERATIONS = {
    "createReport": ("POST", "adsApi/v1/create/reports"),
    "retrieveReport": ("POST", "adsApi/v1/retrieve/reports"),
    "queryAdvertiserAccounts": ("POST", "adsApi/v1/query/advertiserAccounts"),
}
#: The contract names `Amazon-Ads-ClientId`. The limits page names the older header. v1 sends both.
V1_CLIENT_HEADERS = ("Amazon-Ads-ClientId", "Amazon-Advertising-API-ClientId")
#: A report file is a presigned S3 URL: https, on this host suffix, GET with no Ads header.
REPORT_FILE_HOST_SUFFIX = ".amazonaws.com"

# Subscription management never admits an advertising write.
STREAM_OPERATIONS = {
    "createStreamSubscription": ("POST", "streams/subscriptions"),
    "listStreamSubscriptions": ("GET", "streams/subscriptions"),
}
STREAM_CONTENT_TYPE = "application/vnd.MarketingStreamSubscriptions.StreamSubscriptionResource.v1.0+json"


def stream_operation(method, path):
    """Resolve only the two V1 subscription operations."""
    return next((name for name, (verb, endpoint) in STREAM_OPERATIONS.items()
                 if str(method).upper() == verb and str(path).strip("/") == endpoint), None)


def _stream_payload(operation, body, query):
    """Reject unknown subscription fields before reading credentials."""
    if operation == "createStreamSubscription":
        if query or not isinstance(body, dict) or set(body) - {
                "dataSetId", "destinationArn", "clientRequestToken", "notes"}:
            raise AdsWriteRefused("invalid stream subscription fields")
        if body.get("dataSetId") not in {"sp-traffic", "sp-conversion"}:
            raise AdsWriteRefused("the stream dataset is not allowed")
        if not re.fullmatch(r"arn:aws:sqs:us-east-1:023371594014:aios-amazon-marketing-stream",
                            str(body.get("destinationArn") or "")):
            raise AdsWriteRefused("the stream destination is not the dedicated AIOS queue")
        if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", str(body.get("clientRequestToken") or "")):
            raise AdsWriteRefused("a stream create needs a stable retry token")
        if "notes" in body and (not isinstance(body["notes"], str) or len(body["notes"]) > 256):
            raise AdsWriteRefused("invalid stream notes")
    elif operation == "listStreamSubscriptions":
        if body is not None or set(query or {}) - {"startingToken", "maxResults"}:
            raise AdsWriteRefused("invalid stream listing fields")
        if "startingToken" in (query or {}) and not isinstance(query["startingToken"], str):
            raise AdsWriteRefused("invalid stream continuation token")
        if "maxResults" in (query or {}) and (type(query["maxResults"]) is not int or query["maxResults"] <= 0):
            raise AdsWriteRefused("invalid stream page size")
    else:
        raise AdsWriteRefused("the stream operation is not allowed")

#: ⛔ C6: THE NAMED WRITES, AS DATA. `kind -> operation -> rule`. `endpoints` names the one path
#: per ad type; an ad type absent there refuses. `item` is the body template: a "{field}" value
#: is read from the validated payload, any other value is a constant. `each` repeats the item per
#: id in that payload list. The body carries only template keys, never a caller's other fields.
NAMED_WRITES = {
    "bid": {
        "set_bid": {
            "endpoints": {"sp": ("PUT", "sp/targets"), "sb": ("PUT", "sb/targets"),
                          "sd": ("PUT", "sd/targets")},
            "required": ("campaign_id", "ad_group_id", "target_id", "bid"),
            "collection": "targets",
            "item": {"targetId": "{target_id}", "adGroupId": "{ad_group_id}",
                     "campaignId": "{campaign_id}", "bid": "{bid}"},
        },
        # QI3 "pause ads on a money loser": an ad state change, carried under the bid kind.
        "pause_ads": {
            "endpoints": {"sp": ("PUT", "sp/productAds"), "sb": ("PUT", "sb/v4/ads"),
                          "sd": ("PUT", "sd/productAds")},
            "required": ("campaign_id", "ad_group_id", "ad_ids", "state"),
            "collection": "ads", "each": "ad_ids",
            "state": "paused",
            "item": {"adId": "{each}", "adGroupId": "{ad_group_id}",
                     "campaignId": "{campaign_id}", "state": "PAUSED"},
        },
        "enable_ads": {
            "endpoints": {"sp": ("PUT", "sp/productAds"), "sb": ("PUT", "sb/v4/ads"),
                          "sd": ("PUT", "sd/productAds")},
            "required": ("campaign_id", "ad_group_id", "ad_ids", "state"),
            "collection": "ads", "each": "ad_ids", "state": "enabled",
            "item": {"adId": "{each}", "adGroupId": "{ad_group_id}",
                     "campaignId": "{campaign_id}", "state": "ENABLED"},
        },
    },
    "budget": {
        "set_daily_budget": {
            "endpoints": {"sp": ("PUT", "sp/campaigns"), "sb": ("PUT", "sb/v4/campaigns"),
                          "sd": ("PUT", "sd/campaigns")},
            "required": ("campaign_id", "daily_budget"),
            "collection": "campaigns",
            "item": {"campaignId": "{campaign_id}",
                     "budget": {"budget": "{daily_budget}", "budgetType": "DAILY"}},
        },
    },
    "negative_keyword": {
        # Sponsored Display takes no negative keywords, so it has no endpoint and refuses.
        "add_negative_keyword": {
            "endpoints": {"sp": ("POST", "sp/negativeKeywords"),
                          "sb": ("POST", "sb/negativeKeywords")},
            "required": ("campaign_id", "ad_group_id", "keyword_text", "match_type"),
            "collection": "negativeKeywords",
            "item": {"campaignId": "{campaign_id}", "adGroupId": "{ad_group_id}",
                     "keywordText": "{keyword_text}", "matchType": "{match_type}",
                     "state": "ENABLED"},
        },
    },
}
NAMED_WRITES["scheduled_change"] = {
    operation: NAMED_WRITES["bid"][operation]
    for operation in ("set_bid", "pause_ads", "enable_ads")
}

#: Payload field rules for the named writes. A tuple is the allowed values.
FIELD_RULES = {
    "campaign_id": "id", "ad_group_id": "id", "target_id": "id", "ad_ids": "ids",
    "bid": "money", "daily_budget": "money", "keyword_text": "text",
    "match_type": ("negativeExact", "negativePhrase"), "state": ("paused", "enabled"),
}

#: C6: `fn(tenant_key, approval_id) -> record or None`, imported lazily. The record must be
#: approved and name the payload's `item_id`.
APPROVAL_SOURCE = "modules.amazon_operator:approval"

#: schedule_approval(tenant_key, schedule_id) returns a fresh stored record, or None when the App is off.
#: Required: id, approved_by, approved_at (aware ISO timestamp), enabled (bool), campaign_id, ad_type,
#: timezone (IANA), weekday_convention="monday_zero" (Monday=0, Sunday=6), rules (list).
#: Each rule binds weekday (int 0..6), hour (int 0..23), action (operation name), value,
#: ad_group_id, and target_id for set_bid or exact ad_ids for pause_ads/enable_ads.
#: value is the bid for set_bid, "paused" for pause_ads, or "enabled" for enable_ads.
#: Optional profile_id binds the profile on the record and payload. Missing means the default profile.
#: Payload adds schedule_id, item_id, timezone, weekday, hour to the operation's usual fields.
#: approval_id equals schedule_id. The client checks its own clock in the stored timezone.
#: The reader validates entity membership from trusted observations and invalidates approval after edits.
#: The runner persists receipts and claims each local date/rule/hour once, including repeated DST hours.
SCHEDULE_APPROVAL_SOURCE = "modules.amazon_operator:schedule_approval"
SCHEDULE_WEEKDAY_CONVENTION = "monday_zero"

#: sent_write(tenant_key, item_id) returns a stored proposal with id, kind, status, sent_payload, result.
#: enable_ads under bid requires an exact approved payload with undo_of naming that sent pause.
#: sent_payload must record previous_state="enabled" for every ad, plus the original pause fields.
#: result is the original send_named_write receipt. Historical pauses without prior state refuse.
SENT_WRITE_SOURCE = "modules.amazon_operator:sent_write"


class AdsError(RuntimeError):
    """An Ads API failure, safe to show: no token or secret ever reaches it."""


class AdsWriteRefused(AdsError):
    """A call this connector does not make. Raised before any network I/O."""

    def __init__(self, cause):
        self.cause = str(cause)
        super().__init__(f"Refused: {self.cause}. This connector reads reports and sends only "
                         f"the named writes: bid, budget, negative keyword and scheduled change.")


class AdsRejected(AdsError):
    """Amazon answered an error. `errors` keeps each entry's code, message and fieldLocation."""

    def __init__(self, message, errors=()):
        super().__init__(message)
        self.errors = list(errors)


class AdsReportUnavailable(AdsRejected):
    """Amazon does not offer this report to this advertiser."""


class AdsReportPending(AdsError):
    """A report did not finish inside the wait limit. `report_id` names it so a later pass can resume it."""

    def __init__(self, message, report_id=None):
        super().__init__(message)
        self.report_id = report_id


def fixture_mode():
    """True when `AMAZON_ADS_FIXTURE=1` routes every call to the recording fixture."""
    return os.environ.get(FIXTURE_ENV) == "1"


def report_operation(method, path):
    """The Reporting v1 operation name for one call, or None. A path matches only its literal."""
    return next((name for name, (verb, endpoint) in REPORT_OPERATIONS.items()
                 if str(method).upper() == verb and str(path or "").strip("/") == endpoint), None)


class _Prepared:
    """A request the builder accepted. Only `build_request` and `_build_named` make one."""
    __slots__ = ("method", "path", "body", "query", "operation", "named", "_seal")

    def __init__(self, method, path, body, query, operation, named):
        self.method, self.path, self.body, self.query = method, path, body, query
        self.operation, self.named = operation, named
        self._seal = _SEAL


_SEAL = object()


def build_request(method, path, *, body=None, query=None):
    """Accept a report or scoped stream subscription call before any I/O."""
    operation = report_operation(method, path) or stream_operation(method, path)
    if operation is None:
        raise AdsWriteRefused(f"{str(method).upper()} {_safe_path(path)} is not a report call")
    if operation in STREAM_OPERATIONS:
        _stream_payload(operation, body, query)
    return _Prepared(str(method).upper(), str(path).strip("/"), body, dict(query or {}),
                     operation, None)


def _safe_path(path):
    return re.sub(r"[^A-Za-z0-9/_{}.-]", "", str(path or ""))[:120] or "an empty path"


def _valid(field, value):
    rule = FIELD_RULES.get(field)
    if rule == "id":
        return isinstance(value, (str, int)) and not isinstance(value, bool) \
            and bool(re.fullmatch(r"[0-9]{1,24}", str(value)))
    if rule == "ids":
        return isinstance(value, (list, tuple)) and bool(value) and all(_valid("campaign_id", v) for v in value)
    if rule == "money":
        try:
            number = float(value)
        except (TypeError, ValueError):
            return False
        return not isinstance(value, bool) and number > 0 and number == number and number != float("inf")
    if rule == "text":
        return isinstance(value, str) and 0 < len(value.strip()) <= 80
    if isinstance(rule, tuple):
        return value in rule
    return False


def _render(value, payload, each=None):
    if isinstance(value, dict):
        return {k: _render(v, payload, each) for k, v in value.items()}
    if isinstance(value, str) and value.startswith("{") and value.endswith("}"):
        field = value[1:-1]
        raw = each if field == "each" else payload[field]
        if FIELD_RULES.get(field) == "money":
            return round(float(raw), 2)
        return str(raw) if field == "each" or FIELD_RULES.get(field) == "id" else raw
    return value


def _build_named(kind, payload):
    """Accept one of C6's named writes, or raise `AdsWriteRefused` before any I/O."""
    if kind not in NAMED_WRITES:
        raise AdsWriteRefused(f"write kind {str(kind)[:40]!r} is not a named write")
    if not isinstance(payload, dict):
        raise AdsWriteRefused("the write payload is not an object")
    operation = str(payload.get("operation") or "")
    rule = NAMED_WRITES[kind].get(operation)
    if rule is None:
        raise AdsWriteRefused(f"operation {operation[:40]!r} is not named under {kind}")
    ad_type = str(payload.get("ad_type") or "")
    endpoint = rule["endpoints"].get(ad_type)
    if endpoint is None:
        raise AdsWriteRefused(f"{operation} is not named for ad type {ad_type[:8]!r}")
    for field in rule["required"]:
        if not _valid(field, payload.get(field)):
            raise AdsWriteRefused(f"{operation} needs a valid {field}")
    if "state" in rule and payload.get("state") != rule["state"]:
        raise AdsWriteRefused(f"{operation} needs state {rule['state']}")
    each = rule.get("each")
    items = ([_render(rule["item"], payload, v) for v in payload[each]] if each
             else [_render(rule["item"], payload)])
    method, path = endpoint
    return _Prepared(method, path, {rule["collection"]: items}, {}, operation,
                     {"kind": kind, "operation": operation, "ad_type": ad_type})


def _read_record(source, tenant_key, record_id, label):
    """Read one tenant-bound approval or outcome through its lazy source."""
    module_name, _, name = source.partition(":")
    try:
        reader = getattr(importlib.import_module(module_name), name)
    except Exception:                                                  # noqa: BLE001
        raise AdsWriteRefused(f"the {label} source is not installed") from None
    try:
        return reader(tenant_key, record_id)
    except Exception:                                                  # noqa: BLE001
        raise AdsWriteRefused(f"the {label} could not be read") from None


def _utcnow():
    return datetime.now(timezone.utc)


def _approved_schedule(tenant_key, approval_id, payload):
    """Refuse unless the stored schedule permits these entities and this action at the current hour."""
    if payload.get("schedule_id") != approval_id:
        raise AdsWriteRefused("the schedule id must be its approval id")
    record = _read_record(SCHEDULE_APPROVAL_SOURCE, tenant_key, approval_id, "schedule approval")
    if not isinstance(record, dict) or record.get("id") != approval_id:
        raise AdsWriteRefused("the approved schedule does not exist")
    if record.get("enabled") is not True:
        raise AdsWriteRefused("the schedule is switched off")
    if not isinstance(record.get("approved_by"), str) or not record["approved_by"].strip():
        raise AdsWriteRefused("the schedule needs its approver")
    now = _utcnow()
    try:
        approved_at = datetime.fromisoformat(record["approved_at"].replace("Z", "+00:00"))
        if approved_at.utcoffset() is None or approved_at > now:
            raise ValueError("invalid approval time")
    except (KeyError, AttributeError, TypeError, ValueError):
        raise AdsWriteRefused("the schedule needs a valid approval time") from None
    if record.get("decision", "approved") != "approved":
        raise AdsWriteRefused("the schedule is not approved")
    if record.get("weekday_convention") != SCHEDULE_WEEKDAY_CONVENTION:
        raise AdsWriteRefused("the schedule must use Monday-zero weekdays")
    try:
        local = now.astimezone(ZoneInfo(record["timezone"]))
    except (KeyError, TypeError, ValueError, ZoneInfoNotFoundError):
        raise AdsWriteRefused("the schedule needs an IANA timezone") from None
    if (type(payload.get("weekday")) is not int or type(payload.get("hour")) is not int
            or payload["weekday"] != local.weekday() or payload["hour"] != local.hour
            or payload.get("timezone") != record["timezone"]):
        raise AdsWriteRefused("the schedule is not due in its stored timezone")
    if any(record.get(field) != payload.get(field) for field in ("campaign_id", "ad_type", "profile_id")):
        raise AdsWriteRefused("the schedule does not name this campaign and profile")
    operation = payload["operation"]
    value = payload["bid"] if operation == "set_bid" else payload["state"]
    entity_fields = ("ad_group_id", "target_id") if operation == "set_bid" else ("ad_group_id", "ad_ids")
    rules = record.get("rules")
    if not isinstance(rules, list) or not any(
            isinstance(rule, dict) and type(rule.get("weekday")) is int and type(rule.get("hour")) is int
            and rule.get("weekday") == payload["weekday"] and rule.get("hour") == payload["hour"]
            and rule.get("action") == operation and not isinstance(rule.get("value"), bool)
            and rule.get("value") == value
            and all(rule.get(field) == payload.get(field) for field in entity_fields)
            for rule in rules):
        raise AdsWriteRefused("the schedule rule does not approve this action and these entities")
    return record


def _approved_pause_undo(tenant_key, record, payload):
    """Require an exact approved Undo of a sent pause whose recorded prior state was enabled."""
    if not isinstance(record.get("writes"), list):
        raise AdsWriteRefused("an enable Undo needs its exact approved write")
    original_id = payload.get("undo_of")
    if not isinstance(original_id, str) or not original_id or original_id == payload["item_id"]:
        raise AdsWriteRefused("an enable Undo must name the original sent pause")
    original = _read_record(SENT_WRITE_SOURCE, tenant_key, original_id, "sent pause")
    if (not isinstance(original, dict) or original.get("id") != original_id
            or original.get("status") != "sent" or original.get("kind") not in ("bid", "scheduled_change")):
        raise AdsWriteRefused("the original pause was not sent")
    sent = original.get("sent_payload")
    result = original.get("result")
    if (not isinstance(sent, dict) or sent.get("item_id") != original_id
            or sent.get("operation") != "pause_ads" or sent.get("state") != "paused"
            or not isinstance(result, dict) or result.get("sent") is not True
            or result.get("operation") != "pause_ads" or result.get("item_id") != original_id
            or result.get("kind") != original["kind"] or not result.get("approval_id")):
        raise AdsWriteRefused("the original pause needs its sent receipt")
    if sent.get("previous_state") != "enabled":
        raise AdsWriteRefused("the original pause has no recorded enabled prior state")
    fields = ("campaign_id", "ad_type", "profile_id", "ad_group_id", "ad_ids")
    if any(sent.get(field) != payload.get(field) for field in fields):
        raise AdsWriteRefused("the enable Undo does not restore the original paused entities")


def _approved(tenant_key, approval_id, kind, payload):
    """Refuse unless the Operator App stored this approval for this item and this payload."""
    if not isinstance(approval_id, str) or not approval_id.strip():
        raise AdsWriteRefused("a named write needs an approval id")
    item_id = payload.get("item_id")
    if not isinstance(item_id, str) or not item_id:
        raise AdsWriteRefused("a named write needs the item id it was approved for")
    if kind == "scheduled_change":
        return _approved_schedule(tenant_key, approval_id, payload)
    module_name, _, name = APPROVAL_SOURCE.partition(":")
    try:
        reader = getattr(importlib.import_module(module_name), name)
    except Exception:                                                  # noqa: BLE001
        raise AdsWriteRefused("the approval source is not installed") from None
    try:
        record = reader(tenant_key, approval_id)
    except Exception:                                                  # noqa: BLE001
        raise AdsWriteRefused("the approval could not be read") from None
    if not isinstance(record, dict) or record.get("decision") != "approved":
        raise AdsWriteRefused("the approval id is not an approved decision")
    if item_id not in (record.get("item_ids") or ()):
        raise AdsWriteRefused("the approval does not name this item")
    writes = record.get("writes")
    if writes is not None:
        stored = [w for w in writes if isinstance(w, dict) and w.get("item_id") == item_id]
        if not stored or stored[0].get("kind") != kind or stored[0].get("payload") != payload:
            raise AdsWriteRefused("the payload is not the one that was approved")
    if payload.get("operation") == "enable_ads":
        _approved_pause_undo(tenant_key, record, payload)
    return record


def send_named_write(tenant_key, kind, payload, *, approval_id, rt=None):
    """Send one approved named write and return its request, approver and reply."""
    prepared = _build_named(kind, payload)
    key = str(tenant_key or "").strip().lower()
    if not key:
        raise AdsWriteRefused("a named write needs a tenant")
    approval = _approved(key, approval_id, kind, payload)
    approver = approval.get("approved_by") if kind == "scheduled_change" else approval.get("by")
    _log.info("Amazon Ads write approved tenant=%s kind=%s operation=%s approval=%s approver=%s item=%s",
              key, kind, prepared.operation, approval_id, approver, payload["item_id"])
    reply = _send(prepared, key, rt=rt, profile_id=payload.get("profile_id"))
    return {"sent": True, "kind": kind, "operation": prepared.operation,
            "ad_type": prepared.named["ad_type"], "method": prepared.method,
            "path": prepared.path, "approval_id": approval_id, "item_id": payload["item_id"],
            "approved_by": approver, "approved_at": approval.get("approved_at", approval.get("at")),
            "sent_at": _utcnow().isoformat(), "response": reply,
            **({field: payload[field] for field in ("schedule_id", "timezone", "weekday", "hour")}
               if kind == "scheduled_change" else {})}


def request(tenant_key, method, path, *, body=None, query=None, rt=None, profile_id=None, connection_id=None):
    """A report call by method and path. Anything else raises `AdsWriteRefused` before any I/O."""
    return _send(build_request(method, path, body=body, query=query),
                 str(tenant_key or "").strip().lower(), rt=rt, profile_id=profile_id, connection_id=connection_id)


def _admitted(prepared):
    """Re-check at the transport door, so no hand-made object reaches a socket."""
    if not isinstance(prepared, _Prepared) or prepared._seal is not _SEAL:
        return False
    if prepared.named is None:
        if prepared.operation is not None and report_operation(prepared.method, prepared.path) == prepared.operation:
            return True
        if stream_operation(prepared.method, prepared.path) != prepared.operation:
            return False
        try:
            _stream_payload(prepared.operation, prepared.body, prepared.query)
        except AdsWriteRefused:
            return False
        return True
    rule = NAMED_WRITES.get(prepared.named["kind"], {}).get(prepared.named["operation"])
    return bool(rule) and rule["endpoints"].get(prepared.named["ad_type"]) == (prepared.method, prepared.path)


def _send(prepared, tenant_key, *, rt=None, profile_id=None, connection_id=None):
    if not _admitted(prepared):
        raise AdsWriteRefused("the request did not come from the request builder")
    if fixture_mode():
        headers = _headers(prepared, FIXTURE.credential(tenant_key), FIXTURE_TOKEN, profile_id)
        return FIXTURE.answer(prepared, tenant_key, profile_id, headers)
    return _live(prepared, tenant_key, rt=rt, profile_id=profile_id, connection_id=connection_id)


# --------------------------------------------------------------------------- live transport

_NO_CREDENTIAL = ("No Amazon Ads credential is stored for this tenant. "
                  "Connect Amazon Ads under Amazon Ads Setup.")


def credential(tenant_key, rt=None, connection_id=None):
    """The tenant's stored Amazon Ads credential fields, or None. The keychain is the only source."""
    try:
        import core.keychain as kc
        bound = getattr(rt, "key", None) or getattr(getattr(rt, "tenant", None), "key", None)
        if bound != tenant_key:
            return None
        fields = kc.amazon_ads_creds(rt, connection_id=connection_id)
    except Exception:                                                  # noqa: BLE001
        return None
    if not isinstance(fields, dict) or not all(fields.get(f) for f in CREDENTIAL_FIELDS):
        return None
    return fields


def _token(fields):
    data = urllib.parse.urlencode({"grant_type": "refresh_token",
                                   "refresh_token": fields["refresh_token"],
                                   "client_id": fields["client_id"],
                                   "client_secret": fields["client_secret"]}).encode()
    req = urllib.request.Request(LWA_TOKEN_URL, data=data, method="POST",
                                 headers={"Content-Type": "application/x-www-form-urlencoded"})
    try:
        with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
            return json.loads(r.read().decode("utf-8", "replace"))["access_token"]
    except Exception as exc:                                           # noqa: BLE001
        raise AdsError(f"Amazon Ads sign in failed ({type(exc).__name__})") from None


def _headers(prepared, fields, token, profile_id=None):
    """The headers one admitted call sends. A v1 call names its account in the body, not a scope."""
    if prepared.operation in REPORT_OPERATIONS:
        return {"Authorization": f"Bearer {token}", **dict.fromkeys(V1_CLIENT_HEADERS, fields["client_id"]),
                "Content-Type": "application/json", "Accept": "application/json"}
    headers = {"Authorization": f"Bearer {token}",
               "Amazon-Advertising-API-ClientId": fields["client_id"],
               "Amazon-Advertising-API-Scope": str(profile_id or fields["profile_id"]),
               "Content-Type": "application/json", "Accept": "application/json"}
    if prepared.operation in STREAM_OPERATIONS:
        headers["Content-Type"] = STREAM_CONTENT_TYPE
        headers["Accept"] = STREAM_CONTENT_TYPE
    return headers


def _errors(detail):
    """Amazon's error entries from an error body, each with its code, message and fieldLocation."""
    if not isinstance(detail, dict):
        return []
    entries = detail["errors"] if isinstance(detail.get("errors"), list) else [detail]
    return [{"code": str(e.get("code") or ""), "message": str(e.get("details") or e.get("message") or ""),
             "fieldLocation": str(e.get("fieldLocation") or "")}
            for e in entries if isinstance(e, dict) and (e.get("code") or e.get("details") or e.get("message"))]


def _error_text(errors):
    """Amazon's errors as one line a person reads, verbatim, cut to `ERROR_TEXT_LIMIT`."""
    return " ".join(" ".join(filter(None, (e["code"] + ":" if e["code"] else "", e["message"],
                                           f"(field {e['fieldLocation']})" if e["fieldLocation"] else "")))
                    for e in errors)[:ERROR_TEXT_LIMIT]


def _rejection(prefix, errors, *, may_be_unoffered=True):
    """The exception for Amazon's errors: not offered when Amazon says so, else rejected."""
    text = _error_text(errors)
    if may_be_unoffered and re.search(r"not (?:supported|offered|available)", text, re.I):
        return AdsReportUnavailable(f"Amazon does not offer this report: {text}", errors)
    return AdsRejected(f"{prefix}: {text}" if text else prefix, errors)


def _live(prepared, tenant_key, *, rt=None, profile_id=None, connection_id=None):
    fields = credential(tenant_key, rt, connection_id=connection_id)
    if fields is None:
        raise AdsError(_NO_CREDENTIAL)
    if prepared.operation in STREAM_OPERATIONS and (
            str(profile_id or fields["profile_id"]) != str(fields["profile_id"])
            or str(fields.get("region") or DEFAULT_REGION).lower() != "na"):
        raise AdsWriteRefused("the stream scope must match the stored NA business profile")
    host = HOSTS.get(str(fields.get("region") or DEFAULT_REGION).lower(), HOSTS[DEFAULT_REGION])
    url = f"{host}/{prepared.path}"
    if prepared.query:
        url += "?" + urllib.parse.urlencode(prepared.query)
    headers = _headers(prepared, fields, _token(fields), profile_id)
    data = json.dumps(prepared.body).encode() if prepared.body is not None else None
    req = urllib.request.Request(url, data=data, method=prepared.method, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=_TIMEOUT) as r:
            return json.loads(r.read().decode("utf-8", "replace") or "{}")
    except urllib.error.HTTPError as exc:
        try:
            detail = json.loads(exc.read().decode("utf-8", "replace") or "{}")
        except Exception:                                              # noqa: BLE001 an unreadable body still raises its status
            detail = {}
        raise _rejection(f"Amazon Ads answered HTTP {exc.code} on {prepared.operation}", _errors(detail),
                         may_be_unoffered=exc.code == 400) from None
    except Exception as exc:                                           # noqa: BLE001
        raise AdsError(f"Amazon Ads could not be reached ({type(exc).__name__})") from None


# --------------------------------------------------------------------------- reports

_REPORT_LOCKS = {}
_REPORT_LOCKS_GUARD = threading.Lock()
#: Process caches: the advertiser account per connection, the optional fields Amazon refused per
#: (client id, group) with Amazon's text, and the report file URLs a retrieve returned.
_ACCOUNTS = {}
_REFUSED = {}
_ISSUED_FILES = set()


class GroupReport(NamedTuple):
    """One finished group report: its id, flat rows per member table, and notes a person reads."""
    report_id: str
    rows: dict
    notes: tuple


def _report_lock(client_id):
    """One lock per client ID: Amazon runs one report at a time for each app login."""
    with _REPORT_LOCKS_GUARD:
        return _REPORT_LOCKS.setdefault(str(client_id), threading.Lock())


def _report_credential(tenant_key, rt, connection_id):
    """The credential a report runs under: its client id keys the lock, its profile names the account."""
    if fixture_mode():
        return FIXTURE.credential(tenant_key)
    fields = credential(tenant_key, rt, connection_id=connection_id)
    if fields is None:
        raise AdsError(_NO_CREDENTIAL)
    return fields


def _lists_profile(account, profile_id):
    return (isinstance(account, dict) and bool(account.get("advertiserAccountId"))
            and any(isinstance(alt, dict) and str(alt.get("profileId")) == str(profile_id)
                    for alt in account.get("alternateIds") or ()))


def _advertiser_account(tenant_key, *, rt, profile_id, connection_id):
    """The v1 `advertiserAccountId` whose alternate ids carry the stored profile id, cached per connection."""
    key, token = (tenant_key, connection_id or "", str(profile_id)), None
    while key not in _ACCOUNTS:
        page = request(tenant_key, "POST", REPORT_OPERATIONS["queryAdvertiserAccounts"][1],
                       body={"maxResults": 100, **({"nextToken": token} if token else {})},
                       rt=rt, profile_id=profile_id, connection_id=connection_id)
        match = next((a for a in page.get("advertiserAccounts") or () if _lists_profile(a, profile_id)), None)
        token = page.get("nextToken")
        if match is not None:
            _ACCOUNTS[key] = str(match["advertiserAccountId"])
        elif not token:
            raise AdsError(f"No Amazon Ads advertiser account lists profile {profile_id}. "
                           f"Check the profile ID on this Amazon Ads connection.")
    return _ACCOUNTS[key]


def _create_body(group, start, end, account, fields):
    """A CreateReportRequest for one group and window, filtered to the group's ad products."""
    from harness import amazon_ads_schema as schema
    return {"accessRequestedAccounts": [{"advertiserAccountId": account}],
            "reports": [{"format": "GZIP_JSON",
                         "periods": [{"datePeriod": {"startDate": start.isoformat(), "endDate": end.isoformat()}}],
                         "query": {"fields": list(fields),
                                   "filter": {"on": {"field": schema.AD_PRODUCT_FIELD, "comparisonOperator": "IN",
                                                     "not": False, "values": list(group.tables)}}}}]}


def _first_report(reply, operation):
    """The one report a 207 multi-status answer carries, or its errors raised verbatim."""
    errors = [e for entry in reply.get("error") or () if isinstance(entry, dict)
              for e in _errors({"errors": entry.get("errors") or []})]
    if errors or reply.get("error"):
        raise _rejection(f"Amazon Ads refused {operation}", errors)
    for entry in reply.get("success") or ():
        report = entry.get("report") if isinstance(entry, dict) else None
        if isinstance(report, dict) and re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", str(report.get("reportId") or "")):
            return report
    raise AdsError(f"Amazon Ads returned no report on {operation}")


def _named_fields(exc, fields):
    """The requested fields an error names, by id in its text or by index in its field location."""
    text = " ".join([str(exc)] + [e["fieldLocation"] for e in exc.errors])
    named = {f for f in fields if re.search(rf"(?<![\w.]){re.escape(f)}(?!\w)", text)}
    named.update(fields[int(i)] for i in re.findall(r"fields\[(\d+)\]", text) if int(i) < len(fields))
    return named


def _create(tenant_key, group, start, end, account, refused, opts):
    """Create one group report. An error naming only optional fields drops them and creates again."""
    while True:
        fields = group.fields(drop=refused)
        try:
            reply = request(tenant_key, "POST", REPORT_OPERATIONS["createReport"][1],
                            body=_create_body(group, start, end, account, fields), **opts)
            return _first_report(reply, "createReport")
        except AdsRejected as exc:
            named = _named_fields(exc, fields)
            if not named or named & set(group.core):
                raise
            refused.update(dict.fromkeys(sorted(named), _error_text(exc.errors) or str(exc)))


def _await(tenant_key, report_id, opts, *, sleep, now, limit):
    """Poll retrieve about once a minute until the report completes. -> its report file URLs."""
    started = now()
    while True:
        report = _first_report(request(tenant_key, "POST", REPORT_OPERATIONS["retrieveReport"][1],
                                       body={"reportIds": [report_id]}, **opts), "retrieveReport")
        state = str(report.get("status") or "").upper()
        if state == "COMPLETED":
            urls = [str(part.get("url") or "") for part in report.get("completedReportParts") or ()
                    if isinstance(part, dict)]
            _ISSUED_FILES.update(urls)
            return urls
        if state == "FAILED":
            reason = " ".join(filter(None, (str(report.get("failureCode") or ""),
                                            str(report.get("failureReason") or ""))))[:ERROR_TEXT_LIMIT] or state
            if re.search(r"not (?:supported|offered|available)", reason, re.I):
                raise AdsReportUnavailable(f"Amazon does not offer this report: {reason}")
            raise AdsError(f"Amazon Ads report {report_id} ended FAILED: {reason}")
        elapsed = now() - started
        if elapsed > REPORT_MAX_WAIT_SECONDS:
            raise AdsReportPending(f"Amazon Ads report {report_id} did not finish in 3 hours", report_id)
        if limit is not None and elapsed >= limit:
            raise AdsReportPending(f"Amazon Ads report {report_id} is still being prepared", report_id)
        pause = 0 if fixture_mode() else REPORT_POLL_SECONDS
        sleep(pause if limit is None else min(pause, limit - elapsed))


def _flat(row, prefix=""):
    """A nested v1 row -> flat dotted field ids. A flat row stays as it is."""
    out = {}
    for key, value in row.items():
        if isinstance(value, dict):
            out.update(_flat(value, f"{prefix}{key}."))
        else:
            out[f"{prefix}{key}"] = value
    return out


def _part_rows(raw):
    """One report file -> flat rows. GZIP or plain, a JSON array or JSON lines."""
    try:
        text = (gzip.decompress(raw) if raw[:2] == b"\x1f\x8b" else raw).decode("utf-8", "replace").strip()
        if not text:
            return []
        try:
            data = json.loads(text)
        except ValueError:
            data = [json.loads(line) for line in text.splitlines() if line.strip()]
    except (OSError, EOFError, ValueError) as exc:
        raise AdsError(f"Amazon Ads sent a report file Loopable cannot read ({type(exc).__name__})") from None
    return [_flat(row) for row in (data if isinstance(data, list) else [data]) if isinstance(row, dict)]


def _read_file(url):
    """GET one report file with no Ads header. Only an https S3 URL a retrieve returned is admitted."""
    parts = urllib.parse.urlsplit(str(url or ""))
    host = parts.hostname or ""
    if parts.scheme != "https" or not host.endswith(REPORT_FILE_HOST_SUFFIX) or url not in _ISSUED_FILES:
        raise AdsWriteRefused(f"{parts.scheme or 'no scheme'} {_safe_path(host)} is not a report file Amazon returned")
    _ISSUED_FILES.discard(url)
    headers = {}
    if fixture_mode():
        return _part_rows(FIXTURE.download(url, headers))
    try:
        with urllib.request.urlopen(urllib.request.Request(url, method="GET", headers=headers),
                                    timeout=_TIMEOUT) as r:
            raw = r.read()
    except Exception as exc:                                           # noqa: BLE001 the URL carries a signature: never echo it
        raise AdsError(f"Amazon Ads report file could not be read ({type(exc).__name__})") from None
    return _part_rows(raw)


def _split(group, rows):
    """Flat rows -> {member table: rows} by `adProduct.value`, and a note for rows no member takes."""
    from harness import amazon_ads_schema as schema
    out, tables, stray = {table: [] for table in group.members}, group.tables, 0
    for row in rows:
        table = tables.get(str(row.get(schema.AD_PRODUCT_FIELD) or "").upper())
        if table is None or not row.get(schema.vendor_name("date")):
            stray += 1
        else:
            out[table].append(row)
    note = (f"Amazon Ads sent {stray} rows with no date or with another ad product. Loopable left them out.",)
    return out, note if stray else ()


def run_group_report(tenant_key, group, start, end, *, rt=None, profile_id=None, connection_id=None,
                     sleep=time.sleep, now=time.monotonic, max_wait=None, report_id=None):
    """Create one Reporting v1 group report, wait for it, and read every file. -> GroupReport.

    `max_wait` caps this call's poll loop in seconds. `report_id` resumes that report without a create.
    """
    from harness import amazon_ads_schema as schema
    group = schema.GROUPS[group] if isinstance(group, str) else group
    if (end - start).days + 1 > MAX_DAYS_PER_REQUEST:
        raise ValueError(f"a report window is at most {MAX_DAYS_PER_REQUEST} days")
    fields = _report_credential(tenant_key, rt, connection_id)
    opts = {"rt": rt, "profile_id": str(profile_id or fields["profile_id"]), "connection_id": connection_id}
    refused = _REFUSED.setdefault((str(fields["client_id"]), group.name), {})
    limit = None if max_wait is None else max(0.0, min(float(max_wait), REPORT_MAX_WAIT_SECONDS))
    with _report_lock(fields["client_id"]):
        if report_id is None:
            account = _advertiser_account(tenant_key, **opts)
            report_id = _create(tenant_key, group, start, end, account, refused, opts)["reportId"]
        urls = _await(tenant_key, str(report_id), opts, sleep=sleep, now=now, limit=limit)
        rows = [row for url in urls for row in _read_file(url)]
    split, stray = _split(group, rows)
    notes = tuple(f"Amazon Ads refused the field {field} on this report, so Loopable reads it without that "
                  f"field. Amazon said: {text}" for field, text in refused.items())
    return GroupReport(str(report_id), split, notes + stray)


def run_report(tenant_key, table, start, end, **options):
    """One table's rows from its group report. -> (report_id, rows). The store reads `run_group_report`."""
    from harness import amazon_ads_schema as schema
    group = schema.group_of(table)
    if group is None:
        raise AdsReportUnavailable(f"Amazon Reporting v1 offers no report for {schema.short_name(table)}")
    result = run_group_report(tenant_key, group, start, end, **options)
    return result.report_id, result.rows[schema.short_name(table)]


# --------------------------------------------------------------------------- recording fixture

FIXTURE_TOKEN = "fixture-access-token"
FIXTURE_CREDENTIAL = {"client_id": "amzn1.application-oa2-client.fixture", "client_secret": "fixture",
                      "refresh_token": "fixture", "profile_id": "1000000001", "region": "na"}
FIXTURE_FILE_HOST = "https://fixture-ads-reports.s3.amazonaws.com"
FIXTURE_CREATED = "2026-10-20T09:00:00Z"
_FIXTURE_PREFIX = {"SPONSORED_PRODUCTS": ("71", "SP"), "SPONSORED_BRANDS": ("72", "SB"),
                   "SPONSORED_DISPLAY": ("73", "SD")}
#: Per campaign and day: the metric totals every finer row splits evenly.
_FIXTURE_TOTALS = {"metric.impressions": 400, "metric.clicks": 12, "metric.totalCost": 5.0,
                   "metric.sales": 38.0, "metric.purchases": 4, "metric.unitsSold": 4}


def _multi_status(report=None, errors=None):
    """A ReportMultiStatusResponse with one success or one error entry at index 0."""
    return {"success": [{"index": 0, "report": report}] if report else [],
            "error": [{"index": 0, "errors": errors}] if errors else []}


class _Fixture:
    """The recording fixture `AMAZON_ADS_FIXTURE=1` routes to, in the saved contracts' v1 shapes.

    It records method, path, operation, headers and body of every call, report file downloads
    included. Toggles: `drop_days`, `unsupported` (group names that end FAILED), `refuse_fields`
    (a create naming one answers 400), `nested` (files carry nested JSON lines), `responder`.
    """

    FILES = 2

    def __init__(self):
        self.reset()

    def reset(self):
        self.calls, self.reports, self.subscriptions, self.credentials = [], {}, {}, {}
        self.in_flight = self.max_in_flight = 0
        self.drop_days, self.unsupported, self.refuse_fields = set(), set(), set()
        self.nested = False
        self.responder = None

    def credential(self, tenant_key):
        """The fixture credential for one tenant. `credentials[tenant]` overrides its fields."""
        return {**FIXTURE_CREDENTIAL, **self.credentials.get(tenant_key, {})}

    def answer(self, prepared, tenant_key, profile_id, headers=None):
        self.calls.append({"method": prepared.method, "path": prepared.path,
                           "operation": prepared.operation, "body": prepared.body,
                           "query": dict(prepared.query), "tenant": tenant_key, "headers": dict(headers or {}),
                           "named": dict(prepared.named) if prepared.named else None})
        if self.responder is not None:
            return self.responder(prepared)
        if prepared.operation == "listStreamSubscriptions":
            return {"subscriptions": list(self.subscriptions.get((tenant_key, profile_id), {}).values())}
        if prepared.operation == "createStreamSubscription":
            subscriptions = self.subscriptions.setdefault((tenant_key, profile_id), {})
            token = prepared.body["clientRequestToken"]
            if token not in subscriptions:
                subscriptions[token] = {**prepared.body, "subscriptionId": f"stream{len(subscriptions) + 1}",
                                        "status": "PENDING_CONFIRMATION"}
            return dict(subscriptions[token])
        if prepared.named is not None:
            items = next(iter(prepared.body.values()))
            return {"success": [{"index": i} for i in range(len(items))], "error": []}
        if prepared.operation == "queryAdvertiserAccounts":
            return self._accounts(prepared.body, profile_id)
        if prepared.operation == "createReport":
            return self._create(prepared.body)
        return self._retrieve(prepared.body["reportIds"][0])

    def _accounts(self, body, profile_id):
        """Two pages: an unrelated account, then the account that lists the caller's profile."""
        if not body.get("nextToken"):
            return {"advertiserAccounts": [{"advertiserAccountId": "amzn1.ads-account.g.fxother",
                                            "alternateIds": [{"profileId": "999", "countryCode": "CA"}]}],
                    "nextToken": "fixture-page-2"}
        return {"advertiserAccounts": [{"advertiserAccountId": f"amzn1.ads-account.g.fx{profile_id}",
                                        "alternateIds": [{"profileId": str(profile_id), "countryCode": "US",
                                                          "entityId": "ENTITYFX"}]}]}

    def _create(self, body):
        if not (body.get("accessRequestedAccounts") or [{}])[0].get("advertiserAccountId"):
            return _multi_status(errors=[{"code": "400001", "message": "An advertiser account is required.",
                                          "fieldLocation": "accessRequestedAccounts"}])
        refused = [f for f in body["reports"][0]["query"]["fields"] if f in self.refuse_fields]
        if refused:
            raise _rejection("Amazon Ads answered HTTP 400 on createReport",
                             [{"code": "400004", "message": f"Field {refused[0]} is invalid for this request.",
                               "fieldLocation": ""}], may_be_unoffered=False)
        report_id = f"fx{len(self.reports) + 1:05d}"
        self.in_flight += 1
        self.max_in_flight = max(self.max_in_flight, self.in_flight)
        self.reports[report_id] = {"body": body, "polls": 0, "files": None, "done": False}
        return _multi_status(self._record(report_id, "PENDING"))

    def _record(self, report_id, status, **extra):
        """A contract `Report`: every required key, the request's format, periods and query echoed."""
        request = self.reports[report_id]["body"]["reports"][0]
        return {"reportId": report_id, "status": status, "format": request["format"],
                "periods": request["periods"], "query": request["query"],
                "creationDateTime": FIXTURE_CREATED, "lastUpdatedDateTime": FIXTURE_CREATED, **extra}

    def _retrieve(self, report_id):
        from harness import amazon_ads_schema as schema
        report = self.reports[report_id]
        report["polls"] += 1
        query = report["body"]["reports"][0]["query"]
        group = schema.group_for(query["fields"], query["filter"]["on"]["values"])
        if group is not None and group.name in self.unsupported:
            self._finish(report)
            return _multi_status(self._record(report_id, "FAILED", failureCode="REPORT_NOT_SUPPORTED",
                                              failureReason="This report is not supported for this advertiser."))
        if report["polls"] < 2:
            return _multi_status(self._record(report_id, "PROCESSING"))
        if report["files"] is None:
            rows = fixture_rows(report["body"], drop_days=self.drop_days)
            report["files"] = {f"{FIXTURE_FILE_HOST}/{report_id}/part-{i}.json.gz?X-Amz-Signature=fx{report_id}{i}":
                               _fixture_file(rows[i::self.FILES], self.nested) for i in range(self.FILES)}
        return _multi_status(self._record(report_id, "COMPLETED", completedDateTime=FIXTURE_CREATED, completedReportParts=[
            {"url": url, "sizeInBytes": len(raw), "urlExpirationDateTime": "2026-12-31T00:00:00Z"}
            for url, raw in report["files"].items()]))

    def _finish(self, report):
        if not report["done"]:
            report["done"] = True
            self.in_flight -= 1

    def download(self, url, headers):
        """Serve one report file and record the GET with the headers the client sent."""
        self.calls.append({"method": "GET", "path": url, "operation": "downloadReportPart", "body": None,
                           "query": {}, "tenant": None, "headers": dict(headers), "named": None})
        report = self.reports[urllib.parse.urlsplit(url).path.split("/")[1]]
        raw = report["files"][url]
        report.setdefault("read", set()).add(url)
        if report["read"] == set(report["files"]):
            self._finish(report)
        return raw


def _fixture_file(rows, nested):
    """GZIP JSON: an array of flat rows, or nested objects one per line."""
    def nest(row):
        out = {}
        for field, value in row.items():
            head, _, tail = field.partition(".")
            out.setdefault(head, {})[tail] = value
        return out
    text = "\n".join(json.dumps(nest(r)) for r in rows) if nested else json.dumps(rows)
    return gzip.compress(text.encode("utf-8"))


def _fixture_query(body):
    report = body["reports"][0]
    period = report["periods"][0]["datePeriod"]
    return (report["query"]["fields"], report["query"]["filter"]["on"]["values"],
            date.fromisoformat(period["startDate"]), date.fromisoformat(period["endDate"]))


def _fixture_days(start, end, drop_days):
    return [start + timedelta(days=i) for i in range((end - start).days + 1)
            if (start + timedelta(days=i)).isoformat() not in drop_days]


def fixture_totals(body, *, drop_days=()):
    """The fixture's own totals for one create body. -> {(ad product, date, campaign id): {field: total}}."""
    _fields, products, start, end = _fixture_query(body)
    out = {}
    for day in _fixture_days(start, end, drop_days):
        for index, product in enumerate(products):
            for c in (1, 2):
                n = day.toordinal() % 7 + c + index
                out[(product, day.isoformat(), f"{_FIXTURE_PREFIX[product][0]}10{c}")] = {
                    field: total * n for field, total in _FIXTURE_TOTALS.items()}
    return out


def fixture_rows(body, *, drop_days=()):
    """Deterministic v1 rows for one create body: one row per distinct value of every requested
    dimension and day, only the requested fields and ad products. Two ad groups split a campaign."""
    fields, _products, start, end = _fixture_query(body)
    groups = (1, 2) if "adGroup.id" in fields else (0,)
    out = []
    for (product, day, campaign), totals in fixture_totals(body, drop_days=drop_days).items():
        prefix, short = _FIXTURE_PREFIX[product]
        c = campaign[-1]
        for g in groups:
            row = {"date.value": day, "adProduct.value": product, "campaign.id": campaign,
                   "campaign.name": f"{short} campaign {c}", "campaign.deliveryStatus": "DELIVERING",
                   "campaign.budgetAmount": 25 * int(c), "budgetCurrency.value": "USD",
                   "adGroup.id": f"{prefix}20{c}{g}", "adGroup.name": f"Ad group {c}.{g}",
                   "adGroupTarget.id": f"{prefix}30{c}{g}", "target.value": f"term {c}{g}",
                   "target.matchType": "EXACT", "adGroupTarget.bid": str(0.5 + g / 10),
                   "ad.id": f"{prefix}40{c}{g}", "advertisedProduct.id": f"B0FX{prefix}{c}{g}00",
                   "advertisedProductMarketplace.value": "ATVPDKIKX0DER", "advertisedProductSku.value": f"SKU-{c}{g}",
                   "searchTerm.value": f"search {c}{g}",
                   **{f: (t // len(groups) if isinstance(t, int) else t / len(groups)) for f, t in totals.items()}}
            out.append({f: row[f] for f in fields})
    return out


FIXTURE = _Fixture()


def _reset_caches():
    _ACCOUNTS.clear()
    _REFUSED.clear()
    _ISSUED_FILES.clear()


@contextmanager
def recording_fixture():
    """Route every call to a fresh recording fixture and fresh report caches for the block. -> the fixture."""
    previous = os.environ.get(FIXTURE_ENV)
    os.environ[FIXTURE_ENV] = "1"
    FIXTURE.reset()
    _reset_caches()
    try:
        yield FIXTURE
    finally:
        FIXTURE.reset()
        _reset_caches()
        if previous is None:
            os.environ.pop(FIXTURE_ENV, None)
        else:
            os.environ[FIXTURE_ENV] = previous


__all__ = ["KEY", "LABEL", "ENTRY_TYPE", "FIXTURE_ENV", "HOSTS", "REPORT_OPERATIONS", "V1_CLIENT_HEADERS",
           "NAMED_WRITES", "STREAM_OPERATIONS", "STREAM_CONTENT_TYPE", "stream_operation",
           "FIELD_RULES", "APPROVAL_SOURCE", "SCHEDULE_APPROVAL_SOURCE", "SENT_WRITE_SOURCE",
           "SCHEDULE_WEEKDAY_CONVENTION", "REPORT_CONCURRENCY", "REPORTS_PER_DAY",
           "MAX_DAYS_PER_REQUEST", "AdsError", "AdsWriteRefused", "AdsRejected", "AdsReportUnavailable",
           "AdsReportPending", "GroupReport", "fixture_mode", "build_request", "report_operation",
           "send_named_write", "request", "credential", "run_group_report", "run_report", "FIXTURE",
           "recording_fixture", "fixture_rows", "fixture_totals"]