File size: 84,359 Bytes
3e19b1e
b2aa446
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
b2aa446
 
 
3e19b1e
 
 
 
 
b2aa446
 
3e19b1e
b2aa446
 
3e19b1e
 
 
 
 
 
 
b2aa446
3e19b1e
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a97d6f1
b2aa446
 
 
a97d6f1
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
3e19b1e
 
b2aa446
 
 
 
 
 
3e19b1e
 
b2aa446
3e19b1e
 
 
 
 
 
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
3e19b1e
b2aa446
 
 
3e19b1e
 
 
 
 
 
 
 
b2aa446
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
 
3e19b1e
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
3e19b1e
b2aa446
3e19b1e
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
b2aa446
 
 
 
 
 
3e19b1e
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
3e19b1e
b2aa446
3e19b1e
 
b2aa446
3e19b1e
 
 
 
 
 
 
b2aa446
3e19b1e
 
b2aa446
 
 
 
 
3e19b1e
 
b2aa446
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
b2aa446
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
3e19b1e
 
 
 
b2aa446
 
3e19b1e
b2aa446
 
 
 
 
 
 
 
3e19b1e
 
b2aa446
3e19b1e
 
b2aa446
3e19b1e
 
b2aa446
 
 
 
3e19b1e
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
b2aa446
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
3e19b1e
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
3e19b1e
 
b2aa446
 
3e19b1e
 
b2aa446
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
b2aa446
 
 
 
 
 
 
3e19b1e
 
b2aa446
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
3e19b1e
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
3e19b1e
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
3e19b1e
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
"""Per-tenant PostgreSQL money-search rival pools and daily quotes.

Discovery reads the Amazon mirror through a cursor the caller opens: core imports no harness
module (verify_layering) and no App module (rule 13). Tables are created on the first write.
"""

from contextlib import contextmanager
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
import json
import re
import statistics
import time
import uuid

RIVALS = 'amazon_rivals'
DISCOVERY = 'amazon_rival_discovery'
QUOTES = 'amazon_rival_quotes'
RUNS = 'amazon_rival_runs'
WANTED = 'amazon_rival_wanted'
TABLES = (RIVALS, DISCOVERY, QUOTES, RUNS, WANTED)

#: Brand Analytics keeps the top 3 clicked ASINs of each search term.
TOP_CLICKED = 3
SOURCES = frozenset(('auto', 'added'))
CHUNK = 200

BA_TABLE = 'amzn_brand_analytics'
LISTINGS_TABLE = 'amzn_listings'
PRICING_TABLE = 'amzn_pricing'
SQP_TABLE = 'amzn_search_query_performance'
RANKS_TABLE = 'amzn_apify_rank_observations'
SNAPSHOTS_TABLE = 'amzn_competitor_snapshots'
IMAGES_TABLE = 'amzn_competitor_images'
POOL_SNAPSHOT_FIELDS = ('snapshot_date', 'brand', 'title', 'bullets', 'price', 'currency', 'prime', 'offers')
POOL_IMAGE_FIELDS = ('variant', 'link', 'width', 'height')

NO_TOP3 = "Not in any search term's top 3 clicked"
NO_WEEK = 'Brand Analytics has no dated weekly reports'
NO_MONTH = 'No completed monthly Search Query Performance report for this product yet.'
NO_MONEY = 'No searches with market money for this product yet.'
NO_KEYWORD_RANKS = "No keyword ranks for this product's searches yet."
NO_PRODUCT_TYPE = 'Product type not read yet. The next daily run reads it.'
WAITING_PRODUCT_TYPE = '{count} found, waiting for the daily read of their product type.'
NOT_OURS = 'Not an ASIN in your Amazon listings'
PARENT_ROLLS_UP = 'A Parent ASIN has no rival list. Its fields roll up its child ASINs.'
NO_POOL = 'No search report or keyword ranks for this product yet.'
ASIN_RE = re.compile(r'[A-Z0-9]{10}')

POOL_FIELDS = {
    RIVALS: {'origin': ('TEXT', "'click'"), 'money_won': ('DOUBLE PRECISION', '0'),
             'terms_won': ('INTEGER', '0'), 'term_rank': ('INTEGER', 'NULL'),
             'eligible': ('BOOLEAN', 'TRUE')},
    DISCOVERY: {'month': ('DATE', 'NULL'), 'keyword_ranks_on': ('DATE', 'NULL'),
                'product_type': ('TEXT', 'NULL'), 'held': ('INTEGER', '0')},
}
RIVAL_COLUMNS = ('asin', 'rival_asin', 'source', 'removed', 'click_share', 'term', 'title', 'week',
                 'added_by', 'updated_at', *POOL_FIELDS[RIVALS])
DISCOVERY_COLUMNS = ('asin', 'week', 'discovered_at', 'cause', 'auto_count', *POOL_FIELDS[DISCOVERY])
QUOTE_COLUMNS = ('asin', 'quote_on', 'offer_price', 'buy_box_price', 'sales_rank', 'display_group',
                 'offer_cause', 'buy_box_cause', 'rank_cause', 'offers', 'currency', 'run_id', 'quoted_at')
RUN_COLUMNS = ('id', 'started_at', 'progress', 'progress_at', 'finished_at', 'asin_total', 'priced',
               'ranked', 'caused', 'cause', 'counts')
WANTED_COLUMNS = ('asin', 'source', 'wanted_at')


class BackendUnavailable(RuntimeError):
    """Rival rows require PostgreSQL and never fall back to an HF document."""


class MirrorUnreadable(RuntimeError):
    """The Amazon mirror could not be read. Never read as an absent table."""


class FixtureAdapter:
    """Explicit offline fixture marker, never selected as a production fallback."""


def _now():
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()


def _day(value):
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.date().isoformat()
    if isinstance(value, date):
        return value.isoformat()
    return str(value)[:10]


def asin(value, field='asin'):
    """An upper-case 10 character ASIN, or ValueError naming the field."""
    text = str(value or '').strip().upper()
    if not ASIN_RE.fullmatch(text):
        raise ValueError(f'{field} must be a 10 character ASIN.')
    return text


def _asins(values):
    return sorted({asin(v) for v in values})


def _backend(rt):
    if rt is None:
        raise BackendUnavailable('Competitors require an explicitly bound PostgreSQL tenant runtime.')
    bound = rt._store() if callable(getattr(rt, '_store', None)) else rt
    from core import store_pg
    if not isinstance(bound, (store_pg.PgStore, FixtureAdapter)):
        raise BackendUnavailable('Competitors require PostgreSQL (STORE_BACKEND=pg). HF document storage is unsupported.')
    slug = getattr(bound, 'tenant_slug', None)
    if (not slug or getattr(rt, 'key', slug) != slug or getattr(rt, 'store_namespace', '')
            or getattr(getattr(rt, 'tenant', None), 'key', slug) != slug):
        raise ValueError('The competitors runtime and its tenant store must match.')
    if isinstance(bound, FixtureAdapter):
        return bound
    return PgRivalStore(bound)


# --------------------------------------------------------------------------- mirror reads

def weekly_period_sql():
    """Admit connector weeks with exclusive ends and legacy weeks with inclusive ends."""
    start = 'TRY_CAST("_period_start" AS TIMESTAMP)'
    end = 'TRY_CAST("_period_end" AS TIMESTAMP)'
    return (f"isfinite({start}) AND isfinite({end}) AND "
            f"date_diff('day', CAST({start} AS DATE), CAST({end} AS DATE)) IN (6, 7)")


def _week_sql():
    return 'CAST(TRY_CAST("_period_start" AS TIMESTAMP) AS DATE)'


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 as exc:                                           # noqa: BLE001
        raise MirrorUnreadable(type(exc).__name__) from exc


def _read(cur, sql, args=()):
    try:
        return cur.execute(sql, list(args)).fetchall()
    except Exception as exc:                                           # noqa: BLE001
        raise MirrorUnreadable(type(exc).__name__) from exc


def _in(values):
    return '(' + ','.join('?' for _ in values) + ')'


def newest_week(cur):
    """The newest dated Brand Analytics week start as YYYY-MM-DD, None when there is none."""
    if not {'_period_start', '_period_end', 'clicked_asin', 'search_term'} <= _columns(cur, BA_TABLE):
        return None
    rows = _read(cur, f'SELECT max({_week_sql()}) FROM {BA_TABLE} WHERE {weekly_period_sql()}')
    return _day(rows[0][0]) if rows and rows[0][0] is not None else None


def our_asins(cur, candidates=None):
    """Our ASINs from `amzn_listings.asin1`, restricted to `candidates` when given."""
    if candidates is not None and not candidates:
        return set()
    if 'asin1' not in _columns(cur, LISTINGS_TABLE):
        return set()
    wanted = None if candidates is None else _asins(candidates)
    where = f' AND upper(trim(CAST("asin1" AS VARCHAR))) IN {_in(wanted)}' if wanted else ''
    rows = _read(cur, f'SELECT DISTINCT upper(trim(CAST("asin1" AS VARCHAR))) FROM {LISTINGS_TABLE} '
                      f'WHERE "asin1" IS NOT NULL{where}', wanted or ())
    return {r[0] for r in rows if r[0]}


def sku_asin(cur, sku):
    """The ASIN a SKU lists under, None when the listings do not name one."""
    if not {'seller_sku', 'asin1'} <= _columns(cur, LISTINGS_TABLE):
        return None
    rows = _read(cur, f'SELECT DISTINCT upper(trim(CAST("asin1" AS VARCHAR))) FROM {LISTINGS_TABLE} '
                      'WHERE trim(CAST("seller_sku" AS VARCHAR)) = ? AND "asin1" IS NOT NULL LIMIT 2',
                 (str(sku).strip(),))
    return rows[0][0] if len(rows) == 1 and rows[0][0] else None


def children(cur, parent):
    """The child ASINs of a Parent ASIN, from the sales and traffic report."""
    if not {'parent_asin', 'child_asin'} <= _columns(cur, PRICING_TABLE):
        return []
    rows = _read(cur, f'SELECT DISTINCT upper(trim(CAST("child_asin" AS VARCHAR))) FROM {PRICING_TABLE} '
                      'WHERE upper(trim(CAST("parent_asin" AS VARCHAR))) = ? '
                      'AND upper(trim(CAST("child_asin" AS VARCHAR))) <> ? ORDER BY 1',
                 (parent, parent))
    return [r[0] for r in rows if r[0]]


def _money_sql(cur):
    """Newest completed monthly searches per ASIN, including zero-money searches for freshness."""
    required = {'asin', 'search_query_data_search_query', 'start_date', 'end_date',
                'purchase_data_total_purchase_count', 'purchase_data_total_median_purchase_price_amount'}
    if not required <= _columns(cur, SQP_TABLE):
        return ('SELECT NULL::VARCHAR AS asin, NULL::VARCHAR AS term, NULL::DATE AS month, '
                'NULL::DOUBLE AS market_money WHERE FALSE')
    return f'''
        WITH reports AS (
            SELECT upper(trim(CAST(asin AS VARCHAR))) AS asin,
                   lower(trim(CAST(search_query_data_search_query AS VARCHAR))) AS term,
                   TRY_CAST(start_date AS DATE) AS start_on, TRY_CAST(end_date AS DATE) AS end_on,
                   TRY_CAST(purchase_data_total_purchase_count AS DOUBLE) *
                   TRY_CAST(purchase_data_total_median_purchase_price_amount AS DOUBLE) AS market_money
            FROM {SQP_TABLE}
            WHERE date_diff('day', TRY_CAST(start_date AS DATE), TRY_CAST(end_date AS DATE)) > 7
              AND TRY_CAST(end_date AS DATE) < CURRENT_DATE),
        latest AS (
            SELECT * FROM reports QUALIFY end_on = max(end_on) OVER (PARTITION BY asin))
        SELECT asin, term, CAST(date_trunc('month', start_on) AS DATE) AS month,
               max(market_money) AS market_money
        FROM latest GROUP BY asin, term, month'''


def _click_sql(cur):
    """Normalized dated top-three clicks, with percentage shares kept in their source units."""
    cols = _columns(cur, BA_TABLE)
    if not {'search_term', 'clicked_asin', 'click_share_rank', 'click_share',
            '_period_start', '_period_end'} <= cols:
        return ('SELECT NULL::VARCHAR AS term, NULL::VARCHAR AS rival, NULL::DOUBLE AS share, '
                'NULL::VARCHAR AS title, NULL::INTEGER AS term_rank, NULL::DATE AS week WHERE FALSE')
    title = 'CAST(clicked_item_name AS VARCHAR)' if 'clicked_item_name' in cols else 'NULL::VARCHAR'
    return f'''SELECT lower(trim(CAST(search_term AS VARCHAR))) AS term,
                      upper(trim(CAST(clicked_asin AS VARCHAR))) AS rival,
                      TRY_CAST(click_share AS DOUBLE) AS share, {title} AS title,
                      TRY_CAST(click_share_rank AS INTEGER) AS term_rank, {_week_sql()} AS week
               FROM {BA_TABLE} WHERE {weekly_period_sql()}
                 AND TRY_CAST(click_share_rank AS INTEGER) BETWEEN 1 AND {TOP_CLICKED}'''


def _rank_rows_sql(cur):
    """Raw Keyword ranks observations include rivals absent from the own-placement view."""
    if not {'keyword', 'asin', 'date', 'organic_rank', 'is_sponsored'} <= _columns(cur, RANKS_TABLE):
        return ('SELECT NULL::VARCHAR AS term, NULL::VARCHAR AS rival, NULL::DATE AS observed_on, '
                'NULL::INTEGER AS term_rank, NULL::BOOLEAN AS sponsored WHERE FALSE')
    return f'''SELECT lower(trim(CAST(keyword AS VARCHAR))) AS term,
                      upper(trim(CAST(asin AS VARCHAR))) AS rival, TRY_CAST(date AS DATE) AS observed_on,
                      TRY_CAST(organic_rank AS INTEGER) AS term_rank,
                      TRY_CAST(is_sponsored AS BOOLEAN) AS sponsored FROM {RANKS_TABLE}'''


def _search_dates(cur, targets):
    rows = _read(cur, f'''
        WITH money AS ({_money_sql(cur)}), observations AS ({_rank_rows_sql(cur)})
        SELECT m.asin, max(m.month), max(o.observed_on), count(DISTINCT m.term)
               FILTER (WHERE m.market_money > 0)
        FROM money m LEFT JOIN observations o ON o.term = m.term AND m.market_money > 0
        WHERE m.asin IN {_in(targets)} GROUP BY m.asin''', targets)
    return {a: dict(month=_day(m), keyword_ranks_on=_day(k), money_terms=n) for a, m, k, n in rows}


def _newest_snapshots_sql(cur, fields=('product_type', 'brand')):
    if not {'asin', 'snapshot_date', 'product_type', 'brand'} <= _columns(cur, SNAPSHOTS_TABLE):
        return 'SELECT NULL::VARCHAR AS asin, ' + ', '.join(f'NULL::VARCHAR AS {f}' for f in fields) + ' WHERE FALSE'
    return (f'SELECT upper(trim(asin)) AS asin, {", ".join(fields)} FROM {SNAPSHOTS_TABLE} '
            'QUALIFY row_number() OVER (PARTITION BY upper(trim(asin)) ORDER BY snapshot_date DESC) = 1')


def _brand(value):
    return ''.join((value or '').casefold().split())


def _same_type(target_type, rival_type):
    return bool(target_type and rival_type and target_type == rival_type)


def _other_brand(brand, own_brands):
    return not _brand(brand) or _brand(brand) not in own_brands


@dataclass
class PoolFacts:
    """Newest ASIN facts and all historical own brands determine pool eligibility."""

    latest: dict
    own_brands: set
    own_asins: set

    def product_type(self, target):
        return self.latest.get(target, {}).get('product_type')

    def eligible(self, target, rival):
        fact = self.latest.get(rival, {})
        return (rival not in self.own_asins and _same_type(self.product_type(target), fact.get('product_type'))
                and _other_brand(fact.get('brand'), self.own_brands))


def _pool_facts(cur, values, own, prefetched=None, candidate_rows=()):
    latest = {r[1]: dict(product_type=r[-2], brand=r[-1]) for r in candidate_rows}
    for part in _chunks(sorted(values - latest.keys())):
        rows = _read(cur, f'SELECT asin, product_type, brand FROM ({_newest_snapshots_sql(cur)}) '
                         f'WHERE asin IN {_in(part)}', part)
        latest.update({a: dict(product_type=t, brand=b) for a, t, b in rows})
    brands = set()
    if {'asin', 'brand'} <= _columns(cur, SNAPSHOTS_TABLE):
        rows = _read(cur, f'SELECT DISTINCT s.brand FROM {SNAPSHOTS_TABLE} s '
                         f'JOIN {LISTINGS_TABLE} l ON upper(trim(s.asin)) = upper(trim(l.asin1))')
        brands.update(_brand(row[0]) for row in rows if _brand(row[0]))
    latest.update(prefetched or {})
    brands.update(_brand(latest[a].get('brand')) for a in own if a in latest and _brand(latest[a].get('brand')))
    return PoolFacts(latest, brands, own)


def _candidates(cur, targets, week):
    """Every non-own clicked or organic page-one ASIN on each target's monthly money searches."""
    sql = f'''
        WITH money AS ({_money_sql(cur)}), clicks AS ({_click_sql(cur)}),
        observations AS ({_rank_rows_sql(cur)}),
        newest_observations AS (
            SELECT * FROM observations
            QUALIFY observed_on = max(observed_on) OVER (PARTITION BY term)),
        click AS (
            SELECT term, rival, max(share) AS share, min(term_rank) AS term_rank, max(title) AS title
            FROM clicks WHERE week = CAST(? AS DATE) GROUP BY term, rival),
        page1 AS (
            SELECT term, rival, min(term_rank) AS term_rank FROM newest_observations
            WHERE sponsored = FALSE GROUP BY term, rival),
        placements AS (
            SELECT coalesce(c.term, p.term) AS term, coalesce(c.rival, p.rival) AS rival,
                   c.share, c.title, coalesce(c.term_rank, p.term_rank) AS term_rank,
                   c.term IS NOT NULL AS clicked, p.term IS NOT NULL AS page1
            FROM click c FULL OUTER JOIN page1 p ON p.term = c.term AND p.rival = c.rival),
        hits AS (
            SELECT m.asin, p.*, m.market_money * coalesce(p.share, 0) / 100 AS money_won
            FROM money m JOIN placements p ON p.term = m.term
            WHERE m.asin IN {_in(targets)} AND m.market_money > 0 AND p.rival <> ''
              AND p.rival NOT IN (SELECT upper(trim(CAST(asin1 AS VARCHAR)))
                                 FROM {LISTINGS_TABLE} WHERE asin1 IS NOT NULL)),
        totals AS (
            SELECT asin, rival, max(share) AS share, sum(money_won) AS money_won,
                   count(*) FILTER (WHERE clicked AND term_rank = 1) AS terms_won,
                   CASE WHEN bool_or(clicked) AND bool_or(page1) THEN 'both'
                        WHEN bool_or(clicked) THEN 'click' ELSE 'page1' END AS origin
            FROM hits GROUP BY asin, rival),
        representative AS (
            SELECT asin, rival, term, title, term_rank FROM hits
            QUALIFY row_number() OVER (PARTITION BY asin, rival
                                      ORDER BY money_won DESC, term_rank, term) = 1)
        SELECT t.asin, t.rival, t.share, r.term, r.title, t.origin, t.money_won, t.terms_won, r.term_rank,
               s.product_type, s.brand
        FROM totals t JOIN representative r USING (asin, rival)
        LEFT JOIN ({_newest_snapshots_sql(cur)}) s ON s.asin = t.rival
        ORDER BY t.asin, t.money_won DESC, t.rival'''
    return _read(cur, sql, (week, *targets))


# --------------------------------------------------------------------------- discovery

def discover(rt, cur, asins=None, *, candidate_rows=None, prefetched=None):
    """Refresh uncapped money-search pools while preserving removed and hand-added rivals."""
    backend = _backend(rt)
    requested = None if asins is None else _asins(asins)
    targets = sorted(our_asins(cur, requested))
    stamp = _now()
    discovery = {}
    for missing in sorted(set(requested or ()) - set(targets)):
        discovery[missing] = dict(asin=missing, week=None, discovered_at=stamp, cause=NOT_OURS,
                                  auto_count=0, month=None, keyword_ranks_on=None, product_type=None, held=0)
    week = newest_week(cur) if targets else None
    dates = _search_dates(cur, targets) if targets else {}
    rows = (_candidates(cur, targets, week) if candidate_rows is None else candidate_rows) if targets else []
    stored = backend.pool_rows(targets)
    before = backend.rivals_of(targets)
    values = set(targets) | {r[1] for r in rows} | {r['rival_asin'] for r in stored}
    facts = _pool_facts(cur, values, our_asins(cur), prefetched, rows)
    found, held = _eligible_candidates(rows, stored, facts, week, stamp)
    for target in targets:
        count = (len(found.get(target, ())) if facts.product_type(target) else
                 sum(r['source'] == 'auto' for r in stored if r['asin'] == target and not r['removed']))
        meta = dates.get(target) or dict(month=None, keyword_ranks_on=None, money_terms=0)
        cause = _pool_cause(facts.product_type(target), held.get(target, 0), week, meta, count)
        discovery[target] = dict(asin=target, week=week, discovered_at=stamp, cause=cause, auto_count=count,
                                 month=meta['month'], keyword_ranks_on=meta['keyword_ranks_on'],
                                 product_type=facts.product_type(target), held=held.get(target, 0))
    ready = [t for t in targets if facts.product_type(t)]
    backend.replace_auto(ready, [row for t in ready for row in found.get(t, ())], list(discovery.values()))
    backend.set_eligibility(stored, facts)
    members = backend.rivals_of(targets)
    pools = {target: len(members.get(target, ())) for target in targets}
    return {'asins': len(targets), 'rivals': sum(len(v) for v in found.values()), 'week': week,
            'pools': pools, 'rowsRead': len(rows), 'held': held,
            'changed': tuple(t for t in targets if set(before.get(t, ())) != set(members.get(t, ()))),
            'causes': {k: v['cause'] for k, v in discovery.items() if v['cause']}}


def _eligible_candidates(rows, stored, facts, week, stamp):
    kept = {(r['asin'], r['rival_asin']) for r in stored if r['removed'] or r['source'] == 'added'}
    candidates = {(r[0], r[1]) for r in rows} | {
        (r['asin'], r['rival_asin']) for r in stored if r['source'] == 'added' and not r['removed']}
    removed = {(r['asin'], r['rival_asin']) for r in stored if r['removed']}
    held = {}
    for target, rival in candidates - removed:
        if (rival not in facts.own_asins and not facts.product_type(rival)
                and _other_brand(facts.latest.get(rival, {}).get('brand'), facts.own_brands)):
            held[target] = held.get(target, 0) + 1
    found = {}
    for target, rival, share, term, title, origin, money, terms, term_rank, _type, _name in rows:
        if (target, rival) in kept or not facts.eligible(target, rival):
            continue
        found.setdefault(target, []).append(dict(
            asin=target, rival_asin=rival, source='auto', removed=False, eligible=True,
            click_share=None if share is None else float(share), term=term, title=title,
            week=week, added_by=None, updated_at=stamp, origin=origin,
            money_won=float(money), terms_won=int(terms), term_rank=term_rank))
    return found, held


def _discovery_cause(week, meta, count):
    if meta['month'] is None:
        return NO_MONTH
    if not meta['money_terms']:
        return NO_MONEY
    if meta['keyword_ranks_on'] is None:
        return NO_KEYWORD_RANKS
    if week is None:
        return NO_WEEK
    return None if count else NO_TOP3


def _pool_cause(product_type, held, week, meta, count):
    if not product_type:
        return NO_PRODUCT_TYPE
    if held:
        return WAITING_PRODUCT_TYPE.format(count=held)
    return _discovery_cause(week, meta, count)


def stale(rt, cur, target):
    """True when the ASIN's discovery predates a weekly, monthly or Keyword ranks source."""
    row = _backend(rt).discovery([target]).get(target)
    if row is None:
        return True
    types = _read(cur, f'SELECT product_type FROM ({_newest_snapshots_sql(cur)}) WHERE asin = ?', [target])
    product_type = types[0][0] if types else None
    if row['product_type'] != product_type or (not product_type and row['cause'] != NO_PRODUCT_TYPE):
        return True
    newest = {'week': newest_week(cur), **(_search_dates(cur, [target]).get(target) or {})}
    return any(newest.get(key) is not None and
               (row.get(key) is None or row[key] < newest[key])
               for key in ('week', 'month', 'keyword_ranks_on'))


# --------------------------------------------------------------------------- doors

def rivals(rt, target):
    """One ASIN's rivals: hand-added first, then money won and rank average, with discovery dates."""
    target = asin(target)
    backend = _backend(rt)
    rows = backend.rivals(target)
    found = backend.discovery([target]).get(target)
    return {'asin': target, 'rivals': rows, 'removed': backend.removed_count(target),
            'week': found['week'] if found else None,
            'month': found['month'] if found else None,
            'keywordRanksOn': found['keyword_ranks_on'] if found else None,
            'discoveredAt': found['discovered_at'] if found else None,
            'cause': found['cause'] if found else None,
            'productType': found['product_type'] if found else None,
            'held': found['held'] if found else 0}


def pool(rt, cur, target):
    """Read eligible pool rows through the caller's mirror cursor without writes or provider reads."""
    target = asin(target)
    backend = _backend(rt)
    if cur is None:
        return {**rivals(rt, target), 'rivals': [], 'competitors': [], 'dataAsOf': None, 'cause': NO_POOL}
    own = our_asins(cur)
    week = newest_week(cur)
    sources = _candidates(cur, [target], week) if target in own else []
    stored = backend.pool_rows([target])
    facts = _pool_facts(cur, {target} | {r[1] for r in sources} | {r['rival_asin'] for r in stored},
                        own, candidate_rows=sources)
    found, held = _eligible_candidates(sources, stored, facts, week, _now())
    if facts.product_type(target):
        rows = found.get(target, []) + [dict(r, eligible=True) for r in stored
                                       if r['source'] == 'added' and not r['removed']
                                       and facts.eligible(target, r['rival_asin'])]
    else:
        rows = [r for r in stored if r['eligible'] and not r['removed'] and r['rival_asin'] not in own
                and _other_brand(facts.latest.get(r['rival_asin'], {}).get('brand'), facts.own_brands)]
    if target not in own:
        rows = []
    averages = backend.rank_averages([r['rival_asin'] for r in rows])
    rows = [{**r, **averages.get(r['rival_asin'], {'rank_average': None, 'rank_days': 0})} for r in rows]
    meta = _search_dates(cur, [target]).get(target) or dict(month=None, keyword_ranks_on=None, money_terms=0)
    cause = _pool_cause(facts.product_type(target), held.get(target, 0), week, meta, len(rows))
    rows = sorted(rows, key=_pool_order)
    snapshots = _pool_snapshots(cur, [target, *(r['rival_asin'] for r in rows)])
    images = _pool_images(cur, [r['rival_asin'] for r in rows])
    dates = [s['snapshot_date'] for s in snapshots.values() if s['snapshot_date'] is not None]
    return {**rivals(rt, target), 'rivals': rows, 'week': week,
            'month': meta['month'], 'keywordRanksOn': meta['keyword_ranks_on'],
            'productType': facts.product_type(target), 'held': held.get(target, 0),
            'cause': cause if target in own else NOT_OURS, 'dataAsOf': max(dates, default=None),
            'competitors': [_pool_competitor(r, snapshots.get(r['rival_asin'], {}),
                                             images.get(r['rival_asin'], [])) for r in rows]}


def _pool_snapshots(cur, values):
    snapshots = {}
    for part in _chunks(sorted(set(values))):
        rows = _read(cur, f'SELECT * FROM ({_newest_snapshots_sql(cur, POOL_SNAPSHOT_FIELDS)}) '
                         f'WHERE asin IN {_in(part)}', part)
        for target, *fields in rows:
            snapshot = dict(zip(POOL_SNAPSHOT_FIELDS, fields))
            snapshot['snapshot_date'] = _day(snapshot['snapshot_date'])
            snapshot['bullets'] = json.loads(snapshot['bullets'] or '[]')
            snapshots[target] = snapshot
    return snapshots


def _pool_images(cur, values):
    """Resolve only the newest snapshot's variants against changed-link history."""
    images = {}
    if not {'asin', *POOL_IMAGE_FIELDS} <= _columns(cur, IMAGES_TABLE):
        return images
    for part in _chunks(values):
        rows = _read(cur, f'''
            SELECT s.asin, i.variant, i.link, i.width, i.height
            FROM ({_newest_snapshots_sql(cur, ('image_variants',))}) s,
                 json_each(s.image_variants) v, {IMAGES_TABLE} i
            WHERE s.asin IN {_in(part)} AND i.asin = s.asin
              AND i.variant = json_extract_string(v.value, '$.variant')
              AND i.link = json_extract_string(v.value, '$.link')
            ORDER BY s.asin, CAST(v.key AS INTEGER)''', part)
        for target, *fields in rows:
            images.setdefault(target, []).append(dict(zip(POOL_IMAGE_FIELDS, fields)))
    return images


def _pool_competitor(row, snapshot, images):
    days = row['rank_days']
    return {'asin': row['rival_asin'], 'brand': snapshot.get('brand'), 'title': snapshot.get('title'),
            'origin': row['origin'], 'moneyWon': row['money_won'], 'termsWon': row['terms_won'],
            'term': row['term'], 'termRank': row['term_rank'], 'bestSellerRank': row['rank_average'],
            'rankDays': days, 'rankCause': f'Rank average needs 7 days of ranks. {days} so far.' if days < 7 else None,
            'price': snapshot.get('price'), 'currency': snapshot.get('currency'), 'prime': snapshot.get('prime'),
            'offers': snapshot.get('offers'), 'imageCount': len(images), 'images': images,
            'bullets': snapshot.get('bullets', []), 'snapshotOn': snapshot.get('snapshot_date')}


def add(rt, target, rival, *, user, title=None):
    """Add or restore one hand-added rival of an ASIN."""
    target, rival = asin(target), asin(rival, 'rival')
    if rival == target:
        raise ValueError('An ASIN cannot be its own rival.')
    return _backend(rt).add(dict(asin=target, rival_asin=rival, source='added', removed=False, eligible=False,
                                 click_share=None, term=None, title=title, week=None,
                                 added_by=str(user or '') or None, updated_at=_now(),
                                 origin='added', money_won=0, terms_won=0, term_rank=None))


def remove(rt, target, rival, *, user):
    """Mark one rival removed, so discovery never adds it back."""
    return _backend(rt).remove(asin(target), asin(rival, 'rival'), str(user or '') or None, _now())


def rival_asins(rt):
    """Every distinct rival ASIN not removed, for the daily quotes run."""
    return _backend(rt).rival_asins()


def want(rt, asins, source):
    """Register ASINs another surface needs priced by the daily run. Idempotent."""
    if not isinstance(source, str) or not re.fullmatch(r'[a-z0-9_]{1,64}', source):
        raise ValueError('source must be a short lower-case name.')
    values = _asins(asins)
    if not values:
        return {'wanted': 0}
    return _backend(rt).want(values, source, _now())


def wanted(rt, source=None):
    """The wanted ASINs, optionally of one source."""
    return _backend(rt).wanted(source)


def put_quotes(rt, rows):
    """Upsert daily quote rows keyed (asin, quote_on). Each value without a figure carries a cause."""
    clean = []
    for row in rows:
        item = {key: row.get(key) for key in QUOTE_COLUMNS}
        item['asin'] = asin(item['asin'])
        item['quote_on'] = _day(item['quote_on']) or _day(datetime.now(timezone.utc))
        if item['offers'] is not None and not isinstance(item['offers'], str):
            item['offers'] = json.dumps(item['offers'], separators=(',', ':'))
        item['quoted_at'] = item['quoted_at'] or _now()
        clean.append(item)
    return _backend(rt).put_quotes(clean)


def newest_quotes(rt, asins):
    """`{asin: quote}` holding each ASIN's newest quote row. An ASIN with none is absent."""
    values = _asins(asins)
    return _backend(rt).newest_quotes(values) if values else {}


def start_run(rt, run_id, *, asin_total):
    """Open one quotes run row."""
    return _backend(rt).start_run(str(run_id), int(asin_total), _now())


def mark_run(rt, run_id, *, progress, finished=False, counts=None, cause=None, asin_total=None):
    """Record a run's progress marker, and its finish and counts when `finished`."""
    return _backend(rt).mark_run(str(run_id), int(progress), _now(), finished, counts or {}, cause,
                                 None if asin_total is None else int(asin_total))


def runs(rt, limit=10):
    """The newest run rows first."""
    return _backend(rt).runs(int(limit))


def rank_average(rt, asins):
    """Mean daily rank in each ASIN's newest display group, requiring seven of its newest 30 days."""
    values = _asins(asins)
    found = _backend(rt).rank_averages(values) if values else {}
    return {a: (found.get(a) or {}).get('rank_average') for a in values}


def _pool_order(row):
    average = row.get('rank_average')
    return (-float(row.get('money_won') or 0),
            average is None, average if average is not None else 0, row['rival_asin'])


# --------------------------------------------------------------------------- the daily quotes run

#: The run row gets a progress marker after each block of this many ASINs.
PROGRESS_EVERY = 100
#: One SP-API call per this many ASINs: the batch size of all three reads.
READ_BATCH = 20
#: A throttled batch is retried this many times after a backoff, then keeps its cause.
THROTTLE_RETRIES = 2
BACKOFF_SECONDS = 60.0
MAX_BACKOFF_SECONDS = 300.0
#: An unfinished run, or a finished run with a cause, is retried after this many hours.
RETRY_RUN_HOURS = 3

READS = {'offers': 'offers', 'summaries': 'Buy Box price', 'facts': 'catalog facts'}
FACT_COUNT_COLUMNS = {'title': 'title', 'product_type': 'product_type', 'image': 'image', 'rank': 'sales_rank'}
NO_MIRROR = 'The Amazon data is not on this worker yet, so no ASIN was quoted.'
NO_OWN_OFFER = 'Amazon returned no offer of yours on this ASIN.'
NO_BUY_BOX = 'Amazon returned no Buy Box offer for this ASIN.'
NO_PRICE = 'Amazon returned no price for this ASIN.'
NO_RANK = 'Amazon returned no sales rank for this ASIN.'
#: The quote fields S82-T89 compares to find a changed row.
QUOTED_FIELDS = ('offer_price', 'buy_box_price', 'sales_rank', 'display_group')


def _stamp(value):
    got = datetime.fromisoformat(str(value))
    return got if got.tzinfo else got.replace(tzinfo=timezone.utc)


def due(rt, *, now=None):
    """True when this tenant has no run today, or its last run stopped or failed hours ago."""
    now = now or datetime.now(timezone.utc)
    newest = _backend(rt).runs(1)
    if not newest:
        return True
    row = newest[0]
    if _stamp(row['started_at']).date() < now.date():
        return True
    if row['finished_at'] and not row['cause']:
        return False
    last = _stamp(row['finished_at'] or row['progress_at'] or row['started_at'])
    return now - last >= timedelta(hours=RETRY_RUN_HOURS)


def unresolved(row, own):
    """The quote fields of one row with neither a value nor a cause. Empty when the row is whole."""
    pairs = [('buy_box_price', 'buy_box_cause'), ('sales_rank', 'rank_cause')]
    if own:
        pairs.insert(0, ('offer_price', 'offer_cause'))
    return [value for value, cause in pairs if row.get(value) is None and not row.get(cause)]


def _number(value):
    return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None


def _offer_quote(response, seller_id):
    """Our offer price and the Buy Box price as two values (R40), plus every offer Amazon returned."""
    payload = (((response or {}).get('body') or {}).get('payload') or {})
    offers = []
    for offer in payload.get('Offers') or ():
        if not isinstance(offer, dict):
            continue
        listing = offer.get('ListingPrice') or {}
        offers.append({'sellerId': offer.get('SellerId'), 'price': _number(listing.get('Amount')),
                       'shipping': _number((offer.get('Shipping') or {}).get('Amount')),
                       'currency': listing.get('CurrencyCode'), 'buyBox': bool(offer.get('IsBuyBoxWinner')),
                       'mine': bool(offer.get('MyOffer')) or bool(seller_id and offer.get('SellerId') == seller_id),
                       'fba': bool(offer.get('IsFulfilledByAmazon')), 'condition': offer.get('SubCondition')})
    mine = next((o for o in offers if o['mine'] and o['price'] is not None), None)
    box = next((o for o in offers if o['buyBox'] and o['price'] is not None), None)
    box_price = box['price'] if box else None
    currency = (mine or box or {}).get('currency')
    if box_price is None:
        for entry in (payload.get('Summary') or {}).get('BuyBoxPrices') or ():
            amount = _number(((entry or {}).get('ListingPrice') or {}).get('Amount'))
            if amount is not None and str((entry or {}).get('condition') or 'New').lower() == 'new':
                box_price, currency = amount, currency or entry['ListingPrice'].get('CurrencyCode')
                break
    return {'offer_price': mine['price'] if mine else None, 'offer_cause': None if mine else NO_OWN_OFFER,
            'buy_box_price': box_price, 'buy_box_cause': None if box_price is not None else NO_BUY_BOX,
            'offers': offers, 'currency': currency}


def _summary_quote(response):
    """The Buy Box price from one getCompetitiveSummary item response."""
    status = ((response or {}).get('status') or {}).get('statusCode')
    body = (response or {}).get('body') or {}
    if status not in (None, 200):
        errors = body.get('errors') or []
        reason = str((errors[0] or {}).get('message') or '')[:160] if errors else ''
        return {'buy_box_price': None, 'currency': None,
                'buy_box_cause': f"Amazon refused the price read ({status}{': ' + reason if reason else ''})."}
    options = sorted(body.get('featuredBuyingOptions') or [],
                     key=lambda o: 0 if str((o or {}).get('buyingOptionType') or 'New') == 'New' else 1)
    offers = []
    for option in options:
        for offer in (option or {}).get('segmentedFeaturedOffers') or [option]:
            if not isinstance(offer, dict) or not {'sellerId', 'listingPrice'}.intersection(offer):
                continue
            price = _number(((offer or {}).get('listingPrice') or {}).get('amount'))
            offers.append({'sellerId': offer.get('sellerId'), 'price': price,
                           'shipping': _number((offer.get('shippingPrice') or {}).get('amount')),
                           'currency': (offer.get('listingPrice') or {}).get('currencyCode'),
                           'buyBox': True, 'mine': False, 'fba': None,
                           'condition': (option or {}).get('buyingOptionType') or 'New'})
    box = next((offer for offer in offers if offer['price'] is not None), None)
    return {'buy_box_price': box['price'] if box else None, 'buy_box_cause': None if box else NO_BUY_BOX,
            'currency': box['currency'] if box else None, 'offers': offers}


def _keyed(kind, got):
    if kind == 'facts':
        return {str(k).upper(): v for k, v in (got or {}).items()}
    if kind == 'offers':
        return {str((((r or {}).get('body') or {}).get('payload') or {}).get('ASIN') or '').upper(): r
                for r in got or ()}
    return {str(((r or {}).get('body') or {}).get('asin') or '').upper(): r for r in got or ()}


def _throttled(exc):
    return type(exc).__name__ == 'AmazonThrottled' or getattr(exc, 'status', None) == 429


def _backoff(exc, attempt):
    try:
        floor = float(getattr(exc, 'retry_after', None) or 0)
    except (TypeError, ValueError):
        floor = 0.0
    return min(MAX_BACKOFF_SECONDS, max(floor, BACKOFF_SECONDS * 2 ** attempt))


def _refused(kind, asins, exc, backoffs):
    """`{asin: cause}` for every ASIN of one refused batch. A cause never names a credential."""
    label = READS[kind]
    if _throttled(exc):
        cause = (f'Amazon throttled the {label} read (429) after {backoffs} backoffs. '
                 'The next daily run reads it again.')
    else:
        detail = re.sub('[' + chr(0x2013) + chr(0x2014) + ']', '.', str(exc))[:160].strip()
        cause = (f'Amazon refused the {label} read ({type(exc).__name__}{": " + detail if detail else ""}). '
                 'The next daily run reads it again.')
    return {a: cause for a in asins}


def _read_batches(kind, fn, asins, *, sleep, log, counts):
    """`(answers, causes)`: answers keyed by ASIN, and a cause on each ASIN of a refused batch."""
    answers, causes = {}, {}
    for part in _chunks(list(asins), READ_BATCH):
        attempt = 0
        while True:
            try:
                got = _keyed(kind, fn(part))
                answers.update(got)
                if kind == 'facts':
                    for target, fact in got.items():
                        if fact.get('cause'):
                            causes[target] = fact['cause']
                            if '(429)' in fact['cause']:
                                counts['throttled'] += 1
                            elif 'Amazon refused' in fact['cause']:
                                counts['refused'] += 1
                break
            except Exception as exc:                                   # noqa: BLE001
                if _throttled(exc) and attempt < THROTTLE_RETRIES:
                    wait = _backoff(exc, attempt)
                    attempt += 1
                    counts['backoffs'] += 1
                    log(f'{READS[kind]} read throttled (429), backing off {wait:.0f} s')
                    sleep(wait)
                    continue
                counts['throttled' if _throttled(exc) else 'refused'] += len(part)
                causes.update(_refused(kind, part, exc, attempt))
                break
    return answers, causes


def _quote_block(block, own, readers, seller_id, quote_on, run_id, sleep, log, counts,
                 prefetched=None, fact_causes=None):
    """One quote row per ASIN of `block`, each with a value or a cause for every field it owns."""
    mine = [a for a in block if a in own]
    others = [a for a in block if a not in own]
    offered, offer_causes = _read_batches('offers', readers['offers'], mine, sleep=sleep, log=log, counts=counts)
    summed, sum_causes = _read_batches('summaries', readers['summaries'], others, sleep=sleep, log=log,
                                       counts=counts)
    cached = prefetched or {}
    facts, rank_causes = _read_batches('facts', readers['facts'], [a for a in block if a not in cached],
                                     sleep=sleep, log=log, counts=counts)
    facts.update({a: cached[a] for a in block if a in cached})
    rank_causes.update(fact_causes or {})
    stamp = _now()
    rows = []
    for target in block:
        row = dict(asin=target, quote_on=quote_on, run_id=run_id, quoted_at=stamp, offer_price=None,
                   offer_cause=None, buy_box_price=None, buy_box_cause=None, offers=None, currency=None)
        if target in own:
            if target in offer_causes:
                row.update(offer_cause=offer_causes[target], buy_box_cause=offer_causes[target])
            elif target in offered:
                row.update(_offer_quote(offered[target], seller_id))
            else:
                row.update(offer_cause=NO_PRICE, buy_box_cause=NO_PRICE)
        elif target in sum_causes:
            row['buy_box_cause'] = sum_causes[target]
        elif target in summed:
            row.update(_summary_quote(summed[target]))
        else:
            row['buy_box_cause'] = NO_PRICE
        rank = facts.get(target) or {}
        value = rank.get('rank') if isinstance(rank.get('rank'), int) and not isinstance(rank.get('rank'), bool) else None
        row.update(sales_rank=value, display_group=rank.get('group') if value is not None else None,
                   rank_cause=None if value is not None else rank_causes.get(target) or NO_RANK)
        rows.append(row)
    return rows, [_snapshot(row, facts.get(row['asin']) or {}, row['asin'] in own) for row in rows]


def _snapshot(quote, facts, own):
    """C3 facts with price and rank taken from the exact persisted quote row."""
    return {**{key: facts.get(key) for key in ('product_type', 'brand', 'title', 'bullets',
                                              'image_variants', 'prime', 'offers', 'rank_cat', 'image')},
            'asin': quote['asin'], 'snapshot_date': quote['quote_on'],
            'price': quote['offer_price' if own else 'buy_box_price'], 'currency': quote['currency'],
            'sales_rank': quote['sales_rank'], 'display_group': quote['display_group']}


def _tally(counts, rows, own, snapshots):
    for row in rows:
        counts['priced'] += int((row['offer_price'] if row['asin'] in own else None) is not None
                                or row['buy_box_price'] is not None)
        counts['ranked'] += int(row['sales_rank'] is not None)
        counts['caused'] += int(bool(row['offer_cause'] or row['buy_box_cause'] or row['rank_cause']))
    for key, field in FACT_COUNT_COLUMNS.items():
        counts['facts'][key] += sum(row.get(field) is not None and row[field] != '' for row in snapshots)


def _changed(before, row):
    old = before.get(row['asin'])
    return old is None or any(old.get(k) != row.get(k) for k in QUOTED_FIELDS)


def _prepare_pools(rt, open_mirror, facts_reader, sleep, log, counts):
    with open_mirror() as cur:
        if cur is None:
            return None
        own = our_asins(cur)
        sources = _candidates(cur, sorted(own), newest_week(cur)) if own else []
        stored = _backend(rt).pool_rows(sorted(own))
        values = own | {r[1] for r in sources} | {r['rival_asin'] for r in stored if not r['removed']}
        known = _pool_facts(cur, values, own, candidate_rows=sources)
        missing = sorted(a for a in values if not known.product_type(a))
    prefetched, causes = _read_batches('facts', facts_reader, missing, sleep=sleep, log=log, counts=counts)
    prefetched = {a: prefetched.get(a, {}) for a in missing}
    with open_mirror() as cur:
        if cur is None:
            return None
        found = discover(rt, cur, candidate_rows=sources, prefetched=prefetched)
    return own, found, prefetched, causes


def run_quotes(rt, open_mirror, *, offers, summaries, facts, seller_id=None, run_id=None, now=None,
               log=None, sleep=time.sleep):
    """Discover, read unknown types outside the mirror, filter pools, then quote with cached facts."""
    _backend(rt)
    log = log or (lambda _message: None)
    now = now or datetime.now(timezone.utc)
    quote_on = now.date().isoformat()
    run_id = str(run_id or f'{quote_on}-{uuid.uuid4().hex[:8]}')
    counts = dict(ours=0, rivals=0, wanted=0, asins=0, priced=0, ranked=0, caused=0, refused=0, throttled=0,
                  backoffs=0, discovered=0, week=None, pools={}, facts=dict.fromkeys(FACT_COUNT_COLUMNS, 0))
    start_run(rt, run_id, asin_total=0)
    log(f'run {run_id} started')
    done = 0
    try:
        try:
            prepared = _prepare_pools(rt, open_mirror, facts, sleep, log, counts)
            if prepared is None:
                return _finish(rt, run_id, done, counts, NO_MIRROR, log)
            own, found, prefetched, fact_causes = prepared
        except MirrorUnreadable as exc:
            return _finish(rt, run_id, done, counts, f'The Amazon data could not be read ({exc}).', log)
        counts.update(discovered=found['rivals'], week=found['week'], pools=found['pools'])
        others = sorted(set(rival_asins(rt)) - own)
        extra = sorted(set(wanted(rt)) - own - set(others))
        targets = sorted(own) + others + extra
        counts.update(ours=len(own), rivals=len(others), wanted=len(extra), asins=len(targets))
        mark_run(rt, run_id, progress=0, counts=counts, asin_total=len(targets))
        log(f'run {run_id} quotes {len(targets)} ASINs: {len(own)} ours, {len(others)} rivals, '
            f'{len(extra)} wanted')
        before = newest_quotes(rt, targets) if targets else {}
        readers = {'offers': offers, 'summaries': summaries, 'facts': facts}
        changed, snapshots = list(found['changed']), []
        for block in _chunks(targets, PROGRESS_EVERY):
            rows, captured = _quote_block(block, own, readers, seller_id, quote_on, run_id, sleep, log, counts,
                                          prefetched, fact_causes)
            put_quotes(rt, rows)
            snapshots.extend(captured)
            _tally(counts, rows, own, captured)
            changed += [row['asin'] for row in rows if _changed(before, row)]
            done += len(block)
            mark_run(rt, run_id, progress=done, counts=counts)
            log(f'run {run_id} progress {done}/{len(targets)}')
        cause = (f'Amazon could not finish every read at its rate or refused a read. '
                 f'Retry the run within {RETRY_RUN_HOURS} hours after the rate limit delay.'
                 if counts['throttled'] or counts['refused'] else None)
        result = _finish(rt, run_id, done, counts, cause, log)
        result.update(changed=tuple(dict.fromkeys(changed)), snapshots=snapshots)
        return result
    except Exception as exc:
        mark_run(rt, run_id, progress=done, finished=True, counts=counts,
                 cause=f'The run stopped ({type(exc).__name__}). It runs again within {RETRY_RUN_HOURS} hours.')
        log(f'run {run_id} stopped ({type(exc).__name__}) after {done} ASINs')
        raise


def _finish(rt, run_id, done, counts, cause, log):
    mark_run(rt, run_id, progress=done, finished=True, counts=counts, cause=cause)
    log(f'run {run_id} finished: {counts["asins"]} ASINs, {counts["priced"]} priced, {counts["ranked"]} ranked, '
        f'{counts["caused"]} with a cause' + (f'. {cause}' if cause else ''))
    return {'id': run_id, 'progress': done, 'cause': cause, 'counts': dict(counts), 'changed': (), 'snapshots': []}


# --------------------------------------------------------------------------- competition status and rollups

WINNING, CONTESTED, LOSING = 'Winning', 'Contested', 'Losing'
STATUSES = (WINNING, CONTESTED, LOSING)
#: The pastel green, yellow and red of the grid's brand swatches.
STATUS_COLORS = {WINNING: '#A5D8B4', CONTESTED: '#F5D989', LOSING: '#F0A8A0'}
#: R42: the status compares this price of ours to the rivals' median, never the Buy Box price.
OUR_PRICE = 'offer_price'
#: A rival's price is its featured offer, read through getCompetitiveSummary.
RIVAL_PRICE = 'buy_box_price'
GRAINS = ('sku', 'asin', 'parent_asin')

#: (key, label, type, description, extra) of the SKU and ASIN row fields, in grid order.
ROW_COLUMNS = (
    ('competitors', 'Competitors', 'select', 'Our offer price and sales rank against the rivals.',
     {'options': list(STATUSES), 'optionColors': dict(STATUS_COLORS), 'colorCodeOptions': True}),
    ('competitors_cause', 'Competitors cause', 'text', 'Why the status is empty.', {}),
    ('rival_count', 'Rivals', 'int', 'Rivals of this ASIN.', {}),
    ('our_offer_price', 'Our offer price', 'currency', 'Our own offer price.', {}),
    ('buy_box_price', 'Buy Box price', 'currency', 'The Buy Box price on our listing.', {}),
    ('rival_median_price', 'Rival median price', 'currency', "The rivals' median price.", {}),
    ('our_sales_rank', 'Our sales rank', 'int', 'Our sales rank in our display group.', {}),
    ('rival_median_rank', 'Rival median rank', 'int', 'Median sales rank of rivals in our display group.', {}),
    ('rank_group', 'Rank group', 'text', 'The display group the ranks compare in.', {}),
)
#: R74: a Parent ASIN row carries only these rollups over its child ASINs.
PARENT_COLUMNS = (
    ('competitors_children', 'Children competitors', 'text', 'The worst child status, with the counts.', {}),
    ('children_winning', 'Children winning', 'int', 'Child ASINs that are Winning.', {}),
    ('children_contested', 'Children contested', 'int', 'Child ASINs that are Contested.', {}),
    ('children_losing', 'Children losing', 'int', 'Child ASINs that are Losing.', {}),
    ('children_median_offer_price', 'Children median offer price', 'currency',
     'Median of our offer prices over the child ASINs.', {}),
    ('children_rival_median_price', 'Children rival median price', 'currency',
     "Median of the child ASINs' rival median prices.", {}),
)
ROW_KEYS = tuple(c[0] for c in ROW_COLUMNS)
PARENT_KEYS = tuple(c[0] for c in PARENT_COLUMNS)
_KINDS = {c[0]: c[2] for c in ROW_COLUMNS + PARENT_COLUMNS}

NO_ASIN = 'This SKU has no ASIN in the listings.'
NO_QUOTE = 'No daily quote for this ASIN yet.'
NO_OFFER = 'We have no offer price on this ASIN.'
NO_RIVALS = 'No rival found for this ASIN.'
NO_RIVAL_PRICE = 'No rival has a price yet.'
NO_OWN_RANK = 'This ASIN has no sales rank yet.'
NO_GROUP_RIVAL = 'No rival has a sales rank in {group}.'


def _maybe_asin(value):
    text = str(value or '').strip().upper()
    return text if ASIN_RE.fullmatch(text) else None


def _one_line(text):
    return ' '.join(str(text).split())


def _median(values):
    return statistics.median(values) if values else None


def status_for(our_price, rival_price, our_rank, rival_rank):
    """R24: Winning when price and rank both beat the medians, Losing when both are worse."""
    price_better, price_worse = our_price <= rival_price, our_price > rival_price
    rank_better, rank_worse = our_rank < rival_rank, our_rank > rival_rank
    if price_better and rank_better:
        return WINNING
    if price_worse and rank_worse:
        return LOSING
    return CONTESTED


def worst_child(statuses):
    """The worst status among the children, None when no child has one."""
    present = set(statuses)
    return next((s for s in (LOSING, CONTESTED, WINNING) if s in present), None)


def _standing(target, ours, quotes, count, discovery_cause):
    our_price = _number((ours or {}).get(OUR_PRICE))
    our_rank = (ours or {}).get('sales_rank')
    group = (ours or {}).get('display_group') if our_rank is not None else None
    prices = [p for p in (_number((q or {}).get(RIVAL_PRICE)) for q in quotes) if p is not None]
    ranks = [q['sales_rank'] for q in quotes
             if q and q.get('sales_rank') is not None and group is not None and q.get('display_group') == group]
    median_price, median_rank = _median(prices), _median(ranks)
    if ours is None:
        cause = NO_QUOTE
    elif our_price is None:
        cause = ours.get('offer_cause') or NO_OFFER
    elif not count:
        cause = f'{NO_RIVALS[:-1]} ({discovery_cause}).' if discovery_cause else NO_RIVALS
    elif median_price is None:
        cause = NO_RIVAL_PRICE
    elif our_rank is None:
        cause = ours.get('rank_cause') or NO_OWN_RANK
    elif median_rank is None:
        cause = NO_GROUP_RIVAL.format(group=group or 'our display group')
    else:
        cause = None
    return {'asin': target, 'competitors': None if cause else status_for(our_price, median_price, our_rank,
                                                                          median_rank),
            'competitors_cause': _one_line(cause) if cause else None, 'rival_count': count,
            'our_offer_price': our_price, 'buy_box_price': _number((ours or {}).get('buy_box_price')),
            'rival_median_price': median_price, 'our_sales_rank': our_rank, 'rival_median_rank': median_rank,
            'rank_group': group, 'priced_rivals': len(prices), 'ranked_rivals': len(ranks),
            'quote_on': (ours or {}).get('quote_on')}


def standing(rt, asins):
    """`{asin: standing}`: our quote against the newest quote of each rival, the medians and the status.

    The status is empty with a one-line `competitors_cause` when our offer price, a priced rival, our
    rank or a ranked rival in our display group is missing (R24, R42)."""
    backend = _backend(rt)
    targets = sorted({a for a in map(_maybe_asin, asins) if a})
    if not targets:
        return {}
    listed = backend.rivals_of(targets)
    found = backend.discovery(targets)
    quotes = newest_quotes(rt, set(targets) | {r for rows in listed.values() for r in rows})
    return {t: _standing(t, quotes.get(t), [quotes.get(r) for r in listed.get(t, ())], len(listed.get(t, ())),
                         (found.get(t) or {}).get('cause'))
            for t in targets}


def rollup(children):
    """R74: a Parent ASIN's rollup over its children's standings, with no price, rank or status of its own."""
    statuses = [c.get('competitors') for c in children if c and c.get('competitors')]
    counts = {s: statuses.count(s) for s in STATUSES}
    worst = worst_child(statuses)
    unrated = sum(1 for c in children if not (c or {}).get('competitors'))
    parts = [f'{counts[s]} {s}' for s in STATUSES if counts[s]] + ([f'{unrated} with no status'] if unrated else [])
    offers = [c['our_offer_price'] for c in children if c and c.get('our_offer_price') is not None]
    medians = [c['rival_median_price'] for c in children if c and c.get('rival_median_price') is not None]
    return {'competitors_children': f'{worst} ({", ".join(parts)})' if worst else None,
            'children_winning': counts[WINNING], 'children_contested': counts[CONTESTED],
            'children_losing': counts[LOSING], 'children_median_offer_price': _median(offers),
            'children_rival_median_price': _median(medians), 'children': len(children)}


def _cell(key, value):
    """A raw value as the stored cell string of its field; None leaves the cell blank."""
    if value is None or value == '':
        return None
    kind = _KINDS[key]
    if kind == 'currency':
        return f'{float(value):.2f}'
    if kind == 'int':
        return str(int(round(float(value))))
    return str(value)


def row_cells(found):
    """SKU or ASIN row cells of one standing."""
    return {key: _cell(key, found.get(key)) for key in ROW_KEYS}


def parent_cells(found):
    """Parent ASIN row cells of one rollup."""
    return {key: _cell(key, found.get(key)) for key in PARENT_KEYS}


def family(asin_rows):
    """`{parent: [child ASIN]}` from ASIN rows' `asin` and `parent_asin` cells. An ASIN with no parent is its own."""
    out = {}
    for row in asin_rows.values():
        child = _maybe_asin(row.get('asin'))
        if child:
            out.setdefault(_maybe_asin(row.get('parent_asin')) or child, set()).add(child)
    return {parent: sorted(kids) for parent, kids in out.items()}


def affected(rt, changed):
    """Our ASINs whose standing moves when these ASINs' quotes change: each one, and each ASIN they are a rival of."""
    values = {a for a in map(_maybe_asin, changed or ()) if a}
    return values | _backend(rt).targets_of(sorted(values)) if values else set()


def cells(rt, tables, changed=None):
    """`{grain: {row_id: {field: cell}}}` for SKU, ASIN and Parent ASIN rows; `tables` maps grain to stored rows.

    With `changed` (the ASINs a quotes run changed) only the rows those ASINs move are returned."""
    sku_rows, asin_rows = tables.get('sku') or {}, tables.get('asin') or {}
    parent_rows = tables.get('parent_asin') or {}
    kids = family(asin_rows)
    hit = None if changed is None else affected(rt, changed)

    def wanted(asins):
        return hit is None or bool(set(asins) & hit)

    pick = {'sku': {rid: _maybe_asin(r.get('asin')) for rid, r in sku_rows.items()},
            'asin': {rid: _maybe_asin(r.get('asin')) for rid, r in asin_rows.items()}}
    pick = {g: {rid: a for rid, a in rows.items() if (a is None and hit is None) or (a and wanted([a]))}
            for g, rows in pick.items()}
    parents = {}
    for rid, row in parent_rows.items():
        parent = _maybe_asin(row.get('parent_asin'))
        if parent and wanted(kids.get(parent, ())):
            parents[rid] = kids.get(parent, [])
    needed = {a for rows in pick.values() for a in rows.values() if a} | {a for v in parents.values() for a in v}
    found = standing(rt, needed)
    out = {}
    for grain, rows in pick.items():
        out[grain] = {rid: row_cells(found.get(a) or ({'competitors_cause': NO_QUOTE} if a else
                                                      {'competitors_cause': NO_ASIN}))
                      for rid, a in rows.items()}
    out['parent_asin'] = {rid: parent_cells(rollup([found.get(a) for a in v])) for rid, v in parents.items()}
    return out


def _middle(values):
    ordered = sorted(values)
    if not ordered:
        return None
    half = len(ordered) // 2
    return ordered[half] if len(ordered) % 2 else (ordered[half - 1] + ordered[half]) / 2


def _differs(cell, value, tolerance):
    if cell is None or value is None:
        return (cell is None) != (value is None)
    return abs(float(cell) - float(value)) > tolerance


def validate(rt, tables, plan):
    """Recompute each rival median from the quote rows by its own query and tie it to the cells of `plan`.

    `plan` is what `cells` returned for `tables`. Returns checks `{check, ok, rows, mismatches}`."""
    asins = {g: {rid: _maybe_asin((tables.get(g) or {}).get(rid, {}).get('asin')) for rid in plan.get(g) or {}}
             for g in ('sku', 'asin')}
    kids = family(tables.get('asin') or {})
    parents = {rid: kids.get(_maybe_asin((tables.get('parent_asin') or {}).get(rid, {}).get('parent_asin')), [])
               for rid in plan.get('parent_asin') or {}}
    targets = sorted({a for rows in asins.values() for a in rows.values() if a}
                     | {a for v in parents.values() for a in v})
    own, rows = _backend(rt).median_inputs(targets) if targets else ({}, [])
    prices, ranks = {}, {}
    for target, price, rank, group in rows:
        if price is not None:
            prices.setdefault(target, []).append(float(price))
        if rank is not None and group is not None and group == own.get(target):
            ranks.setdefault(target, []).append(rank)
    price = {t: _middle(prices.get(t, ())) for t in targets}
    rank = {t: _middle(ranks.get(t, ())) for t in targets}
    bad = {'price': [], 'rank': [], 'parent': []}
    for grain, rows_ in asins.items():
        for rid, target in rows_.items():
            got = plan[grain][rid]
            if _differs(got.get('rival_median_price'), price.get(target), 0.006):
                bad['price'].append(f'{grain} {rid} {target}')
            if _differs(got.get('rival_median_rank'), rank.get(target), 0.5):
                bad['rank'].append(f'{grain} {rid} {target}')
    for rid, children_ in parents.items():
        want = _middle([price[c] for c in children_ if price.get(c) is not None])
        if _differs(plan['parent_asin'][rid].get('children_rival_median_price'), want, 0.006):
            bad['parent'].append(f'parent_asin {rid}')
    count = sum(len(v) for v in asins.values())
    return [{'check': 'rival median price ties to the quote rows', 'ok': not bad['price'], 'rows': count,
             'mismatches': bad['price']},
            {'check': 'rival median rank in our display group ties to the quote rows', 'ok': not bad['rank'],
             'rows': count, 'mismatches': bad['rank']},
            {'check': "a parent's rival median price ties to its children's", 'ok': not bad['parent'],
             'rows': len(parents), 'mismatches': bad['parent']}]


# --------------------------------------------------------------------------- pool validation

def _pool_expected(cur, targets):
    """Recompute raw click money independently of discovery's candidate and money queries."""
    required = {'asin', 'search_query_data_search_query', 'start_date', 'end_date',
                'purchase_data_total_purchase_count', 'purchase_data_total_median_purchase_price_amount'}
    clicks = {'search_term', 'clicked_asin', 'click_share', 'click_share_rank', '_period_start', '_period_end'}
    if not required <= _columns(cur, SQP_TABLE) or not clicks <= _columns(cur, BA_TABLE):
        return {}
    rows = _read(cur, f'''
        WITH monthly AS (
            SELECT upper(trim(CAST(asin AS VARCHAR))) AS owner,
                   lower(trim(CAST(search_query_data_search_query AS VARCHAR))) AS query,
                   TRY_CAST(end_date AS DATE) AS ends,
                   TRY_CAST(purchase_data_total_purchase_count AS DOUBLE) *
                   TRY_CAST(purchase_data_total_median_purchase_price_amount AS DOUBLE) AS money
            FROM {SQP_TABLE}
            WHERE TRY_CAST(end_date AS DATE) > TRY_CAST(start_date AS DATE) + INTERVAL '7 days'
              AND TRY_CAST(end_date AS DATE) < CURRENT_DATE),
        newest_month AS (SELECT owner, max(ends) AS ends FROM monthly GROUP BY owner),
        searches AS (
            SELECT m.owner, m.query, max(m.money) AS money FROM monthly m
            JOIN newest_month n ON n.owner = m.owner AND n.ends = m.ends
            GROUP BY m.owner, m.query HAVING max(m.money) > 0),
        report AS (
            SELECT lower(trim(CAST(search_term AS VARCHAR))) AS query,
                   upper(trim(CAST(clicked_asin AS VARCHAR))) AS rival,
                   TRY_CAST(click_share AS DOUBLE) AS share,
                   TRY_CAST(click_share_rank AS INTEGER) AS position, {_week_sql()} AS starts
            FROM {BA_TABLE} WHERE {weekly_period_sql()}),
        term_clicks AS (
            SELECT query, rival, max(share) AS share, min(position) AS position FROM report
            WHERE starts = (SELECT max(starts) FROM report) AND position BETWEEN 1 AND 3
            GROUP BY query, rival)
        SELECT s.owner, c.rival, sum(s.money * coalesce(c.share, 0) * 0.01),
               sum(CASE WHEN c.position = 1 THEN 1 ELSE 0 END)
        FROM searches s JOIN term_clicks c ON c.query = s.query
        WHERE s.owner IN {_in(targets)} GROUP BY s.owner, c.rival''', targets)
    return {(a, r): (float(m), int(n)) for a, r, m, n in rows}


def validate_pool(cur, rt, targets):
    """Tie stored auto-pool money and term wins to an independent raw-source aggregation."""
    targets = _asins(targets)
    expected = _pool_expected(cur, targets) if targets else {}
    bad_money, bad_terms, count = [], [], 0
    backend = _backend(rt)
    for target in targets:
        for row in backend.rivals(target):
            if row['source'] != 'auto':
                continue
            count += 1
            money, terms = expected.get((target, row['rival_asin']), (0, 0))
            label = f'{target} {row["rival_asin"]}'
            if _differs(row['money_won'], money, 0.000001):
                bad_money.append(label)
            if row['terms_won'] != terms:
                bad_terms.append(label)
    return [{'check': 'pool money won ties to Brand Analytics and search report rows',
             'ok': not bad_money, 'rows': count, 'mismatches': bad_money},
            {'check': 'pool terms won ties to Brand Analytics and search report rows',
             'ok': not bad_terms, 'rows': count, 'mismatches': bad_terms}]


# --------------------------------------------------------------------------- storage

def _ddl(table):
    return {
        RIVALS: f'''CREATE TABLE IF NOT EXISTS {table} (
            tenant TEXT NOT NULL, asin TEXT NOT NULL, rival_asin TEXT NOT NULL,
            source TEXT NOT NULL CHECK (source IN ('auto','added')),
            removed BOOLEAN NOT NULL, click_share DOUBLE PRECISION, term TEXT, title TEXT,
            week DATE, added_by TEXT, updated_at TEXT NOT NULL,
            PRIMARY KEY (tenant, asin, rival_asin))''',
        DISCOVERY: f'''CREATE TABLE IF NOT EXISTS {table} (
            tenant TEXT NOT NULL, asin TEXT NOT NULL, week DATE, discovered_at TEXT NOT NULL,
            cause TEXT, auto_count INTEGER NOT NULL, PRIMARY KEY (tenant, asin))''',
        QUOTES: f'''CREATE TABLE IF NOT EXISTS {table} (
            tenant TEXT NOT NULL, asin TEXT NOT NULL, quote_on DATE NOT NULL,
            offer_price DOUBLE PRECISION, buy_box_price DOUBLE PRECISION, sales_rank INTEGER,
            display_group TEXT, offer_cause TEXT, buy_box_cause TEXT, rank_cause TEXT, offers TEXT,
            currency TEXT, run_id TEXT, quoted_at TEXT NOT NULL, PRIMARY KEY (tenant, asin, quote_on))''',
        RUNS: f'''CREATE TABLE IF NOT EXISTS {table} (
            tenant TEXT NOT NULL, id TEXT NOT NULL, started_at TEXT NOT NULL, progress INTEGER NOT NULL,
            progress_at TEXT, finished_at TEXT, asin_total INTEGER NOT NULL, priced INTEGER,
            ranked INTEGER, caused INTEGER, cause TEXT, counts TEXT, PRIMARY KEY (tenant, id))''',
        WANTED: f'''CREATE TABLE IF NOT EXISTS {table} (
            tenant TEXT NOT NULL, asin TEXT NOT NULL, source TEXT NOT NULL, wanted_at TEXT NOT NULL,
            PRIMARY KEY (tenant, asin, source))''',
    }


def _chunks(values, size=CHUNK):
    for start in range(0, len(values), size):
        yield values[start:start + size]


def _marks(count):
    return ', '.join(['%s'] * count)


class PgRivalStore:
    """Guarded SQL storage in the schema of one explicit PgStore."""

    def __init__(self, bound):
        from core import store_pg
        if not isinstance(bound, store_pg.PgStore):
            raise TypeError('A bound PgStore is required.')
        self.tenant_slug = bound.tenant_slug
        self.schema = store_pg._schema_for(self.tenant_slug)
        if not re.fullmatch(r'[a-zA-Z0-9_]+', self.schema):
            raise ValueError('Invalid tenant schema.')

    def t(self, name):
        return f'"{self.schema}"."{name}"'

    @contextmanager
    def _connection(self):
        from core import store_pg
        store_pg._effective_slug(self.tenant_slug)
        with store_pg._pool().connection() as con:
            yield con

    def _write_guard(self):
        from core import store_pg
        store_pg.check_write(self.tenant_slug, 'write Amazon rivals')

    def _exists(self, con, name):
        return con.execute('SELECT to_regclass(%s)', (self.t(name),)).fetchone()[0] is not None

    def ensure_schema(self, con):
        """Create every rival table and index, only on a write."""
        for name in TABLES:
            con.execute(_ddl(self.t(name))[name])
        for name, fields in POOL_FIELDS.items():
            for column, (kind, default) in fields.items():
                con.execute(f'ALTER TABLE {self.t(name)} ADD COLUMN IF NOT EXISTS {column} {kind} '
                            f'DEFAULT {default}')
        con.execute(f'CREATE INDEX IF NOT EXISTS "amazon_rivals_rival" ON {self.t(RIVALS)} (tenant, rival_asin)')

    @contextmanager
    def _write(self):
        self._write_guard()
        with self._connection() as con:
            self.ensure_schema(con)
            yield con

    def _select(self, con, name, columns, where, args, order='', *, include_ineligible=False):
        if not self._exists(con, name):
            return []
        projection = columns
        fields = POOL_FIELDS.get(name, {})
        if fields.keys() & set(columns) or name == RIVALS:
            existing = {r[0] for r in con.execute(
                'SELECT column_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s',
                (self.schema, name)).fetchall()}
            projection = [f'{fields[c][1]} AS {c}' if c in fields and c not in existing else c for c in columns]
            if name == RIVALS and 'eligible' in existing and not include_ineligible:
                where = f'({where}) AND eligible = TRUE' if where else 'eligible = TRUE'
        rows = con.execute(f'SELECT {", ".join(projection)} FROM {self.t(name)} WHERE tenant = %s'
                           f'{" AND " + where if where else ""}{order}',
                           (self.tenant_slug, *args)).fetchall()
        return [dict(zip(columns, row)) for row in rows]

    @staticmethod
    def _rival(row):
        return {**row, 'removed': bool(row['removed']), 'eligible': bool(row['eligible']), 'week': _day(row['week']),
                'origin': 'added' if row['source'] == 'added' else row['origin'],
                'click_share': None if row['click_share'] is None else float(row['click_share'])}

    def pool_rows(self, targets):
        """Stored choices include hidden additions and removal tombstones."""
        with self._connection() as con:
            return [self._rival(row) for part in _chunks(list(targets)) for row in self._select(
                con, RIVALS, RIVAL_COLUMNS, f'asin IN ({_marks(len(part))})', part,
                include_ineligible=True)]

    def set_eligibility(self, rows, facts):
        with self._write() as con:
            for row in rows:
                if row['removed']:
                    continue
                target, rival = row['asin'], row['rival_asin']
                allowed = (facts.eligible(target, rival) if facts.product_type(target) else
                           row['eligible'] and rival not in facts.own_asins
                           and _other_brand(facts.latest.get(rival, {}).get('brand'), facts.own_brands))
                if allowed != row['eligible']:
                    con.execute(f'UPDATE {self.t(RIVALS)} SET eligible = %s '
                                'WHERE tenant = %s AND asin = %s AND rival_asin = %s',
                                (allowed, self.tenant_slug, target, rival))

    def replace_auto(self, targets, rows, discovery):
        with self._write() as con:
            for part in _chunks(targets):
                con.execute(f"DELETE FROM {self.t(RIVALS)} WHERE tenant = %s AND asin IN ({_marks(len(part))}) "
                            "AND source = 'auto' AND removed = %s", (self.tenant_slug, *part, False))
            cols = ('tenant',) + RIVAL_COLUMNS
            for part in _chunks(rows, 100):
                con.execute(f'INSERT INTO {self.t(RIVALS)} ({", ".join(cols)}) VALUES '
                            + ', '.join(f'({_marks(len(cols))})' for _ in part)
                            + ' ON CONFLICT (tenant, asin, rival_asin) DO NOTHING',
                            tuple(v for row in part for v in (self.tenant_slug, *(row[c] for c in RIVAL_COLUMNS))))
            cols = ('tenant',) + DISCOVERY_COLUMNS
            for part in _chunks(discovery, 100):
                con.execute(f'INSERT INTO {self.t(DISCOVERY)} ({", ".join(cols)}) VALUES '
                            + ', '.join(f'({_marks(len(cols))})' for _ in part)
                            + ' ON CONFLICT (tenant, asin) DO UPDATE SET week = excluded.week, '
                            'discovered_at = excluded.discovered_at, cause = excluded.cause, '
                            'auto_count = excluded.auto_count, month = excluded.month, '
                            'keyword_ranks_on = excluded.keyword_ranks_on, '
                            'product_type = excluded.product_type, held = excluded.held',
                            tuple(v for row in part for v in (self.tenant_slug, *(row[c] for c in DISCOVERY_COLUMNS))))

    def discovery(self, targets):
        with self._connection() as con:
            rows = []
            for part in _chunks(list(targets)):
                rows += self._select(con, DISCOVERY, DISCOVERY_COLUMNS, f'asin IN ({_marks(len(part))})', part)
        return {row['asin']: {**row, **{key: _day(row[key]) for key in
                                      ('week', 'month', 'keyword_ranks_on')}} for row in rows}

    def rivals(self, target):
        with self._connection() as con:
            rows = self._select(con, RIVALS, RIVAL_COLUMNS, 'asin = %s AND removed = %s', (target, False))
        averages = self.rank_averages([row['rival_asin'] for row in rows])
        enriched = [{**self._rival(row), **averages.get(row['rival_asin'],
                                                     {'rank_average': None, 'rank_days': 0})} for row in rows]
        return sorted(enriched, key=lambda row: (row['source'] != 'added', *_pool_order(row)))

    def rank_averages(self, values):
        out = {}
        with self._connection() as con:
            if not self._exists(con, QUOTES):
                return out
            for part in _chunks(values):
                rows = con.execute(f'''
                    WITH newest AS (
                        SELECT asin, max(quote_on) AS newest FROM {self.t(QUOTES)}
                        WHERE tenant = %s AND asin IN ({_marks(len(part))}) GROUP BY asin),
                    groups AS (
                        SELECT n.asin, n.newest, q.display_group FROM newest n
                        JOIN {self.t(QUOTES)} q ON q.asin = n.asin AND q.quote_on = n.newest
                        WHERE q.tenant = %s)
                    SELECT q.asin, CASE WHEN count(q.sales_rank) >= 7 THEN avg(q.sales_rank) END,
                           count(q.sales_rank)
                    FROM groups m JOIN {self.t(QUOTES)} q ON q.asin = m.asin
                      AND q.display_group = m.display_group AND q.quote_on >= m.newest - 29
                      AND q.quote_on <= m.newest
                    WHERE q.tenant = %s GROUP BY q.asin''',
                    (self.tenant_slug, *part, self.tenant_slug, self.tenant_slug)).fetchall()
                out.update({a: dict(rank_average=None if avg is None else float(avg), rank_days=n)
                            for a, avg, n in rows})
        return out

    def removed_count(self, target):
        with self._connection() as con:
            if not self._exists(con, RIVALS):
                return 0
            return con.execute(f'SELECT count(*) FROM {self.t(RIVALS)} WHERE tenant = %s AND asin = %s '
                               'AND removed = %s', (self.tenant_slug, target, True)).fetchone()[0]

    def add(self, row):
        cols = ('tenant',) + RIVAL_COLUMNS
        with self._write() as con:
            got = con.execute(f'INSERT INTO {self.t(RIVALS)} ({", ".join(cols)}) VALUES ({_marks(len(cols))}) '
                              "ON CONFLICT (tenant, asin, rival_asin) DO UPDATE SET source = 'added', "
                              "origin = 'added', money_won = 0, terms_won = 0, term_rank = NULL, "
                              'removed = excluded.removed, added_by = excluded.added_by, '
                              'updated_at = excluded.updated_at, '
                              'title = coalesce(excluded.title, title) '
                              f'RETURNING {", ".join(RIVAL_COLUMNS)}',
                              (self.tenant_slug, *(row[c] for c in RIVAL_COLUMNS))).fetchone()
            if not dict(zip(RIVAL_COLUMNS, got))['eligible']:
                con.execute(f'UPDATE {self.t(DISCOVERY)} SET week = NULL, month = NULL, keyword_ranks_on = NULL '
                            'WHERE tenant = %s AND asin = %s', (self.tenant_slug, row['asin']))
        return self._rival(dict(zip(RIVAL_COLUMNS, got)))

    def remove(self, target, rival, user, stamp):
        with self._write() as con:
            got = con.execute(f'UPDATE {self.t(RIVALS)} SET removed = %s, added_by = %s, updated_at = %s '
                              'WHERE tenant = %s AND asin = %s AND rival_asin = %s '
                              f'RETURNING {", ".join(RIVAL_COLUMNS)}',
                              (True, user, stamp, self.tenant_slug, target, rival)).fetchone()
        if got is None:
            raise KeyError('Rival not found.')
        return self._rival(dict(zip(RIVAL_COLUMNS, got)))

    def rivals_of(self, targets):
        """`{asin: [rival ASIN]}` of the rivals not removed."""
        out = {}
        with self._connection() as con:
            for part in _chunks(list(targets)):
                for row in self._select(con, RIVALS, ('asin', 'rival_asin'),
                                        f'asin IN ({_marks(len(part))}) AND removed = %s', (*part, False),
                                        ' ORDER BY asin, rival_asin'):
                    out.setdefault(row['asin'], []).append(row['rival_asin'])
        return out

    def targets_of(self, values):
        """Our ASINs that hold any of these ASINs as a rival not removed."""
        out = set()
        with self._connection() as con:
            for part in _chunks(list(values)):
                out |= {row['asin'] for row in self._select(
                    con, RIVALS, ('asin',), f'rival_asin IN ({_marks(len(part))}) AND removed = %s', (*part, False))}
        return out

    def median_inputs(self, targets):
        """`({asin: our display group}, [(asin, rival price, rival rank, rival group)])` from the newest quotes."""
        own, rows = {}, []
        newest = (f'q.quote_on = (SELECT max(n.quote_on) FROM {self.t(QUOTES)} AS n '
                  'WHERE n.tenant = q.tenant AND n.asin = q.asin)')
        with self._connection() as con:
            if not (self._exists(con, QUOTES) and self._exists(con, RIVALS)):
                return own, rows
            columns = {r[0] for r in con.execute(
                'SELECT column_name FROM information_schema.columns WHERE table_schema = %s AND table_name = %s',
                (self.schema, RIVALS)).fetchall()}
            eligibility = 'AND r.eligible = TRUE ' if 'eligible' in columns else ''
            for part in _chunks(list(targets)):
                marks = _marks(len(part))
                for target, rank, group in con.execute(
                        f'SELECT q.asin, q.sales_rank, q.display_group FROM {self.t(QUOTES)} AS q '
                        f'WHERE q.tenant = %s AND q.asin IN ({marks}) AND {newest}',
                        (self.tenant_slug, *part)).fetchall():
                    own[target] = group if rank is not None else None
                rows += [tuple(r) for r in con.execute(
                    f'SELECT r.asin, q.{RIVAL_PRICE}, q.sales_rank, q.display_group FROM {self.t(RIVALS)} AS r '
                    f'JOIN {self.t(QUOTES)} AS q ON q.tenant = r.tenant AND q.asin = r.rival_asin '
                    f'WHERE r.tenant = %s AND r.removed = %s {eligibility}'
                    f'AND r.asin IN ({marks}) AND {newest}',
                    (self.tenant_slug, False, *part)).fetchall()]
        return own, rows

    def rival_asins(self):
        with self._connection() as con:
            rows = self._select(con, RIVALS, ('DISTINCT rival_asin',), 'removed = %s', (False,),
                                ' ORDER BY rival_asin')
        return [row['DISTINCT rival_asin'] for row in rows]

    def want(self, values, source, stamp):
        cols = ('tenant',) + WANTED_COLUMNS
        with self._write() as con:
            for part in _chunks(values):
                con.execute(f'INSERT INTO {self.t(WANTED)} ({", ".join(cols)}) VALUES '
                            + ', '.join(f'({_marks(len(cols))})' for _ in part)
                            + ' ON CONFLICT (tenant, asin, source) DO NOTHING',
                            tuple(v for a in part for v in (self.tenant_slug, a, source, stamp)))
        return {'wanted': len(values)}

    def wanted(self, source):
        with self._connection() as con:
            rows = self._select(con, WANTED, ('DISTINCT asin',), 'source = %s' if source else '',
                                (source,) if source else (), ' ORDER BY asin')
        return [row['DISTINCT asin'] for row in rows]

    def put_quotes(self, rows):
        cols = ('tenant',) + QUOTE_COLUMNS
        update = ', '.join(f'{c} = excluded.{c}' for c in QUOTE_COLUMNS if c not in ('asin', 'quote_on'))
        with self._write() as con:
            for part in _chunks(rows, 100):
                con.execute(f'INSERT INTO {self.t(QUOTES)} ({", ".join(cols)}) VALUES '
                            + ', '.join(f'({_marks(len(cols))})' for _ in part)
                            + f' ON CONFLICT (tenant, asin, quote_on) DO UPDATE SET {update}',
                            tuple(v for row in part for v in (self.tenant_slug, *(row[c] for c in QUOTE_COLUMNS))))
        return {'quotes': len(rows)}

    def newest_quotes(self, values):
        out = {}
        cols = ', '.join(f'q.{c}' for c in QUOTE_COLUMNS)
        with self._connection() as con:
            if not self._exists(con, QUOTES):
                return out
            for part in _chunks(values):
                rows = con.execute(
                    f'SELECT {cols} FROM {self.t(QUOTES)} AS q JOIN ('
                    f'SELECT asin, max(quote_on) AS newest FROM {self.t(QUOTES)} '
                    f'WHERE tenant = %s AND asin IN ({_marks(len(part))}) GROUP BY asin) AS m '
                    'ON q.asin = m.asin AND q.quote_on = m.newest WHERE q.tenant = %s',
                    (self.tenant_slug, *part, self.tenant_slug)).fetchall()
                for row in rows:
                    item = dict(zip(QUOTE_COLUMNS, row))
                    item['quote_on'] = _day(item['quote_on'])
                    item['offers'] = json.loads(item['offers']) if item['offers'] else None
                    out[item['asin']] = item
        return out

    def start_run(self, run_id, total, stamp):
        with self._write() as con:
            con.execute(f'INSERT INTO {self.t(RUNS)} (tenant, id, started_at, progress, asin_total) '
                        'VALUES (%s, %s, %s, %s, %s)', (self.tenant_slug, run_id, stamp, 0, total))
        return {'id': run_id, 'started_at': stamp, 'asin_total': total}

    def mark_run(self, run_id, progress, stamp, finished, counts, cause, total=None):
        with self._write() as con:
            got = con.execute(
                f'UPDATE {self.t(RUNS)} SET progress = %s, progress_at = %s, finished_at = %s, '
                'priced = %s, ranked = %s, caused = %s, cause = %s, counts = %s, '
                'asin_total = coalesce(%s, asin_total) '
                'WHERE tenant = %s AND id = %s RETURNING id',
                (progress, stamp, stamp if finished else None, counts.get('priced'), counts.get('ranked'),
                 counts.get('caused'), cause, json.dumps(counts, sort_keys=True) if counts else None,
                 total, self.tenant_slug, run_id)).fetchone()
        if got is None:
            raise KeyError('Run not found.')
        return {'id': run_id, 'progress': progress, 'finished': finished}

    def runs(self, limit):
        with self._connection() as con:
            rows = self._select(con, RUNS, RUN_COLUMNS, '', (), f' ORDER BY started_at DESC, id LIMIT {int(limit)}')
        for row in rows:
            row['counts'] = json.loads(row['counts']) if row['counts'] else {}
        return rows