Spaces:
Running

File size: 70,674 Bytes
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
7f72224
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
"""Amazon operator App: daily ad proposals on SP, SB and SD, gated by profit after COGS and stock cover.

The agent proposes and a person approves a batch before any write (R14). `set_status(..., "approved")`
is the one approve path: it stores one approval record, then sends one named Ads write per proposal
through `_ads_client()`. Rules per SKU, every threshold an App setting (R48, R49):
  stop   cover under `stop_cover_days`: pause the ad group's ads for the SKU. A stopped SKU gets no raise.
  pause  linked SKU with profit after COGS under `pause_below_profit`: pause the same way.
  raise  cover over `raise_cover_days` and a linked SKU at or above the pause line: bid up `bid_step_pct`.
  budget a campaign whose every evaluated SKU got a raise: daily budget up `budget_step_pct`.
  negative keyword: a search term with clicks, spend and no orders over the lookback.
An unlinked SKU (blank COGS) gets no profit-gated proposal and a held note that says why.

Inputs: COGS from the `ut_amazon_sku_profit` table (`cogs_per_unit`, linked SKUs only), cover from
the mirror `amzn_inventory_planning` (`days_of_supply`, latest snapshot per SKU), ad rows from the
Ads tables named by `_ads_table`. This module imports no other App at import time, so deleting any App
leaves it whole, and deleting this App removes only the documents in `KEYS` (rule 13).

C7 inbox: `pull_app_proposals` imports each module in `PROPOSAL_SOURCES` lazily, reads its C4
`proposals()` into `amazon_operator_inbox`, and a decision on an inbox item calls that module's
`on_decision`. An App proposal never reaches the Ads client: it is a decision handed back, not a write.

Store documents (tenant runtime store, App owned, never the mirror and never a `ut_amzn_*` table):
  amazon_operator_settings  thresholds and the default owner
  amazon_operator_days      {latest, days: {day: {built_at, data_date, items, held, spend, ...}}}
  amazon_operator_baseline  the 60 day ad profit after COGS baseline and the R13 time baseline
  amazon_operator_decisions {decisions: {id: {id, decision, by, at, item_ids, note, writes}}}
  amazon_operator_outcomes  {items: {item id: {status, cause, decision_id, at, kind}}}
  amazon_operator_inbox     {items: {inbox id: {source_kind, source_module, item_id, sku, action, reason, app, status}}}

Limit (rule 1): each document is one JSON value, and the Postgres store refuses a document over
`core.store_pg.DOCUMENT_CEILING_BYTES` (128 MB). At about 1 KB a proposal, the days document reaches
it near 120,000 proposals. Nothing here caps rows, proposals or pages. The fix when it nears:
split `amazon_operator_days` by month.
"""
import base64
import contextlib
import copy
import datetime as dt
import hashlib
import json
import logging
import math
import uuid
from pathlib import Path

SOURCE_KIND = "amazon_operator"
AD_TYPES = ("sp", "sb", "sd")
#: validate() sums every Ads type on its own list, so a build that skips one cannot tie.
ALL_AD_TYPES = ("sp", "sb", "sd")
AD_LABELS = {"sp": "Sponsored Products", "sb": "Sponsored Brands", "sd": "Sponsored Display"}
REPORTS = ("campaigns", "targeting", "advertised_products", "search_terms")

KEY_SETTINGS = "amazon_operator_settings"
KEY_DAYS = "amazon_operator_days"
KEY_BASELINE = "amazon_operator_baseline"
KEY_DECISIONS = "amazon_operator_decisions"
KEY_OUTCOMES = "amazon_operator_outcomes"
KEY_INBOX = "amazon_operator_inbox"
#: Every store document this App owns. remove() deletes these and nothing else.
KEYS = (KEY_SETTINGS, KEY_DAYS, KEY_BASELINE, KEY_DECISIONS, KEY_OUTCOMES, KEY_INBOX)

#: C7: the App modules whose C4 proposals() feed the inbox, imported lazily by name, in this order.
PROPOSAL_SOURCES = ("modules.restock_planner", "modules.reimbursements", "modules.payouts",
                    "modules.account_health", "modules.returns_repeat", "modules.aged_stock",
                    "modules.opportunity_finder")
#: The App's label when its module carries no APP_LABEL.
APP_LABELS = {"restock_planner": "Restock planner", "reimbursements": "Reimbursements", "payouts": "Payouts and cash",
              "account_health": "Account health", "returns_repeat": "Returns and repeat",
              "aged_stock": "Aged stock", "opportunity_finder": "Opportunity finder"}
#: Inbox statuses. `stale` is an item its App no longer lists; it cannot be approved.
INBOX_OPEN = ("proposed",)
#: The `kind` of an inbox item, and the `source` of a decision record on App items.
APP_KIND = "app"
STALE = "This item is no longer open in its App."
APPROVED_NOTE = "Approved in the Operator inbox."

PROFIT_TABLE = "ut_amazon_sku_profit"
PLANNING_TABLE = "amzn_inventory_planning"

DEFAULTS = {"stop_cover_days": 14, "raise_cover_days": 90, "pause_below_profit": 0.0,
            "bid_step_pct": 10.0, "budget_step_pct": 10.0, "lookback_days": 14,
            "negative_min_clicks": 10, "negative_min_cost": 5.0}
_INTS = ("stop_cover_days", "raise_cover_days", "lookback_days", "negative_min_clicks")
STATUSES = ("proposed", "approved", "sent", "refused", "dismissed")
OPEN = ("proposed",)
#: The statuses a person sets. `sent` and `refused` are outcomes that only the write records.
DECISIONS = ("approved", "dismissed")
#: Fields a decision or an outcome writes on a proposal. A same day rebuild carries every one over.
DECIDED_FIELDS = ("status", "owner", "due", "decision_id", "decided_by", "decided_at", "note", "cause",
                  "outcome_at", "result", "sent_payload")
NOT_INSTALLED = "The Amazon Ads connector is not installed."
NOT_FOUND = "That proposal does not exist."
READ_ONLY = "Your account can view these proposals but not approve or dismiss them."
DUE_DAYS = 1
BASELINE_DAYS = 60
TIME_BASELINE = {"low": 10, "high": 20, "unit": "hours per week", "source": "R13, R52",
                 "basis": "Jake's stated ads time before Loopable. No time log exists."}
BAR = {"ads_hours_per_week_under": 3, "profit_after_cogs": "level or up", "days": 60, "source": "R15, R52"}
BASELINE_BASIS = ("Ad sales minus ad cost minus ad orders times COGS per unit, for linked SKUs only. "
                  "Ad orders stand in for units. Unlinked SKUs are left out and counted.")
NO_COGS = "No COGS yet. Link this SKU in Amazon SKU profit."
NO_SKU = "No SKU on this ad. Its ASIN matches no SKU in Amazon SKU profit or inventory planning."
NO_PROFIT = "No profit after COGS yet. Refresh Amazon SKU profit."
NO_COVER = "No cover yet. Inventory planning has no days of supply for this SKU."
NO_CLICKS = "No clicks in the lookback, so there is no bid to raise."
LIMIT = ("Each Amazon operator document is limited to 128 MB by the store. About 120,000 proposals "
         "fit in one. Split the days document by month when it nears that size.")

_log = logging.getLogger(__name__)


def _now():
    return dt.datetime.now(dt.timezone.utc)


def _stamp(at):
    return at.strftime("%Y-%m-%dT%H:%M:%SZ")


def _num(value):
    """A finite float, or None for a blank or unreadable cell."""
    if value is None or (isinstance(value, str) and not value.strip()):
        return None
    try:
        number = float(value)
    except (TypeError, ValueError):
        return None
    return number if math.isfinite(number) else None


def _money(value):
    return f"{value:.2f}"


def _days(value):
    return str(int(value)) if float(value).is_integer() else f"{value:.1f}"


def _earns(net):
    """'makes 5.00' or 'loses 12.50': a negative profit is never printed after 'makes'."""
    return f"loses {_money(-net)}" if net < 0 else f"makes {_money(net)}"


def _rt(tenant_key, st=None):
    """The tenant runtime store handle (get and update), or raise when it cannot be resolved."""
    if st is not None:
        return st
    from harness import amazon_store
    rt = amazon_store._runtime_for(tenant_key)
    if rt is None:
        raise RuntimeError(f"The store for tenant {tenant_key!r} could not be opened.")
    return rt


def _doc(st, key):
    value = st.get(key)
    return value if isinstance(value, dict) else {}


# --------------------------------------------------------------------------- mirror and Ads reads

def _mirror_path(tenant_key, st):
    from harness import amazon_store
    rt = st if hasattr(st, "datastore_path") else None
    return amazon_store._tenant_mirror_path(tenant_key, rt)


@contextlib.contextmanager
def _reader(tenant_key, st):
    """A read-only cursor on the tenant mirror, or None when the mirror file does not exist."""
    path = Path(_mirror_path(tenant_key, st))
    if not path.exists():
        yield None
        return
    from harness import datastore
    try:
        shared = Path(datastore.DB_PATH).resolve() == path.resolve()
    except Exception:                                                  # noqa: BLE001
        shared = False
    # The process holds one writer on its own mirror: a separate read-only connect would refuse.
    if shared:
        cur = datastore.ro_cursor()
        try:
            yield cur
        finally:
            cur.close()
        return
    import duckdb
    con = duckdb.connect(str(path), read_only=True)
    try:
        yield con
    finally:
        con.close()


def _ads_table(ad_type, report):
    """The mirror table for one Ads report. Every Ads read resolves its table name here."""
    plain = f"amzn_ads_{ad_type}_{report}"
    try:
        from harness import amazon_ads_store
    except Exception:                                                  # noqa: BLE001
        return plain
    namer = getattr(amazon_ads_store, "table_name", None)
    if callable(namer):
        try:
            name = str(namer(f"{ad_type}_{report}"))
        except Exception:                                              # noqa: BLE001
            return plain
        if name.startswith("amzn_ads_"):
            return name
    return plain


def _columns(cur, table):
    try:
        return {r[0] for r in cur.execute(
            "SELECT column_name FROM information_schema.columns WHERE table_name = ?", [table]).fetchall()}
    except Exception:                                                  # noqa: BLE001
        return set()


def _text(cols, *names):
    for name in names:
        if name in cols:
            return f'CAST("{name}" AS VARCHAR)'
    return "NULL"


def _double(cols, name):
    return f'COALESCE(TRY_CAST("{name}" AS DOUBLE), 0)' if name in cols else "0"


_DATE = 'CAST(TRY_CAST("date" AS DATE) AS VARCHAR)'


def _data_date(cur, ad_types):
    """The latest `date` across the advertised products tables, as YYYY-MM-DD, or None."""
    best = None
    for ad_type in ad_types:
        table = _ads_table(ad_type, "advertised_products")
        if "date" not in _columns(cur, table):
            continue
        row = cur.execute(f"SELECT MAX({_DATE}) FROM {table}").fetchone()
        if row and row[0] and (best is None or row[0] > best):
            best = str(row[0])
    return best


def _product_rows(cur, ad_type, start, end):
    """Advertised products rows dated start to end inclusive, as dicts."""
    table = _ads_table(ad_type, "advertised_products")
    cols = _columns(cur, table)
    if not {"date", "cost", "campaign_id"} <= cols:
        return []
    rows = cur.execute(
        f"SELECT {_DATE}, {_text(cols, 'campaign_id')}, {_text(cols, 'campaign_name', 'campaign')}, "
        f"{_text(cols, 'ad_group_id')}, {_text(cols, 'target_id')}, {_text(cols, 'ad_id')}, "
        f"{_text(cols, 'advertised_sku')}, {_text(cols, 'asin', 'advertised_asin')}, "
        f"{_double(cols, 'clicks')}, {_double(cols, 'cost')}, {_double(cols, 'sales')}, "
        f"{_double(cols, 'orders')} FROM {table} WHERE {_DATE} BETWEEN ? AND ?", [start, end]).fetchall()
    keys = ("date", "campaign_id", "campaign", "ad_group_id", "target_id", "ad_id", "sku", "asin",
            "clicks", "cost", "sales", "orders")
    out = []
    for row in rows:
        rec = dict(zip(keys, row))
        for k in ("campaign_id", "campaign", "ad_group_id", "target_id", "ad_id", "sku", "asin"):
            rec[k] = str(rec[k]).strip() if rec[k] is not None else ""
        rec["ad_type"] = ad_type
        out.append(rec)
    return out


def _search_rows(cur, ad_type, start, end):
    table = _ads_table(ad_type, "search_terms")
    cols = _columns(cur, table)
    term = _text(cols, "search_term", "query", "keyword")
    if not {"date", "campaign_id"} <= cols or term == "NULL":
        return []
    rows = cur.execute(
        f"SELECT {_text(cols, 'campaign_id')}, {_text(cols, 'campaign_name', 'campaign')}, "
        f"{_text(cols, 'ad_group_id')}, {term}, SUM({_double(cols, 'clicks')}), SUM({_double(cols, 'cost')}), "
        f"SUM({_double(cols, 'orders')}) FROM {table} WHERE {_DATE} BETWEEN ? AND ? GROUP BY ALL",
        [start, end]).fetchall()
    return [{"ad_type": ad_type, "campaign_id": str(c or "").strip(), "campaign": str(n or "").strip(),
             "ad_group_id": str(g or "").strip(), "term": " ".join(str(t or "").split()).lower(),
             "clicks": float(k or 0), "cost": float(s or 0), "orders": float(o or 0)}
            for c, n, g, t, k, s, o in rows if str(t or "").strip()]


def _cover(cur):
    """{sku: (days_of_supply, asin)} from each SKU's latest planning snapshot. The lowest row wins a tie."""
    cols = _columns(cur, PLANNING_TABLE) if cur is not None else set()
    if not {"sku", "days_of_supply"} <= cols:
        return {}
    snap = _text(cols, "_snapshot_date")
    rows = cur.execute(f'SELECT CAST("sku" AS VARCHAR), {_text(cols, "asin")}, {snap}, '
                       f'TRY_CAST("days_of_supply" AS DOUBLE) FROM {PLANNING_TABLE}').fetchall()
    latest = {}
    for sku, asin, when, days in rows:
        sku = str(sku or "").strip()
        if not sku:
            continue
        when = str(when or "")
        have = latest.get(sku)
        if have is None or when > have[0]:
            latest[sku] = [when, days, str(asin or "").strip()]
        elif when == have[0] and days is not None and (have[1] is None or days < have[1]):
            have[1] = days
    return {sku: (_num(days), asin) for sku, (_when, days, asin) in latest.items()}


def _profit(st):
    """{sku: {"linked", "cogs_per_unit", "net_profit", "asin"}} from the Amazon SKU profit table."""
    import core.user_tables as ut
    rows = (ut.get_one(PROFIT_TABLE, st) or {}).get("rows") or {}
    out = {}
    for row in rows.values():
        if not isinstance(row, dict):
            continue
        sku = str(row.get("sku") or "").strip()
        if not sku:
            continue
        cogs = _num(row.get("cogs_per_unit"))
        out[sku] = {"linked": cogs is not None, "cogs_per_unit": cogs,
                    "net_profit": _num(row.get("net_profit")) if cogs is not None else None,
                    "asin": str(row.get("asin") or "").strip()}
    return out


def _sku_for(rec, by_asin):
    return rec["sku"] or by_asin.get(rec["asin"], "")


# --------------------------------------------------------------------------- settings and owner

#: Accounts that sign in for a process, never a person who can own a proposal.
SERVICE_ACCOUNTS = ("admin", "automation", "scheduler", "qa-runner", "leadership")


def _is_service(name, rec):
    name = str(name or "").strip().lower()
    return (not name or name.startswith("qa") or name in SERVICE_ACCOUNTS
            or name.endswith("-admin") or bool(rec.get("platform_admin")))


def owner_account(st, tenant_key=None):
    """The tenant's earliest active person Administrator, else its `admin` account, else its first Administrator."""
    try:
        users = st.get("users")
    except Exception:                                                  # noqa: BLE001
        users = None
    want = str(tenant_key or "").strip().lower()
    admins = [(str(name), rec) for name, rec in (users or {}).items()
              if isinstance(rec, dict) and rec.get("active", True)
              and str(rec.get("role") or "").lower() == "admin"
              and (not want or str(rec.get("tenant") or "royal-imports").strip().lower() == want)]
    people = sorted(((n, r) for n, r in admins if not _is_service(n, r)),
                    key=lambda item: ("@" not in item[0], not item[1].get("password_changed_at"),
                                      str(item[1].get("password_changed_at") or ""), item[0]))
    if people:
        return str(people[0][1].get("name") or people[0][0])
    names = sorted(n for n, _r in admins)
    return "admin" if "admin" in names or not names else names[0]


def _clean(name, value):
    """One setting checked and typed, or ValueError with a plain message."""
    if isinstance(value, bool):
        raise ValueError("A threshold must be a number.")
    try:
        number = float(value)
    except (TypeError, ValueError):
        raise ValueError("A threshold must be a number.") from None
    if not math.isfinite(number):
        raise ValueError("A threshold must be a number.")
    if name in _INTS:
        if not number.is_integer():
            raise ValueError("Days and clicks must be whole numbers.")
        number = int(number)
        if number < (1 if name in ("lookback_days", "negative_min_clicks") else 0):
            raise ValueError("Days and clicks must be 0 or more, and the lookback at least 1 day.")
        return number
    if name in ("bid_step_pct", "budget_step_pct") and not 0 < number <= 100:
        raise ValueError("A step must be above 0 and at most 100 percent.")
    if name == "negative_min_cost" and number < 0:
        raise ValueError("The negative keyword spend must be 0 or more.")
    return number


def settings(tenant_key, *, st=None):
    """Thresholds and the default owner, with defaults filled in."""
    st = _rt(tenant_key, st)
    doc = _doc(st, KEY_SETTINGS)
    out = {}
    for name, default in DEFAULTS.items():
        try:
            out[name] = _clean(name, doc.get(name, default))
        except ValueError:
            out[name] = default
    out["defaults"] = dict(DEFAULTS)
    out["defaultOwnerSetting"] = doc.get("default_owner") or None
    out["defaultOwner"] = out["defaultOwnerSetting"] or owner_account(st, tenant_key)
    out["limit"] = LIMIT
    return out


def set_settings(tenant_key, *, st=None, default_owner=None, **changes):
    """Set any threshold in DEFAULTS, or the default owner ('' resets to the owner account)."""
    st = _rt(tenant_key, st)
    unknown = sorted(set(changes) - set(DEFAULTS))
    if unknown:
        raise ValueError("Unknown setting: " + ", ".join(unknown) + ".")
    clean = {k: _clean(k, v) for k, v in changes.items() if v is not None}
    current = settings(tenant_key, st=st)
    stop = clean.get("stop_cover_days", current["stop_cover_days"])
    raise_ = clean.get("raise_cover_days", current["raise_cover_days"])
    if raise_ <= stop:
        raise ValueError("The raise cover days must be above the stop cover days.")

    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        doc.update(clean)
        if default_owner is not None:
            doc["default_owner"] = str(default_owner).strip() or None
        return doc
    st.update(KEY_SETTINGS, _apply)
    return settings(tenant_key, st=st)


# --------------------------------------------------------------------------- the daily build

def _pid(day, kind, action, ad_type, campaign_id, ad_group_id, target_id, subject):
    """Stable id: a rebuild on the same day yields the same id, so it never duplicates."""
    raw = "|".join(str(p or "") for p in (day, kind, action, ad_type, campaign_id, ad_group_id,
                                          target_id, subject))
    return "p" + hashlib.sha1(raw.encode("utf-8")).hexdigest()[:16]


def _units(rows, by_asin, data_date):
    """Group rows by (ad type, campaign, ad group, SKU); rows with no SKU go to the held list."""
    units, held = {}, {}
    for rec in rows:
        sku = _sku_for(rec, by_asin)
        key = (rec["ad_type"], rec["campaign_id"], rec["ad_group_id"], sku)
        if not sku:
            held.setdefault(key, {"ad_type": rec["ad_type"], "campaign_id": rec["campaign_id"],
                                  "campaign": rec["campaign"] or rec["campaign_id"],
                                  "ad_group_id": rec["ad_group_id"], "sku": "", "asin": rec["asin"],
                                  "reason": NO_SKU})
            continue
        unit = units.setdefault(key, {"ad_type": rec["ad_type"], "campaign_id": rec["campaign_id"],
                                      "campaign": "", "ad_group_id": rec["ad_group_id"], "sku": sku,
                                      "asin": rec["asin"], "targets": set(), "ad_ids": set(),
                                      "clicks": 0.0, "cost": 0.0, "sales": 0.0, "orders": 0.0,
                                      "spend": 0.0})
        unit["campaign"] = unit["campaign"] or rec["campaign"]
        unit["asin"] = unit["asin"] or rec["asin"]
        if rec["target_id"]:
            unit["targets"].add(rec["target_id"])
        if rec["ad_id"]:
            unit["ad_ids"].add(rec["ad_id"])
        for k in ("clicks", "cost", "sales", "orders"):
            unit[k] += rec[k]
        if rec["date"] == data_date:
            unit["spend"] += rec["cost"]
    for unit in units.values():
        unit["campaign"] = unit["campaign"] or unit["campaign_id"]
    return units, list(held.values())


def _proposal(day, data_date, unit, kind, action, change, payload, reason, gate, owner, due, *,
              target_id="", subject=None, spend=None):
    pid = _pid(day, kind, action, unit["ad_type"], unit["campaign_id"], unit.get("ad_group_id", ""),
               target_id, subject if subject is not None else unit.get("sku", ""))
    return {"id": pid, "day": day, "data_date": data_date, "ad_type": unit["ad_type"],
            "campaign_id": unit["campaign_id"], "campaign": unit["campaign"],
            "ad_group_id": unit.get("ad_group_id", ""), "target_id": target_id,
            "sku": unit.get("sku", ""), "asin": unit.get("asin", ""), "kind": kind, "action": action,
            "change": change, "payload": payload, "reason": reason, "gate": gate,
            "spend": round(float(unit.get("spend", 0.0) if spend is None else spend), 2),
            "status": "proposed", "owner": owner, "due": due}


def _evaluate(day, data_date, conf, units, profit, cover, owner, due):
    """(proposals, held) for the grouped units. Pure: no store and no mirror."""
    stop_at, raise_at = conf["stop_cover_days"], conf["raise_cover_days"]
    pause_at, step = conf["pause_below_profit"], conf["bid_step_pct"]
    proposals, held, raised = [], [], {}
    for key in sorted(units):
        unit = units[key]
        sku = unit["sku"]
        days = (cover.get(sku) or (None, ""))[0]
        info = profit.get(sku) or {"linked": False, "net_profit": None}
        camp = (unit["ad_type"], unit["campaign_id"])
        raised.setdefault(camp, [])
        pause_payload = {"operation": "pause_ads", "ad_type": unit["ad_type"],
                         "campaign_id": unit["campaign_id"], "ad_group_id": unit["ad_group_id"],
                         "sku": sku, "asin": unit["asin"], "ad_ids": sorted(unit["ad_ids"]),
                         "state": "paused"}
        if days is not None and days < stop_at:
            proposals.append(_proposal(
                day, data_date, unit, "bid", "stop", f"Pause ads for {sku}", pause_payload,
                f"Stock covers {_days(days)} days. Stop ads so spend does not outrun stock.",
                f"Cover {_days(days)} days is under the {_days(stop_at)} day stop line.", owner, due))
            raised[camp].append(False)
            continue
        if not info["linked"]:
            held.append({**_held(unit), "reason": NO_COGS})
            raised[camp].append(False)
            continue
        net = info["net_profit"]
        if net is not None and net < pause_at:
            proposals.append(_proposal(
                day, data_date, unit, "bid", "pause", f"Pause ads for {sku}", pause_payload,
                f"This SKU {_earns(net)} after COGS over the profit period.",
                f"Profit after COGS {_money(net)} is under the {_money(pause_at)} pause line.", owner, due))
            raised[camp].append(False)
            continue
        if net is None:
            held.append({**_held(unit), "reason": NO_PROFIT})
            raised[camp].append(False)
            continue
        if days is None:
            held.append({**_held(unit), "reason": NO_COVER})
            raised[camp].append(False)
            continue
        if days > raise_at:
            if unit["clicks"] <= 0:
                held.append({**_held(unit), "reason": NO_CLICKS})
                raised[camp].append(False)
                continue
            bid = unit["cost"] / unit["clicks"]
            new = round(bid * (1 + step / 100.0), 2)
            target = sorted(unit["targets"])[0] if len(unit["targets"]) == 1 else ""
            proposals.append(_proposal(
                day, data_date, unit, "bid", "raise", f"Bid {_money(bid)} to {_money(new)}",
                {"operation": "set_bid", "ad_type": unit["ad_type"], "campaign_id": unit["campaign_id"],
                 "ad_group_id": unit["ad_group_id"], "target_id": target, "sku": sku,
                 "asin": unit["asin"], "previous_bid": round(bid, 2), "bid": new},
                f"Stock covers {_days(days)} days and the SKU {_earns(net)} after COGS. "
                f"Raise the bid to sell through.",
                f"Cover {_days(days)} days is over the {_days(raise_at)} day raise line. Profit after COGS "
                f"{_money(net)} is at or above {_money(pause_at)}.", owner, due, target_id=target))
            raised[camp].append(True)
            continue
        raised[camp].append(False)
    return proposals, held, raised


def _held(unit):
    return {"ad_type": unit["ad_type"], "campaign_id": unit["campaign_id"], "campaign": unit["campaign"],
            "ad_group_id": unit["ad_group_id"], "sku": unit["sku"], "asin": unit["asin"]}


def _raise_gate_copy(count):
    """The budget gate line, with the count and the noun in agreement."""
    return "The 1 SKU passed the raise gate." if count == 1 else f"All {count} SKUs passed the raise gate."


def _budgets(day, data_date, conf, units, raised, owner, due):
    step, lookback = conf["budget_step_pct"], conf["lookback_days"]
    out = []
    for (ad_type, campaign_id), flags in sorted(raised.items()):
        if not flags or not all(flags):
            continue
        members = [u for u in units.values() if (u["ad_type"], u["campaign_id"]) == (ad_type, campaign_id)]
        cost = sum(u["cost"] for u in members)
        if cost <= 0:
            continue
        daily = cost / lookback
        new = round(daily * (1 + step / 100.0), 2)
        camp = {"ad_type": ad_type, "campaign_id": campaign_id,
                "campaign": members[0]["campaign"], "ad_group_id": "", "sku": "", "asin": ""}
        out.append(_proposal(
            day, data_date, camp, "budget", "raise_budget", f"Daily budget to {_money(new)}",
            {"operation": "set_daily_budget", "ad_type": ad_type, "campaign_id": campaign_id,
             "average_daily_cost": round(daily, 2), "daily_budget": new},
            f"Every SKU in this campaign got a bid raise. Average daily spend is {_money(daily)} "
            f"over {lookback} days.",
            _raise_gate_copy(len(flags)), owner, due,
            subject=campaign_id, spend=sum(u["spend"] for u in members)))
    return out


def _negatives(day, data_date, conf, terms, owner, due):
    min_clicks, min_cost, lookback = conf["negative_min_clicks"], conf["negative_min_cost"], conf["lookback_days"]
    out = []
    for row in sorted(terms, key=lambda r: (r["ad_type"], r["campaign_id"], r["ad_group_id"], r["term"])):
        if row["clicks"] < min_clicks or row["orders"] > 0 or row["cost"] < min_cost:
            continue
        unit = {"ad_type": row["ad_type"], "campaign_id": row["campaign_id"],
                "campaign": row["campaign"] or row["campaign_id"], "ad_group_id": row["ad_group_id"],
                "sku": "", "asin": ""}
        out.append(_proposal(
            day, data_date, unit, "negative_keyword", "add_negative",
            f'Add "{row["term"]}" as a negative exact keyword',
            {"operation": "add_negative_keyword", "ad_type": row["ad_type"], "campaign_id": row["campaign_id"],
             "ad_group_id": row["ad_group_id"], "keyword_text": row["term"], "match_type": "negativeExact"},
            f'"{row["term"]}" took {_days(row["clicks"])} clicks and {_money(row["cost"])} spend in '
            f"{lookback} days with no orders.",
            f"Clicks {_days(row['clicks'])} at or above {min_clicks}, spend {_money(row['cost'])} at or "
            f"above {_money(min_cost)}, orders 0.", owner, due, subject=row["term"], spend=0.0))
    return out


def build(tenant_key, *, st=None, now=None):
    """Build today's proposals from the Ads tables, cover and COGS, and store them. Returns a summary."""
    st = _rt(tenant_key, st)
    now = now or _now()
    day = now.date().isoformat()
    conf = settings(tenant_key, st=st)
    owner = conf["defaultOwner"]
    due = (now.date() + dt.timedelta(days=DUE_DAYS)).isoformat()
    profit = _profit(st)
    with _reader(tenant_key, st) as cur:
        if cur is None:
            return {"state": "no_mirror", "day": day}
        data_date = _data_date(cur, AD_TYPES)
        if data_date is None:
            return {"state": "no_ads_data", "day": day}
        end = dt.date.fromisoformat(data_date)
        start = (end - dt.timedelta(days=conf["lookback_days"] - 1)).isoformat()
        cover = _cover(cur)
        rows, terms = [], []
        for ad_type in AD_TYPES:
            rows += _product_rows(cur, ad_type, start, data_date)
            terms += _search_rows(cur, ad_type, start, data_date)
        baseline = _doc(st, KEY_BASELINE)
        base_rows = None
        if baseline.get("state") != "computed":
            first = baseline.get("first_data_date") or data_date
            b_end = dt.date.fromisoformat(first) - dt.timedelta(days=1)
            b_start = b_end - dt.timedelta(days=BASELINE_DAYS - 1)
            base_rows = (first, b_start.isoformat(), b_end.isoformat(),
                         [r for t in AD_TYPES for r in _product_rows(cur, t, b_start.isoformat(),
                                                                     b_end.isoformat())])
    by_asin = {}
    for sku, (_days_, asin) in cover.items():
        if asin:
            by_asin.setdefault(asin, sku)
    for sku, info in profit.items():
        if info["asin"]:
            by_asin[info["asin"]] = sku
    units, held = _units(rows, by_asin, data_date)
    proposals, more_held, raised = _evaluate(day, data_date, conf, units, profit, cover, owner, due)
    held += more_held
    proposals += _budgets(day, data_date, conf, units, raised, owner, due)
    proposals += _negatives(day, data_date, conf, terms, owner, due)
    spend = {t: 0.0 for t in AD_TYPES}
    for rec in rows:
        if rec["date"] == data_date:
            spend[rec["ad_type"]] += rec["cost"]
    spend = {t: round(v, 2) for t, v in spend.items()}

    def _days_doc(doc):
        doc = doc if isinstance(doc, dict) else {}
        days = doc.setdefault("days", {})
        before = (days.get(day) or {}).get("items") or {}
        items = {}
        for prop in proposals:
            old = before.get(prop["id"])
            if old:
                prop = {**prop, **{k: old[k] for k in DECIDED_FIELDS if k in old}}
            items[prop["id"]] = prop
        # A decided proposal whose rule no longer fires stays whole: its decision and outcome are history.
        for pid, old in before.items():
            if pid not in items and isinstance(old, dict) and old.get("status") not in OPEN:
                items[pid] = old
        days[day] = {"built_at": _stamp(now), "data_date": data_date, "lookback_start": start,
                     "items": items, "held": held, "spend": spend,
                     "evaluated_rows": len(rows), "ad_types": list(AD_TYPES)}
        doc["latest"] = max(days)
        doc.pop("last_error", None)
        return doc
    st.update(KEY_DAYS, _days_doc)
    if base_rows is not None:
        _store_baseline(st, profit, by_asin, *base_rows, now=now)
    return {"state": "built", "day": day, "data_date": data_date, "proposals": len(proposals),
            "held": len(held), "spend": spend}


def compute_baseline(rows, profit, by_asin):
    """Ad profit after COGS over rows for linked SKUs; unlinked SKUs are left out and counted."""
    linked, unlinked, unresolved = set(), set(), 0
    sales = cost = cogs = 0.0
    for rec in rows:
        sku = _sku_for(rec, by_asin)
        info = profit.get(sku) if sku else None
        if not sku:
            unresolved += 1
            continue
        if not info or not info["linked"]:
            unlinked.add(sku)
            continue
        linked.add(sku)
        sales += rec["sales"]
        cost += rec["cost"]
        cogs += rec["orders"] * info["cogs_per_unit"]
    return {"ad_profit_after_cogs": round(sales - cost - cogs, 2), "ad_sales": round(sales, 2),
            "ad_cost": round(cost, 2), "cogs": round(cogs, 2), "linked_skus": len(linked),
            "unlinked_skus": len(unlinked), "unlinked": sorted(unlinked), "rows_without_sku": unresolved,
            "days_with_data": len({r["date"] for r in rows})}


def _store_baseline(st, profit, by_asin, first, start, end, rows, *, now):
    figures = compute_baseline(rows, profit, by_asin)
    ready = figures["days_with_data"] > 0

    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        if doc.get("state") == "computed":
            return doc
        doc.update(figures if ready else {})
        doc.update({"state": "computed" if ready else "waiting", "first_data_date": first,
                    "window_start": start, "window_end": end, "days": BASELINE_DAYS,
                    "basis": BASELINE_BASIS, "time_baseline_hours_per_week": dict(TIME_BASELINE),
                    "bar": dict(BAR)})
        if ready:
            doc["computed_at"] = _stamp(now)
        return doc
    st.update(KEY_BASELINE, _apply)


def baseline(tenant_key, *, st=None):
    """The stored 60 day baseline, or a waiting record before the first build."""
    doc = _doc(_rt(tenant_key, st), KEY_BASELINE)
    return doc or {"state": "waiting", "time_baseline_hours_per_week": dict(TIME_BASELINE), "bar": dict(BAR)}


def on_ads_sync(tenant_key, synced_tables):
    """Contract C6 callback: build today's proposals, then pull the App inbox. Logs one line on failure and never raises."""
    try:
        out = build(tenant_key)
    except Exception as exc:                                           # noqa: BLE001
        _log.warning("amazon_operator: the proposal build for %s failed (%s): %s",
                     tenant_key, type(exc).__name__, exc)
        return None
    _safe_pull(tenant_key)
    return out


# --------------------------------------------------------------------------- the C4 item protocol

def _all_proposals(st):
    days = _doc(st, KEY_DAYS).get("days") or {}
    out = []
    for day in days.values():
        out += list(((day or {}).get("items") or {}).values())
    return out


def day_record(tenant_key, day=None, *, st=None):
    """One built day (the latest when day is None), or None."""
    doc = _doc(_rt(tenant_key, st), KEY_DAYS)
    day = day or doc.get("latest")
    return ((doc.get("days") or {}).get(day) or None) if day else None


def _item(prop):
    label = AD_LABELS.get(prop.get("ad_type"), str(prop.get("ad_type") or "").upper())
    return {"id": prop["id"], "title": f"{label} {prop.get('campaign') or prop.get('campaign_id')}: "
                                       f"{prop.get('change')}",
            "status": prop.get("status"), "owner": prop.get("owner"), "due": prop.get("due"),
            "reason": prop.get("reason"), "sku": prop.get("sku") or None, "asin": prop.get("asin") or None,
            "kind": prop.get("kind"), "action": prop.get("action"), "change": prop.get("change"),
            "gate": prop.get("gate"), "ad_type": prop.get("ad_type"), "campaign": prop.get("campaign"),
            "campaign_id": prop.get("campaign_id"), "day": prop.get("day"),
            "data_date": prop.get("data_date"), "spend": prop.get("spend"),
            "decision_id": prop.get("decision_id"), "decided_by": prop.get("decided_by"),
            "decided_at": prop.get("decided_at"), "note": prop.get("note"), "cause": prop.get("cause"),
            "outcome_at": prop.get("outcome_at")}


def _encode(key):
    return base64.urlsafe_b64encode(json.dumps(list(key)).encode("utf-8")).decode("ascii")


def _decode(cursor):
    try:
        day, pid = json.loads(base64.urlsafe_b64decode(str(cursor).encode("ascii")).decode("utf-8"))
        return str(day), str(pid)
    except Exception:                                                  # noqa: BLE001
        raise ValueError("The cursor could not be read.") from None


def items(tenant_key, user=None, *, status=None, cursor=None, limit=200, st=None):
    """C4: every proposal and decided App item, newest day first, paged by an opaque cursor. limit=None returns every row."""
    st = _rt(tenant_key, st)
    rows = [p for p in _all_proposals(st) + _decided_app_rows(st) if status is None or p.get("status") == status]
    # Newest day first, then id ascending: the sort key is (inverted day, id).
    rows.sort(key=lambda p: (_inv(p.get("day") or ""), p["id"]))
    if cursor:
        day, pid = _decode(cursor)
        after = (_inv(day), pid)
        rows = [p for p in rows if (_inv(p.get("day") or ""), p["id"]) > after]
    if limit is not None:
        limit = int(limit)
        if limit < 1:
            raise ValueError("The page size must be at least 1.")
    page = rows if limit is None else rows[:limit]
    more = limit is not None and len(rows) > limit
    return {"items": [_app_item(p) if p.get("kind") == APP_KIND else _item(p) for p in page],
            "cursor": _encode((page[-1].get("day") or "", page[-1]["id"])) if more else None}


def _inv(day):
    """A string key that sorts days newest first."""
    return "".join(chr(0x10FFFF - ord(c)) for c in day)


def proposals(tenant_key, *, st=None):
    """C4: open proposals for the governed inbox."""
    st = _rt(tenant_key, st)
    rows = [p for p in _all_proposals(st) if p.get("status") in OPEN]
    rows.sort(key=lambda p: (_inv(p.get("day") or ""), p["id"]))
    return [{"source_kind": SOURCE_KIND, "item_id": p["id"], "sku": p.get("sku") or None,
             "action": p.get("action"), "reason": p.get("reason")} for p in rows]


def today(tenant_key, *, st=None, now=None, cursor=None, app_cursor=None, held_cursor=None, limit=50, q="", refresh=True):
    """The latest built day as the App shows it: every proposal, held notes, settings and the App inbox."""
    st = _rt(tenant_key, st)
    if refresh:
        _safe_pull(tenant_key, st=st, now=now)
    return screen_today(tenant_key, st=st, now=now, cursor=cursor, app_cursor=app_cursor,
                        held_cursor=held_cursor, limit=limit, q=q)


def _screen_backend(st, tenant_key):
    from core import store, store_pg
    resolve = getattr(st, "_document_store", None)
    backend = resolve() if callable(resolve) else st
    if backend is store and store.backend() == "pg":
        backend = store._d()
    if not isinstance(backend, store_pg.PgStore):
        return None
    if backend.tenant_slug != str(tenant_key).strip().lower():
        raise PermissionError("The Amazon operator store belongs to another tenant.")
    return backend


@contextlib.contextmanager
def _screen_store(tenant_key, st):
    """Expose authored JSON to SQL without reading complete production documents into Python."""
    backend = _screen_backend(st, tenant_key)
    key = getattr(st, "store_key", lambda name: name)
    names = [key(KEY_DAYS), key(KEY_INBOX)]
    if backend is not None:
        from core import store_pg
        with store_pg._pool().connection() as con:
            def execute(sql, args=()):
                return con.execute(store_pg._q(sql.replace("'{}'", "'{{}}'"), "store_kv", backend.tenant_slug), [*names, *args])
            yield execute, True, names
    else:
        import duckdb
        con = duckdb.connect()
        try:
            con.execute("CREATE TABLE docs (name VARCHAR, value JSON)")
            for name, document in zip(names, (KEY_DAYS, KEY_INBOX)):
                con.execute("INSERT INTO docs VALUES (?, ?)", [name, json.dumps(_doc(st, document))])
            yield lambda sql, args=(): con.execute(sql, [*names, *args]), False, names
        finally:
            con.close()


def _stored_sql(pg):
    each = "jsonb_each" if pg else "json_each"
    array = "jsonb_array_elements" if pg else "json_each"
    placeholder = "%s" if pg else "?"
    docs = f"SELECT key AS name, value FROM {{tbl}} WHERE key IN ({placeholder}, {placeholder})" if pg else (
        f"SELECT * FROM docs WHERE name IN ({placeholder}, {placeholder})")
    return f"""WITH documents AS ({docs}),
      day_doc AS (SELECT value FROM documents ORDER BY (value ->> 'latest') IS NULL LIMIT 1),
      ad AS (SELECT p.value AS r, d.key AS day FROM day_doc,
        LATERAL {each}(COALESCE(value -> 'days', '{{}}')) d,
        LATERAL {each}(COALESCE(d.value -> 'items', '{{}}')) p),
      apps AS (SELECT p.value AS r, left(COALESCE(p.value ->> 'decided_at', ''), 10) AS day FROM documents,
        LATERAL {each}(COALESCE(value -> 'items', '{{}}')) p),
      held AS (SELECT h.value AS r, d.key AS day FROM day_doc,
        LATERAL {each}(COALESCE(value -> 'days', '{{}}')) d,
        LATERAL {array}(COALESCE(d.value -> 'held', '[]')) h)
      """


_SCREEN_FIELDS = ("id", "status", "owner", "due", "reason", "sku", "asin", "kind", "action", "change", "gate",
                  "ad_type", "campaign", "campaign_id", "day", "data_date", "spend", "decision_id", "decided_by",
                  "decided_at", "note", "cause", "outcome_at", "app", "source_kind", "source_module", "item_id",
                  "first_seen", "last_seen")


def _stored_page(execute, pg, sql, section, *, q="", cursor=None, limit=50, status=None, now=None):
    try:
        start, size = int(cursor or 0), int(limit)
    except (TypeError, ValueError):
        raise ValueError("The page cursor and size must be whole numbers.") from None
    if start < 0 or size < 1:
        raise ValueError("The page cursor must be nonnegative and the size at least 1.")
    p = "%s" if pg else "?"
    today_day = (now or _now()).date().isoformat()
    args = []
    if section == "history":
        selected = "SELECT * FROM ad UNION ALL SELECT * FROM apps WHERE (r ->> 'status') IN ('approved', 'dismissed')"
        order = "day DESC, (r ->> 'id')"
    elif section == "apps":
        selected = f"SELECT * FROM apps WHERE (r ->> 'status') IN ('proposed', 'stale') OR day = {p}"
        args.append(today_day)
        order = ("CASE (r ->> 'status') WHEN 'proposed' THEN 0 WHEN 'stale' THEN 1 ELSE 2 END, "
                 "(r ->> 'app'), (r ->> 'sku'), (r ->> 'id')")
    else:
        selected = f"SELECT * FROM {section} WHERE day = (SELECT value ->> 'latest' FROM day_doc)"
        order = ("CASE WHEN (r ->> 'status') = 'proposed' THEN 0 ELSE 1 END, "
                 "(r ->> 'ad_type'), (r ->> 'campaign'), (r ->> 'id')") if section == "ad" else "CAST(r AS TEXT)"
    search_fields = ("id", "campaign", "campaign_id", "sku", "asin", "reason", "change", "gate", "app", "action", "status")
    text = "concat_ws(' ', " + ", ".join(f"(r ->> '{f}')" for f in search_fields) + ")"
    where = f"strpos(lower({text}), {p}) > 0"
    args.append(str(q or "").strip().lower())
    if status:
        where += f" AND (r ->> 'status') = {p}"
        args.append(status)
    sql += f", selected AS ({selected}), matched AS (SELECT * FROM selected WHERE {where}) "
    total, opened = execute(sql + "SELECT count(*), count(*) FILTER (WHERE (r ->> 'status') = 'proposed') FROM matched", args).fetchone()
    if start >= total:
        start = max(0, (total - 1) // size * size)
    builder = "jsonb_build_object" if pg else "json_object"
    fields = _SCREEN_FIELDS if section != "held" else ("ad_type", "campaign", "campaign_id", "sku", "asin", "reason")
    projection = builder + "(" + ", ".join(f"'{f}', r -> '{f}'" for f in fields) + ")"
    rows = execute(sql + f"SELECT {projection} FROM matched ORDER BY {order} LIMIT {p} OFFSET {p}", [*args, size, start]).fetchall()
    values = [r[0] if isinstance(r[0], dict) else json.loads(r[0]) for r in rows]
    return values, {"total": total, "open": opened, "offset": start, "limit": size,
                    "cursor": str(start + size) if start + size < total else None}


def screen_today(tenant_key, *, st=None, now=None, cursor=None, app_cursor=None, held_cursor=None, limit=50, q=""):
    """Read bounded Ads, source App and held pages without generating proposals or writing documents."""
    st = _rt(tenant_key, st)
    conf = settings(tenant_key, st=st)
    with _screen_store(tenant_key, st) as (execute, pg, _names):
        sql = _stored_sql(pg)
        latest = "(SELECT value ->> 'latest' FROM day_doc)"
        meta = execute(sql + f"SELECT day, r ->> 'data_date', r ->> 'built_at' FROM "
                       f"(SELECT d.key AS day, d.value AS r FROM day_doc, LATERAL "
                       f"{'jsonb_each' if pg else 'json_each'}(COALESCE(value -> 'days', '{{}}')) d) t "
                       f"WHERE day = {latest} LIMIT 1").fetchone()
        ads, ad_page = _stored_page(execute, pg, sql, "ad", q=q, cursor=cursor, limit=limit, now=now)
        apps, app_page = _stored_page(execute, pg, sql, "apps", q=q, cursor=app_cursor, limit=limit, now=now)
        held, held_page = _stored_page(execute, pg, sql, "held", q=q, cursor=held_cursor, limit=limit, now=now)
    return {"day": meta[0] if meta else None, "dataDate": meta[1] if meta else None,
            "builtAt": meta[2] if meta else None, "items": [_item(p) for p in ads], "held": held,
            "appItems": [_app_item(p) for p in apps], "pages": {"items": ad_page, "apps": app_page, "held": held_page},
            "settings": {k: conf[k] for k in DEFAULTS} | {"defaultOwner": conf["defaultOwner"]}}


def screen_history(tenant_key, *, st=None, status=None, cursor=None, limit=50, q=""):
    """Read and count one history page in the tenant store."""
    st = _rt(tenant_key, st)
    with _screen_store(tenant_key, st) as (execute, pg, _names):
        rows, page = _stored_page(execute, pg, _stored_sql(pg), "history", q=q, cursor=cursor, limit=limit, status=status)
    return {**page, "items": [_app_item(p) if p.get("kind") == APP_KIND else _item(p) for p in rows]}


# --------------------------------------------------------------------------- decisions and named writes

def _ads_client():
    """The one seam to the Ads client that sends the three named writes, or None when it cannot import."""
    import importlib
    try:
        client = importlib.import_module("harness.amazon_ads_client")
    except Exception:                                                  # noqa: BLE001
        return None
    return client if callable(getattr(client, "send_named_write", None)) else None


def _plain(text):
    """One line of plain text with every em and en dash rewritten as a comma."""
    out = " ".join(str(text or "").split())
    for dash in (chr(0x2014), chr(0x2013)):
        out = out.replace(f" {dash} ", ", ").replace(dash, ", ")
    return out


def _cause(exc):
    detail = _plain(exc).rstrip(".")
    if type(exc).__name__ == "AdsWriteRefused":
        return f"Amazon Ads refused this change: {detail}." if detail else "Amazon Ads refused this change."
    return f"The change could not be sent: {detail}." if detail else "The change could not be sent."


def _json_safe(value):
    try:
        return json.loads(json.dumps(value, default=str))
    except (TypeError, ValueError):
        return str(value)


def _editor(st, user):
    """The deciding account's name. PermissionError for a viewer, an inactive or an unknown account."""
    name, rec = None, user
    if isinstance(user, str):
        name = user.strip()
        try:
            rec = (st.get("users") or {}).get(name)
        except Exception:                                              # noqa: BLE001
            rec = None
    if not isinstance(rec, dict) or rec.get("active") is False:
        raise PermissionError(READ_ONLY)
    role = str(rec.get("role") or "user").strip().lower()
    if role == "viewer" or rec.get("can_edit") is False or rec.get("canEdit") is False:
        raise PermissionError(READ_ONLY)
    return str(rec.get("username") or name or rec.get("name") or "unknown")


def _ids(item_id):
    raw = [item_id] if isinstance(item_id, str) else list(item_id or ())
    out = []
    for pid in raw:
        pid = str(pid or "").strip()
        if pid and pid not in out:
            out.append(pid)
    if not out:
        raise ValueError("Pick at least one proposal.")
    return out


def _skip_cause(status, decision):
    verb = "sent" if decision == "approved" else "dismissed"
    return f"This proposal is already {status}. Nothing was {verb}."


def _put_decision(st, record):
    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        doc.setdefault("decisions", {})[record["id"]] = record
        return doc
    st.update(KEY_DECISIONS, _apply)


def _claim(st, ids, status, decision_id, who, at, note):
    """Move each open proposal in ids to status in one store update. Returns the ids it moved."""
    want, moved = set(ids), []

    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        moved.clear()
        for day in (doc.get("days") or {}).values():
            for pid, prop in ((day or {}).get("items") or {}).items():
                if pid in want and isinstance(prop, dict) and prop.get("status") in OPEN:
                    prop.update(status=status, decision_id=decision_id, decided_by=who, decided_at=at, note=note)
                    moved.append(pid)
        return doc
    st.update(KEY_DAYS, _apply)
    return [pid for pid in ids if pid in set(moved)]


def _record_outcome(st, pid, decision_id, kind, status, cause, result, payload, at):
    def _row(doc):
        doc = doc if isinstance(doc, dict) else {}
        for day in (doc.get("days") or {}).values():
            prop = ((day or {}).get("items") or {}).get(pid)
            if isinstance(prop, dict):
                prop.update(status=status, cause=cause, outcome_at=at, result=result, sent_payload=payload)
        return doc

    def _log(doc):
        doc = doc if isinstance(doc, dict) else {}
        doc.setdefault("items", {})[pid] = {"status": status, "cause": cause, "decision_id": decision_id,
                                            "kind": kind, "at": at}
        return doc
    st.update(KEY_DAYS, _row)
    st.update(KEY_OUTCOMES, _log)


def set_status(tenant_key, user, item_id, status, *, note=None, st=None, now=None):
    """C4: decide one proposal or a list. `approved` is one batch: an approval record, then one named write each.

    PermissionError for a viewer, before any store change. ValueError on an unknown status. Only a
    `proposed` row moves. A refused write records its cause on its row and the rest of the batch goes on.
    Ads proposal ids and App inbox ids may share one call. An inbox id goes back to its App's on_decision.
    """
    st = _rt(tenant_key, st)
    who = _editor(st, user)
    status = str(status or "").strip().lower()
    if status not in STATUSES:
        raise ValueError(f"Unknown status: {status or 'blank'}. Use approved or dismissed.")
    if status not in DECISIONS:
        raise ValueError("Only approved or dismissed can be set. Sent and refused come from the Ads write.")
    ids = _ids(item_id)
    note = (_plain(note) or None) if note is not None else None
    if status == "dismissed" and not note:
        raise ValueError("Give a reason to dismiss.")
    at = _stamp(now or _now())
    _safe_pull(tenant_key, st=st, now=now)
    inbox = _inbox(st)
    app_ids = [pid for pid in ids if pid in inbox]
    app_rows, app_decision = (_decide_apps(st, tenant_key, app_ids, inbox, status, note, who, at)
                              if app_ids else ({}, None))
    ad_ids = [pid for pid in ids if pid not in inbox]
    found = {p["id"]: p for p in _all_proposals(st)}
    rows = dict(app_rows)
    for pid in ad_ids:
        prop = found.get(pid)
        if prop is None:
            rows[pid] = {"id": pid, "status": "not_found", "cause": NOT_FOUND}
        elif prop.get("status") not in OPEN:
            rows[pid] = {"id": pid, "status": "skipped", "current": prop.get("status"),
                         "cause": _skip_cause(prop.get("status"), status)}
    eligible = [pid for pid in ad_ids if pid not in rows]
    decision_id = None
    if eligible:
        decision_id = ("apv_" if status == "approved" else "dsm_") + uuid.uuid4().hex[:16]
        record = {"id": decision_id, "decision": status, "by": who, "at": at, "item_ids": eligible, "note": note}
        if status == "approved":
            record["writes"] = [{"item_id": pid, "kind": found[pid]["kind"], "payload": _write_payload(found[pid])}
                                for pid in eligible]
        # The record is stored before any row moves, so a write never names an approval that is not there.
        _put_decision(st, record)
        claimed = _claim(st, eligible, status, decision_id, who, at, note)
        if claimed != eligible:
            for pid in eligible:
                if pid not in claimed:
                    rows[pid] = {"id": pid, "status": "skipped", "current": "decided",
                                 "cause": _skip_cause("decided", status)}
            record["item_ids"] = claimed
            if "writes" in record:
                record["writes"] = [w for w in record["writes"] if w["item_id"] in claimed]
            _put_decision(st, record)
        if status == "dismissed":
            for pid in claimed:
                rows[pid] = {"id": pid, "status": "dismissed"}
        else:
            client = _ads_client()
            for pid in claimed:
                rows[pid] = _send(st, tenant_key, client, found[pid], decision_id)
    out = [rows[pid] for pid in ids]
    count = {s: sum(1 for r in out if r["status"] == s)
             for s in ("sent", "refused", "dismissed", "skipped", "approved")}
    return {"decision": status, "decision_id": decision_id or app_decision,
            "approval_id": decision_id if status == "approved" else None, "rows": out,
            **count, "not_found": sum(1 for r in out if r["status"] == "not_found")}


def _write_payload(prop):
    """What send_named_write gets: the proposal's payload plus its item id, so the client can match the approval."""
    return {**(prop.get("payload") or {}), "item_id": prop["id"]}


def _send(st, tenant_key, client, prop, approval_id):
    """One named write for one approved proposal, its outcome stored on its row. Never raises."""
    payload = _write_payload(prop)
    result = None
    if client is None:
        status, cause = "refused", NOT_INSTALLED
    else:
        try:
            result = _json_safe(client.send_named_write(tenant_key, prop["kind"], payload,
                                                        approval_id=approval_id))
        except Exception as exc:                                       # noqa: BLE001
            status, cause = "refused", _cause(exc)
        else:
            status, cause = "sent", None
    at = _stamp(_now())
    try:
        _record_outcome(st, prop["id"], approval_id, prop["kind"], status, cause, result,
                        payload if status == "sent" else None, at)
    except Exception as exc:                                           # noqa: BLE001
        _log.warning("amazon_operator: the outcome of %s could not be stored (%s): %s",
                     prop["id"], type(exc).__name__, exc)
    row = {"id": prop["id"], "status": status, "kind": prop["kind"]}
    if cause:
        row["cause"] = cause
    return row


def approval(tenant_key, approval_id, *, st=None):
    """The stored approval record for approval_id, or None. The Ads client checks an id here before a write."""
    rec = (_doc(_rt(tenant_key, st), KEY_DECISIONS).get("decisions") or {}).get(str(approval_id or ""))
    # An App inbox decision is never an Ads approval.
    ok = isinstance(rec, dict) and rec.get("decision") == "approved" and rec.get("source") != APP_KIND
    return rec if ok else None


def on_decision(tenant_key, item_id, decision, reason, *, user=None, st=None):
    """C4 inbox callback. It runs set_status, so it needs the deciding user and refuses without one."""
    return set_status(tenant_key, user, item_id, decision, note=reason, st=st)


# --------------------------------------------------------------------------- C7 App inbox

def _short(name):
    return str(name).rsplit(".", 1)[-1]


def _inbox_id(source_kind, item_id):
    """Stable inbox id: a second pull of the same App item yields the same id, so it never duplicates."""
    return "a" + hashlib.sha1(f"{source_kind}|{item_id}".encode("utf-8")).hexdigest()[:16]


def _inbox(st):
    items = _doc(st, KEY_INBOX).get("items")
    return {k: v for k, v in items.items() if isinstance(v, dict)} if isinstance(items, dict) else {}


def _load_source(name):
    """(module, False), or (None, True) for a module that is not installed, or (None, False) for a failed import.

    Each failure logs one line. Sources are imported here only, by name, so deleting an App leaves this module whole.
    """
    import importlib
    try:
        return importlib.import_module(name), False
    except ModuleNotFoundError as exc:
        if exc.name == name:
            _log.info("amazon_operator: %s is not installed; its proposals are skipped", name)
            return None, True
        _log.warning("amazon_operator: %s could not be imported (%s); its proposals are skipped", name, exc)
    except Exception as exc:                                           # noqa: BLE001
        _log.warning("amazon_operator: %s could not be imported (%s: %s); its proposals are skipped",
                     name, type(exc).__name__, exc)
    return None, False


def _label(mod, name):
    label = getattr(mod, "APP_LABEL", None)
    if isinstance(label, str) and label.strip():
        return _plain(label)
    short = _short(name)
    return APP_LABELS.get(short) or short.replace("_", " ").capitalize()


def _read_sources(tenant_key):
    """{module name: (label, proposals) or None}. None marks a missing module. A failed read is left out."""
    out = {}
    for name in PROPOSAL_SOURCES:
        mod, missing = _load_source(name)
        if mod is None:
            if missing:
                out[name] = None
            continue
        reader = getattr(mod, "proposals", None)
        if not callable(reader):
            _log.warning("amazon_operator: %s has no proposals(); it is skipped", name)
            continue
        try:
            got = list(reader(tenant_key) or ())
        except Exception as exc:                                       # noqa: BLE001
            _log.warning("amazon_operator: %s proposals() failed for %s (%s: %s); it is skipped",
                         name, tenant_key, type(exc).__name__, exc)
            continue
        out[name] = (_label(mod, name), got)
    return out


def _merge_inbox(doc, read, at):
    """The inbox after one pull. Pure. Decided items never change; an unlisted open item becomes stale."""
    doc = doc if isinstance(doc, dict) else {}
    items = doc.get("items") if isinstance(doc.get("items"), dict) else {}
    seen = set()
    for name, got in read.items():
        if got is None:
            continue
        label, rows = got
        for raw in rows:
            if not isinstance(raw, dict) or not str(raw.get("item_id") or "").strip():
                continue
            item_id = str(raw["item_id"]).strip()
            kind = str(raw.get("source_kind") or _short(name)).strip()
            iid = _inbox_id(kind, item_id)
            seen.add(iid)
            fields = {"source_kind": kind, "source_module": name, "item_id": item_id,
                      "sku": _plain(raw.get("sku")) or None, "action": _plain(raw.get("action")),
                      "reason": _plain(raw.get("reason")), "app": label}
            old = items.get(iid)
            if not isinstance(old, dict):
                items[iid] = {"id": iid, "kind": APP_KIND, **fields, "status": "proposed", "cause": None,
                              "first_seen": at, "last_seen": at}
                continue
            if old.get("status") not in INBOX_OPEN + ("stale",):
                continue
            new = {**old, **fields, "status": "proposed",
                   "cause": old.get("cause") if old.get("status") in INBOX_OPEN else None}
            if new != old:
                items[iid] = {**new, "last_seen": at}
    for iid, rec in list(items.items()):
        name = rec.get("source_module") if isinstance(rec, dict) else None
        # A missing module (None) or a read that no longer lists the item. A failed read is not in `read`.
        if iid in seen or name not in read or rec.get("status") not in INBOX_OPEN:
            continue
        items[iid] = {**rec, "status": "stale", "cause": STALE, "last_seen": at}
    doc["items"] = items
    return doc


def pull_app_proposals(tenant_key, *, st=None, now=None):
    """C7: read every source App's open proposals into the inbox. Idempotent, and it writes only on a change."""
    st = _rt(tenant_key, st)
    read = _read_sources(tenant_key)
    at = _stamp(now or _now())
    current = st.get(KEY_INBOX)
    current = current if isinstance(current, dict) else {}
    merged = _merge_inbox(copy.deepcopy(current), read, at)
    changed = merged != current and bool(current or merged.get("items"))
    if changed:
        st.update(KEY_INBOX, lambda doc: _merge_inbox(doc, read, at))
    inbox = _inbox(st)
    return {"changed": changed, "read": sorted(n for n, g in read.items() if g is not None),
            "missing": sorted(n for n, g in read.items() if g is None),
            "open": sum(1 for r in inbox.values() if r.get("status") in INBOX_OPEN),
            "stale": sum(1 for r in inbox.values() if r.get("status") == "stale")}


def _safe_pull(tenant_key, *, st=None, now=None):
    try:
        return pull_app_proposals(tenant_key, st=st, now=now)
    except Exception as exc:                                           # noqa: BLE001
        _log.warning("amazon_operator: the App inbox pull for %s failed (%s): %s",
                     tenant_key, type(exc).__name__, exc)
        return None


def _app_item(rec):
    """One inbox item as the App and History show it."""
    return {"id": rec["id"], "kind": APP_KIND, "title": f"{rec.get('app')}: {rec.get('action')}",
            "app": rec.get("app"), "source_kind": rec.get("source_kind"), "source_module": rec.get("source_module"),
            "item_id": rec.get("item_id"), "status": rec.get("status"), "owner": rec.get("decided_by"),
            "due": None, "reason": rec.get("reason"), "sku": rec.get("sku") or None, "asin": None,
            "action": rec.get("action"), "change": rec.get("action"), "cause": rec.get("cause"),
            "note": rec.get("note"), "decision_id": rec.get("decision_id"), "decided_by": rec.get("decided_by"),
            "decided_at": rec.get("decided_at"), "day": rec.get("day") or str(rec.get("decided_at") or "")[:10],
            "first_seen": rec.get("first_seen"), "last_seen": rec.get("last_seen")}


def _decided_app_rows(st):
    return [{**rec, "kind": APP_KIND, "day": str(rec.get("decided_at") or "")[:10]}
            for rec in _inbox(st).values() if rec.get("status") in DECISIONS]


def app_items_today(st, *, now=None):
    """Open and stale inbox items, plus those decided today. Uncapped (rule 1)."""
    day = (now or _now()).date().isoformat()
    order = {"proposed": 0, "stale": 1}
    rows = [r for r in _inbox(st).values()
            if r.get("status") in INBOX_OPEN + ("stale",) or str(r.get("decided_at") or "")[:10] == day]
    rows.sort(key=lambda r: (order.get(r.get("status"), 2), r.get("app") or "", r.get("sku") or "", r["id"]))
    return [_app_item(r) for r in rows]


def _hand_back(tenant_key, rec, decision, reason):
    """Call the source App's on_decision. None on success, else the plain cause."""
    name, app = rec.get("source_module") or "", rec.get("app") or "Its App"
    if name not in PROPOSAL_SOURCES:
        return f"{app} is not an inbox source, so it could not take this decision."
    mod, _missing = _load_source(name)
    fn = getattr(mod, "on_decision", None) if mod is not None else None
    if not callable(fn):
        return f"{app} is not installed, so it could not take this decision."
    try:
        fn(tenant_key, rec["item_id"], decision, reason)
    except Exception as exc:                                           # noqa: BLE001
        detail = _plain(exc).rstrip(".")
        return f"{app} could not take this decision: {detail}." if detail else f"{app} could not take this decision."
    return None


def _decide_apps(st, tenant_key, ids, inbox, status, note, who, at):
    """Decide inbox items: claim them in one update, then hand each decision back to its App. Never writes outbound."""
    rows, eligible = {}, []
    for iid in ids:
        current = inbox[iid].get("status")
        if current == "stale" and status == "approved":
            rows[iid] = {"id": iid, "status": "skipped", "current": "stale",
                         "cause": f"{STALE} It cannot be approved."}
        elif current not in INBOX_OPEN + ("stale",):
            rows[iid] = {"id": iid, "status": "skipped", "current": current, "cause": _skip_cause(current, status)}
        else:
            eligible.append(iid)
    if not eligible:
        return rows, None
    decision_id = ("apd_" if status == "approved" else "dsm_") + uuid.uuid4().hex[:16]
    record = {"id": decision_id, "decision": status, "source": APP_KIND, "by": who, "at": at,
              "item_ids": eligible, "note": note}
    _put_decision(st, record)
    claimed = {}

    def _claim_apps(doc):
        doc = doc if isinstance(doc, dict) else {}
        claimed.clear()
        for iid in eligible:
            rec = (doc.get("items") or {}).get(iid)
            if isinstance(rec, dict) and rec.get("status") in INBOX_OPEN + ("stale",):
                claimed[iid] = rec["status"]
                rec.update(status=status, decision_id=decision_id, decided_by=who, decided_at=at, note=note,
                           cause=None if rec["status"] in INBOX_OPEN else rec.get("cause"))
        return doc
    st.update(KEY_INBOX, _claim_apps)
    done = []
    for iid in eligible:
        if iid not in claimed:
            rows[iid] = {"id": iid, "status": "skipped", "current": "decided", "cause": _skip_cause("decided", status)}
            continue
        rec = inbox[iid]
        # A stale item is gone from its App, so dismissing it closes it here only.
        cause = None if claimed[iid] == "stale" else _hand_back(
            tenant_key, rec, status, note or (APPROVED_NOTE if status == "approved" else ""))
        if cause:
            _reopen(st, iid, cause)
            rows[iid] = {"id": iid, "status": "refused", "cause": cause, "app": rec.get("app")}
        else:
            done.append(iid)
            rows[iid] = {"id": iid, "status": status, "app": rec.get("app")}
    if done != eligible:
        record["item_ids"] = done
        _put_decision(st, record)
    return rows, decision_id


def _reopen(st, iid, cause):
    """Put an inbox item back to proposed with the cause its App gave."""
    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        rec = (doc.get("items") or {}).get(iid)
        if isinstance(rec, dict):
            rec.update(status="proposed", cause=cause, decision_id=None, decided_by=None, decided_at=None, note=None)
        return doc
    st.update(KEY_INBOX, _apply)


def validate(tenant_key, day=None, *, st=None, **_period):
    """C4: a built day's evaluated spend ties to SUM(cost) over the three advertised products tables."""
    st = _rt(tenant_key, st)
    rec = day_record(tenant_key, day, st=st)
    if not rec:
        return {"ok": False, "app_total": None, "independent_total": None,
                "detail": "No proposals are built for this day."}
    data_date = rec.get("data_date")
    app_total = round(sum(float(v or 0) for v in (rec.get("spend") or {}).values()), 2)
    independent, by_type = 0.0, {}
    with _reader(tenant_key, st) as cur:
        if cur is None:
            return {"ok": False, "app_total": app_total, "independent_total": None,
                    "detail": "The tenant mirror is not there, so the Ads cost cannot be read."}
        for ad_type in ALL_AD_TYPES:
            table = _ads_table(ad_type, "advertised_products")
            if not {"date", "cost"} <= _columns(cur, table):
                continue
            row = cur.execute(f'SELECT SUM(TRY_CAST("cost" AS DOUBLE)) FROM {table} '
                              f"WHERE TRY_CAST(\"date\" AS DATE) = CAST(? AS DATE)", [data_date]).fetchone()
            by_type[ad_type] = round(float(row[0] or 0), 2)
            independent += float(row[0] or 0)
    independent = round(independent, 2)
    ok = abs(app_total - independent) <= 0.01
    detail = (f"Ad spend on {data_date}: proposals read {_money(app_total)}, the Ads tables hold "
              f"{_money(independent)}.")
    if not ok:
        missed = [AD_LABELS[t] for t in ALL_AD_TYPES
                  if abs(by_type.get(t, 0.0) - float((rec.get("spend") or {}).get(t, 0.0))) > 0.01]
        detail += " They do not tie" + (": " + ", ".join(missed) + " differ." if missed else ".")
    return {"ok": ok, "app_total": app_total, "independent_total": independent, "detail": detail,
            "by_type": by_type}


def remove(tenant_key, *, st=None):
    """Delete every document in KEYS and nothing else. Connector tables and the mirror stay (rule 13)."""
    st = _rt(tenant_key, st)
    for key in KEYS:
        deleter = getattr(st, "delete_document", None)
        if callable(deleter):
            deleter(key)
        else:
            st.update(key, lambda _doc: {})
    return list(KEYS)