File size: 87,363 Bytes
9e15897
cf09724
 
 
 
7f72224
 
 
 
cf09724
b2aa446
 
 
cf09724
 
7f72224
cf09724
7f72224
 
cf09724
 
 
7f72224
9e15897
b2aa446
cf09724
b2aa446
cf09724
a97d6f1
 
cf09724
 
 
 
 
9e15897
cf09724
9e15897
cf09724
9e15897
cf09724
 
 
948168f
7f72224
 
 
 
82ff59c
 
7f72224
cf09724
 
 
 
 
7f72224
 
b2aa446
7f72224
b2aa446
7f72224
 
 
 
cf09724
 
 
 
b2aa446
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
7f72224
 
 
 
 
 
 
 
b2aa446
7f72224
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
b2aa446
 
 
7f72224
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f694a2b
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f694a2b
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
7f72224
b2aa446
7f72224
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
7f72224
 
b2aa446
 
 
 
7f72224
3e19b1e
 
 
 
 
 
b2aa446
 
7f72224
b2aa446
7f72224
b2aa446
 
7f72224
b2aa446
 
 
7f72224
b2aa446
 
7f72224
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
b2aa446
 
 
 
 
 
7f72224
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
948168f
 
 
 
7f72224
b2aa446
7f72224
 
 
 
 
 
cf09724
 
948168f
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
948168f
 
 
 
 
 
 
 
 
cf09724
948168f
cf09724
 
 
948168f
cf09724
 
 
948168f
 
cf09724
 
7f72224
 
82ff59c
 
 
 
 
7f72224
82ff59c
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ff59c
7f72224
 
 
3e19b1e
cf09724
 
 
 
3e19b1e
 
 
 
 
 
 
 
cf09724
 
 
3e19b1e
 
 
cf09724
7f72224
 
cf09724
 
 
7f72224
cf09724
9e15897
 
 
cf09724
9e15897
7f72224
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
cf09724
 
 
f694a2b
7f72224
 
 
f694a2b
7f72224
cf09724
f694a2b
cf09724
7f72224
f694a2b
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
f694a2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
7f72224
cf09724
f694a2b
7f72224
cf09724
 
 
 
 
 
 
7f72224
 
 
 
b2aa446
 
 
 
7f72224
cf09724
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f694a2b
 
b2aa446
f694a2b
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f694a2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
f694a2b
cf09724
b2aa446
 
 
 
 
 
 
 
 
 
f694a2b
 
b2aa446
 
f694a2b
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
b2aa446
7f72224
b2aa446
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
cf09724
 
 
 
7f72224
 
 
 
b2aa446
7f72224
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
cf09724
7f72224
cf09724
 
7f72224
cf09724
7f72224
cf09724
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
7f72224
b2aa446
cf09724
 
 
 
b2aa446
 
4f4f4bb
7f72224
 
4f4f4bb
 
7f72224
 
 
 
 
b2aa446
 
 
 
 
 
7f72224
 
 
 
 
82ff59c
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f4f4bb
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
cf09724
b2aa446
cf09724
b2aa446
 
 
 
 
 
cf09724
b2aa446
cf09724
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
9e15897
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
cf09724
b2aa446
9e15897
b2aa446
9e15897
 
 
b2aa446
 
9e15897
cf09724
 
 
9e15897
cf09724
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
82ff59c
 
 
 
 
 
f694a2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cf09724
 
 
7f72224
 
cf09724
b2aa446
cf09724
 
 
7f72224
 
b2aa446
 
 
cf09724
 
b2aa446
 
 
cf09724
b2aa446
f694a2b
cf09724
b2aa446
 
 
 
 
f694a2b
cf09724
 
 
 
f694a2b
b2aa446
 
 
 
cf09724
 
f694a2b
 
b2aa446
 
 
 
 
 
f694a2b
7f72224
cf09724
 
 
 
f694a2b
cf09724
b2aa446
 
cf09724
 
 
 
 
82ff59c
cf09724
 
 
 
 
f694a2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
b2aa446
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
7f72224
 
 
 
 
 
9e15897
 
7f72224
 
 
 
 
 
 
 
9e15897
 
7f72224
 
 
9e15897
7f72224
 
 
9e15897
 
 
 
7f72224
 
 
 
 
 
 
9e15897
 
7f72224
9e15897
7f72224
9e15897
 
7f72224
 
 
9e15897
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
7f72224
 
 
9e15897
 
7f72224
 
9e15897
 
cf09724
 
9e15897
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
7f72224
9e15897
 
cf09724
 
 
 
 
 
 
 
 
 
7f72224
cf09724
 
 
 
f694a2b
cf09724
 
 
f694a2b
7f72224
f694a2b
7f72224
 
cf09724
7f72224
f694a2b
7f72224
f694a2b
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
cf09724
b2aa446
cf09724
9e15897
 
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
b2aa446
9e15897
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
9e15897
 
 
 
b2aa446
 
9e15897
b2aa446
 
 
 
 
 
 
9e15897
 
b2aa446
9e15897
b2aa446
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
 
b2aa446
9e15897
b2aa446
9e15897
b2aa446
9e15897
b2aa446
9e15897
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
"""Competitor watch App: watched terms, weekly comparisons and owned seller alerts.

Store documents (tenant runtime store, App owned, never the mirror and never Amazon):
  competitor_watch_settings  {undercut_pct, rank_surge_pct, default_owner}
  competitor_watch_terms     {seeded: [...], added: [...], removed: [...], seeded_at}
  competitor_watch_alerts    legacy source, retained for explicit resumable migration
  competitor_watch_alert/<id> one alert per store row
  competitor_watch_check/<id> one check per store row
  competitor_watch_alerts_index migration checkpoint and serialized alert sequence
  competitor_watch_weeks     {last_compared, comparison: {...}, metrics: {period_start: {asin: metric}}}
  competitor_watch_terms_index {version: 2, activeTotal, trackingReady, trackingCause}, prepared by sync
  competitor_watch_terms SQL table (tenant, term, label, active, starred, ours)
  competitor_watch_term/<term> legacy rows, retained after one-time migration

Top 3 history is read from the connector table `amzn_brand_analytics`, which the store's weekly
retention keeps for watched terms. App documents never change the connector (rule 13).

Alerts and checks page in the tenant's existing Postgres store. No collection document or row cap
limits their growth. GET never prepares rows or reads the legacy collection.
"""
import contextlib
import datetime as dt
import json
import math
import re
from pathlib import Path
from urllib.parse import unquote_plus

from core.amazon_rivals import weekly_period_sql as _weekly_period_sql

TRIGGERS = {
    "new_asin": "New ASIN in top 3",
    "lost_spot": "Lost spot",
    "undercut": "Undercut",
    "rank_surge": "Rank surge",
    "own_asin_seller": "Seller on my ASIN",
}
STATUSES = ("Open", "Repriced", "Ads changed", "Listing improved", "Watching", "Ignore", "Reported to Amazon")
#: A key (term, asin, trigger) is held while its latest alert has one of these statuses.
HOLDING = ("Open", "Watching", "Ignore", "Reported to Amazon")
DEFAULTS = {"undercut_pct": 5.0, "rank_surge_pct": 50.0}
DUE_DAYS = 7
NOT_READY = "Comparison starts after the next weekly pull."
#: The mirror holds the tables but this read failed or was busy. `{cause}` is the error class.
READ_FAILED = ("The Amazon mirror could not be read ({cause}), so no search term was compared "
               "and the next Amazon sync will retry.")
BA_DATES_MISSING = "Brand Analytics report dates are missing"
BA_WEEKLY_MISSING = "Brand Analytics has no dated weekly reports"
#: Stored sync failures that a live probe finding a dated weekly report proves superseded.
SUPERSEDED_BY_WEEKLY = frozenset(READ_FAILED.format(cause=cause) for cause in (BA_DATES_MISSING, BA_WEEKLY_MISSING))
LIMIT = "Alerts and checks use separate store rows and server pages, with no row cap."

KEY_SETTINGS = "competitor_watch_settings"
KEY_TERMS = "competitor_watch_terms"
KEY_ALERTS = "competitor_watch_alerts"
KEY_WEEKS = "competitor_watch_weeks"
KEY_TERM_INDEX = "competitor_watch_terms_index"
TERM_PREFIX = "competitor_watch_term/"
TERM_TABLE = "competitor_watch_terms"
TERMS_NOT_READY = "Search terms are not ready. The next Amazon sync prepares term paging."
TRACKING_NOT_READY = "Tracked terms have no checked ownership source. The next Amazon sync will retry."
KEY_ALERT_INDEX = "competitor_watch_alerts_index"
ALERT_PREFIX = "competitor_watch_alert/"
CHECK_PREFIX = "competitor_watch_check/"
ALERTS_NOT_READY = "Alert paging is not ready. The next Amazon sync or an administrator must finish alert migration."

BA_TABLE = "amzn_brand_analytics"
SQP_TABLE = "amzn_search_query_performance"
LISTINGS_TABLE = "amzn_listings"
WAIT_QUOTES = "Waits for the daily price job"


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


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


def _norm(term):
    return " ".join(str(term or "").split()).lower()


def display_term(term):
    """Decode a label without changing the stored parent-record key."""
    return " ".join(unquote_plus(str(term or "")).split())


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


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


class TermsNotReady(RuntimeError):
    """Term paging has not been prepared by a completed sync."""

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


class AlertsNotReady(RuntimeError):
    """Alert rows are not ready for reads or edits."""


def _bound_store(tenant_key, st):
    backend = st._document_store() if hasattr(st, "_document_store") else st
    slug = getattr(backend, "tenant_slug", None)
    if slug is not None and slug != tenant_key:
        raise RuntimeError("The store handle belongs to another tenant.")
    return backend


def _paths(tenant_key, st, name, paths):
    backend = _bound_store(tenant_key, st)
    reader = getattr(backend, "get_json_paths", None)
    if callable(reader):
        key = st.store_key(name) if hasattr(st, "store_key") else name
        return reader(key, paths)
    doc = _doc(st, name)
    out = []
    for path in paths:
        value = doc
        for part in path:
            value = value.get(part) if isinstance(value, dict) else None
        out.append(value)
    return out


class _DocumentIndex:
    """Bind legacy document SQL to the caller's tenant."""

    def __init__(self, tenant_key, st):
        from core import store_pg
        self.pg, self.slug, self.st = store_pg, tenant_key, st
        self.key = st.store_key if hasattr(st, "store_key") else str
        self.prefix = self.key(TERM_PREFIX)

    def connection(self):
        self.pg._effective_slug(self.slug)
        return self.pg._pool().connection()

    def sql(self, statement):
        return self.pg._q(statement, "store_kv", self.slug)


class TermStoreFixture:
    """Explicit offline term-store adapter, never a production fallback."""


class _TermIndex(_DocumentIndex):
    """Indexed tenant term rows, prepared only by an explicit sync write."""

    def __init__(self, tenant_key, st):
        super().__init__(tenant_key, st)
        schema = self.pg._schema_for(self.slug)
        if not re.fullmatch(r"[a-zA-Z0-9_]+", schema):
            raise ValueError("Invalid tenant schema.")
        self.table = f'"{schema}"."{TERM_TABLE}"'

    def term_sql(self, statement):
        return statement.replace("{terms}", self.table)

    def ready(self):
        with self.connection() as con:
            row = con.execute(self.sql("SELECT value ->> 'version' FROM {tbl} WHERE key = %s"),
                              [self.key(KEY_TERM_INDEX)]).fetchone()
        return bool(row and row[0] == "2")

    def legacy_all(self):
        """Keep the wider pre-migration watched list readable by retention without migrating it."""
        with self.connection() as con:
            row = con.execute(self.sql("SELECT value ->> 'version' FROM {tbl} WHERE key = %s"),
                              [self.key(KEY_TERM_INDEX)]).fetchone()
            if not row or row[0] != "1":
                return None
            return [row[0] for row in con.execute(self.sql("SELECT value ->> 'term' FROM {tbl} "
                "WHERE starts_with(key, %s) AND (value ->> 'active') = 'true'"), [self.prefix]).fetchall()]

    def ensure_schema(self, con):
        con.execute(self.term_sql('CREATE TABLE IF NOT EXISTS {terms} ('
            'tenant TEXT NOT NULL, term TEXT COLLATE "C" NOT NULL, label TEXT NOT NULL, '
            'active BOOLEAN NOT NULL DEFAULT TRUE, starred BOOLEAN NOT NULL DEFAULT FALSE, '
            'ours BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (tenant, term))'))
        for suffix, columns in (("active", "tenant, active, term"),
                                ("starred", "tenant, starred, term"), ("ours", "tenant, ours, term"),
                                ("label", "tenant, active, label, term")):
            con.execute(self.term_sql(f'CREATE INDEX IF NOT EXISTS "cw_terms_{suffix}" '
                                      f'ON {{terms}} ({columns})'))
        con.execute(self.term_sql('CREATE INDEX IF NOT EXISTS "cw_terms_tracked_label" '
                                  'ON {terms} (tenant, label, term)'))

    def _put_meta(self, con, meta):
        con.execute(self.sql("INSERT INTO {tbl} (key, value) VALUES (%s, %s::jsonb) "
                            "ON CONFLICT (key) DO UPDATE SET value = excluded.value"),
                    [self.key(KEY_TERM_INDEX), json.dumps(meta)])

    @contextlib.contextmanager
    def _locked(self, *, prepare=False):
        self.pg.check_write(self.slug, "write competitor watch term rows")
        with self.connection() as con:
            con.execute("SET LOCAL lock_timeout = '10s'")
            con.execute("SET LOCAL statement_timeout = '30s'")
            if prepare:
                con.execute(self.sql("INSERT INTO {tbl} (key, value) VALUES (%s, %s::jsonb) "
                                     "ON CONFLICT (key) DO NOTHING"),
                            [self.key(KEY_TERM_INDEX), "{}"])
            row = con.execute(self.sql("SELECT value FROM {tbl} WHERE key = %s FOR UPDATE"),
                              [self.key(KEY_TERM_INDEX)]).fetchone()
            meta = json.loads(row[0]) if row and isinstance(row[0], str) else (row[0] if row else {})
            if not prepare and meta.get("version") != 2:
                raise TermsNotReady(TERMS_NOT_READY)
            if prepare:
                self.ensure_schema(con)
            yield con, meta
            meta["activeTotal"] = con.execute(self.term_sql(
                "SELECT COUNT(*) FROM {terms} WHERE tenant = %s AND active = TRUE"), [self.slug]).fetchone()[0]
            meta["version"] = 2
            self._put_meta(con, meta)

    def _insert(self, con, rows):
        statement = self.term_sql("INSERT INTO {terms} (tenant, term, label, active, starred) "
            "SELECT * FROM unnest(%s::text[], %s::text[], %s::text[], %s::boolean[], %s::boolean[]) "
            "ON CONFLICT (tenant, term) DO NOTHING")
        for start in range(0, len(rows), 1000):
            con.execute(statement, [list(values) for values in zip(*rows[start:start + 1000])])

    def seed(self, found, legacy, *, ours=None, tracking_error=None):
        with self._locked(prepare=True) as (con, meta):
            if meta.get("version") != 2:
                # Existing per-term rows override the older collection, including removals and stars.
                cursor = ""
                while True:
                    rows = con.execute(self.sql("SELECT key, value FROM {tbl} WHERE starts_with(key, %s) "
                        'AND key COLLATE "C" > %s ORDER BY key COLLATE "C" LIMIT 500'),
                        [self.prefix, cursor]).fetchall()
                    if not rows:
                        break
                    migrated = []
                    for key, value in rows:
                        value = json.loads(value) if isinstance(value, str) else value
                        term = _norm(value.get("term") or key[len(self.prefix):])
                        if term:
                            migrated.append((self.slug, term, display_term(term), value.get("active", True) is True,
                                             value.get("starred", False) is True))
                    self._insert(con, migrated)
                    cursor = rows[-1][0]
                removed = {_norm(t) for t in legacy.get("removed") or ()}
                terms = {_norm(t) for t in [*(legacy.get("seeded") or ()),
                                           *(legacy.get("added") or ()), *removed] if _norm(t)}
                self._insert(con, [(self.slug, t, display_term(t), t not in removed, False) for t in terms])
            self._insert(con, [(self.slug, t, display_term(t), True, False) for t in found if t])
            # Only a checked ownership result may replace membership, including a valid empty set.
            if ours is not None:
                self._insert(con, [(self.slug, t, display_term(t), True, False) for t in ours])
                con.execute(self.term_sql("UPDATE {terms} SET ours = (term = ANY(%s)) WHERE tenant = %s "
                    "AND ours IS DISTINCT FROM (term = ANY(%s))"), [list(ours), self.slug, list(ours)])
            if tracking_error:
                meta.update(trackingReady=False, trackingCause=tracking_error)
            elif ours is not None:
                meta.update(trackingReady=True, trackingCause=None)

    def edit(self, terms, *, active=None, starred=None):
        with self._locked() as (con, _meta):
            self._insert(con, [(self.slug, t, display_term(t), True, False) for t in terms])
            field, value = ("active", active) if active is not None else ("starred", starred)
            with con.cursor() as cur:
                cur.executemany(self.term_sql(f"UPDATE {{terms}} SET {field} = %s WHERE tenant = %s AND term = %s"),
                                [(value, self.slug, t) for t in terms])

    def page(self, search, offset, limit, selected, *, tracked=False, termOrder=None):
        if not self.ready():
            raise TermsNotReady(TERMS_NOT_READY)
        if termOrder not in (None, "asc", "desc"):
            raise ValueError("termOrder must be asc or desc.")
        if tracked:
            status = self.tracking_status()
            if not status["trackingReady"]:
                raise SourceNotReady(status["trackingCause"], page={
                    "terms": [], "term": None, "termTotal": None, "termOffset": 0,
                    "termLimit": limit, "termLabels": {}, "termFlags": {}, **status})
        membership = "(ours = TRUE OR starred = TRUE)" if tracked else "active = TRUE"
        order = "term" if termOrder is None else f"label {termOrder.upper()}, term {termOrder.upper()}"
        # Default pages read the transactional total and the active-term B-tree directly.
        total = (self.term_sql("SELECT count(*) FROM {terms} WHERE tenant = %s AND " + membership +
                              (" AND strpos(lower(label), %s) > 0" if search else "")) if search or tracked else
                 self.sql("SELECT (value ->> 'activeTotal')::bigint FROM {tbl} WHERE key = %s"))
        total_params = ([self.slug, *([display_term(search)] if search else [])]
                        if search or tracked else [self.key(KEY_TERM_INDEX)])
        tail = ("), "
            "bounds AS (SELECT total, CASE WHEN %s >= total THEN "
            "greatest(0, floor((total - 1)::numeric / %s)::bigint * %s) ELSE %s END AS skip FROM totals) "
            "SELECT total, skip, EXISTS(SELECT 1 FROM {terms} WHERE tenant = %s AND term = %s AND " + membership + "), "
            'ARRAY(SELECT term FROM {terms} WHERE tenant = %s AND ' + membership + ' '
            + ("AND strpos(lower(label), %s) > 0 " if search else "") +
            'ORDER BY ' + order + ' LIMIT %s OFFSET (SELECT skip FROM bounds)) '
            "FROM bounds")
        if isinstance(total, str):
            statement = self.term_sql("WITH totals(total) AS (" + total + tail)
        else:
            # PostgreSQL's `self.sql` returns a psycopg Composed: compose it, never concatenate it as text.
            from psycopg import sql as psql
            statement = psql.SQL("WITH totals(total) AS (") + total + psql.SQL(self.term_sql(tail))
        params = [*total_params, offset, limit, limit, offset, self.slug, selected, self.slug,
                  *([display_term(search)] if search else []), limit]
        with self.connection() as con:
            row = con.execute(statement, params).fetchone()
        total, start, held, terms = row
        picked = selected if held else next(iter(terms), None)
        flags = self.flags([*terms, *([picked] if picked else [])])
        return {"terms": list(terms), "term": selected if held else next(iter(terms), None),
                "termTotal": total, "termOffset": start, "termLimit": limit,
                "termLabels": {t: display_term(t) for t in flags}, "termFlags": flags,
                **self.tracking_status()}

    def tracking_status(self):
        """Read ownership readiness separately from the wider retention list's migration checkpoint."""
        with self.connection() as con:
            row = con.execute(self.sql("SELECT value ->> 'trackingReady', value ->> 'trackingCause' "
                                       "FROM {tbl} WHERE key = %s"), [self.key(KEY_TERM_INDEX)]).fetchone()
        ready = bool(row and row[0] == "true")
        cause = (row[1] if row else None) or TRACKING_NOT_READY
        return {"trackingReady": ready, "trackingCause": None if ready else cause}

    def require_tracking(self):
        status = self.tracking_status()
        if not status["trackingReady"]:
            raise SourceNotReady(status["trackingCause"])

    def flags(self, terms):
        if not terms:
            return {}
        with self.connection() as con:
            rows = con.execute(self.term_sql("SELECT term, ours, starred, active FROM {terms} "
                "WHERE tenant = %s AND term = ANY(%s)"), [self.slug, list(terms)]).fetchall()
        return {term: {"ours": ours, "starred": starred, "active": active} for term, ours, starred, active in rows}

    def count(self, *, tracked=False):
        if not self.ready():
            raise TermsNotReady(TERMS_NOT_READY)
        if tracked:
            self.require_tracking()
        with self.connection() as con:
            return con.execute(self.term_sql("SELECT COUNT(*) FROM {terms} WHERE tenant = %s AND " +
                ("(ours = TRUE OR starred = TRUE)" if tracked else "active = TRUE")), [self.slug]).fetchone()[0]

    def all(self, *, tracked=False):
        if not self.ready():
            raise TermsNotReady(TERMS_NOT_READY)
        with self.connection() as con:
            return [r[0] for r in con.execute(self.term_sql('SELECT term FROM {terms} WHERE tenant = %s AND '
                + ('(ours = TRUE OR starred = TRUE)' if tracked else 'active = TRUE') + ' ORDER BY term'),
                [self.slug]).fetchall()]


def _term_index(tenant_key, st):
    from core.store_pg import PgStore
    bound = _bound_store(tenant_key, st)
    if getattr(st, "key", tenant_key) != tenant_key or getattr(st, "store_namespace", ""):
        raise RuntimeError("The store handle belongs to another tenant.")
    if isinstance(bound, TermStoreFixture):
        return bound.term_store
    return _TermIndex(tenant_key, st) if isinstance(bound, PgStore) else None


def _term_sql(column):
    return f"lower(trim(regexp_replace(coalesce({column}, ''), '\\s+', ' ', 'g')))"


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

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


class _ReadFailed(Exception):
    """A mirror read failed, was locked or busy. Never read as an absent table."""


class SourceNotReady(_ReadFailed):
    """A required source cannot support a checked weekly result."""

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


@contextlib.contextmanager
def _reader(tenant_key, st):
    """A read-only cursor on the tenant mirror, None when the mirror file does not exist.

    An open failure raises `_ReadFailed` naming its error class."""
    path = Path(_mirror_path(tenant_key, st))
    if not path.exists():
        yield None
        return
    from harness import datastore
    try:
        shared = Path(datastore.DB_PATH).resolve() == path.resolve()
    except Exception:                                                  # noqa: BLE001
        shared = False
    # The process holds one writer on its own mirror: a separate read-only connect would refuse.
    try:
        if shared:
            cur = datastore.ro_cursor()
        else:
            import duckdb
            cur = duckdb.connect(str(path), read_only=True)
    except Exception as exc:                                           # noqa: BLE001
        raise _ReadFailed(type(exc).__name__) from exc
    try:
        yield cur
    finally:
        cur.close()


def _columns(cur, table):
    """The table's column names, an empty set when it is absent. A failed read raises `_ReadFailed`."""
    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 _ReadFailed(type(exc).__name__) from exc


def _ba_columns(cur):
    """Check weekly readiness with metadata and scalar existence checks, without loading source rows."""
    return _ba_source(cur)[0]


def _ba_source(cur):
    """The Brand Analytics columns and whether a dated weekly report exists. Unready sources raise."""
    cols = _columns(cur, BA_TABLE) if cur is not None else set()
    weekly = False
    if cols and not {"_period_start", "_period_end"} <= cols:
        try:
            populated = cur.execute(f"SELECT EXISTS(SELECT 1 FROM {BA_TABLE})").fetchone()[0]
        except Exception as exc:                                       # noqa: BLE001
            raise _ReadFailed(type(exc).__name__) from exc
        if populated:
            raise SourceNotReady(BA_DATES_MISSING)
    elif {"_period_start", "_period_end"} <= cols:
        try:
            populated, weekly = cur.execute(
                f"SELECT EXISTS(SELECT 1 FROM {BA_TABLE}), "
                f"EXISTS(SELECT 1 FROM {BA_TABLE} WHERE {_weekly_period_sql()})").fetchone()
        except Exception as exc:                                       # noqa: BLE001
            raise _ReadFailed(type(exc).__name__) from exc
        if populated and not weekly:
            raise SourceNotReady(BA_WEEKLY_MISSING)
    return cols, bool(weekly)


def _sqp(cur, term=None):
    """Monthly SQP rows as (term, asin, impressions, end_date) for our ASINs."""
    need = {"search_query_data_search_query", "asin"}
    cols = _columns(cur, SQP_TABLE) if cur is not None else set()
    if not need <= cols:
        return []
    if "_report_period" in cols:
        period = '"_report_period" = \'MONTH\''
    elif {"start_date", "end_date"} <= cols:
        start = 'TRY_CAST("start_date" AS DATE)'
        end_date = 'TRY_CAST("end_date" AS DATE)'
        period = f'day({start}) = 1 AND {end_date} = last_day({start})'
    else:
        return []
    imp = ('TRY_CAST("impression_data_asin_impression_count" AS DOUBLE)'
           if "impression_data_asin_impression_count" in cols else "0")
    end = 'CAST("end_date" AS VARCHAR)' if "end_date" in cols else "''"
    where = f" WHERE {period}"
    if term is not None:
        where += f' AND {_term_sql("search_query_data_search_query")} = ?'
    rows = cur.execute(
        f'SELECT "search_query_data_search_query", "asin", {imp}, {end} FROM {SQP_TABLE}{where}',
        [term] if term is not None else []).fetchall()
    return [(_norm(t), str(a or "").strip(), float(i or 0), str(e or "")) for t, a, i, e in rows if _norm(t)]


def _our_asins(cur, sqp_rows, candidates=None):
    ours = {a for _t, a, _i, _e in sqp_rows if a}
    if cur is not None and candidates != set() and "asin" in _columns(cur, SQP_TABLE):
        wanted = sorted(candidates) if candidates is not None else None
        where = ' AND trim("asin") IN (' + ','.join('?' for _ in wanted) + ')' if wanted is not None else ''
        ours |= {str(r[0]).strip() for r in cur.execute(
            f'SELECT DISTINCT "asin" FROM {SQP_TABLE} WHERE "asin" IS NOT NULL{where}', wanted or []).fetchall()}
    if cur is not None and candidates != set() and "asin1" in _columns(cur, LISTINGS_TABLE):
        wanted = sorted(candidates) if candidates is not None else None
        where = ' AND trim("asin1") IN (' + ','.join('?' for _ in wanted) + ')' if wanted is not None else ''
        ours |= {str(r[0]).strip() for r in cur.execute(
            f'SELECT DISTINCT "asin1" FROM {LISTINGS_TABLE} WHERE "asin1" IS NOT NULL{where}',
            wanted or []).fetchall()}
    return {a for a in ours if a}


def _our_asin_for(term, sqp_rows):
    """R23: our ASIN with the most impressions on the term, in the term's newest SQP period."""
    rows = [r for r in sqp_rows if r[0] == term and r[1]]
    if not rows:
        return None
    newest = max(r[3] for r in rows)
    totals = {}
    for _t, asin, imp, end in rows:
        if end == newest:
            totals[asin] = totals.get(asin, 0.0) + imp
    return max(sorted(totals), key=lambda a: totals[a])


def _top3(cur, terms=None):
    """{term: {period_start: {"end": str, "rows": {asin: (rank, click_share, conversion_share)}}}}."""
    cols = _ba_columns(cur)
    if not {"search_term", "clicked_asin", "click_share_rank", "_period_start", "_period_end"} <= cols:
        return {}
    cs = 'TRY_CAST("click_share" AS DOUBLE)' if "click_share" in cols else "NULL"
    cv = 'TRY_CAST("conversion_share" AS DOUBLE)' if "conversion_share" in cols else "NULL"
    pe = 'CAST(TRY_CAST("_period_end" AS DATE) AS VARCHAR)'
    wanted = None if terms is None else sorted({_norm(t) for t in terms})
    if wanted == []:
        return {}
    where = (f' AND {_term_sql("search_term")} IN (SELECT unnest(?::VARCHAR[]))'
             if wanted is not None else '')
    rows = cur.execute(
        f'SELECT "search_term", CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR), {pe}, "clicked_asin", '
        f'TRY_CAST("click_share_rank" AS INTEGER), {cs}, {cv} FROM {BA_TABLE} '
        f'WHERE TRY_CAST("click_share_rank" AS INTEGER) BETWEEN 1 AND 3 '
        f'AND ({_weekly_period_sql()}){where}', [wanted] if wanted is not None else []).fetchall()
    return _ranked_history(rows, wanted)


def _ranked_history(rows, wanted=None):
    out = {}
    for term, start, end, asin, rank, share, conv in rows:
        key = _norm(term)
        if wanted is not None and key not in wanted or not asin:
            continue
        week = out.setdefault(key, {}).setdefault(str(start), {"end": str(end or ""), "rows": {}})
        week["rows"][str(asin).strip()] = (int(rank), share, conv)
    return out


def _page_history(cur, terms, selected):
    """Read page week counts and the selected term's ranks in one source scan."""
    cols = _ba_columns(cur)
    wanted = sorted(set(terms) | ({selected} if selected else set()))
    if not wanted or not {"search_term", "_period_start", "_period_end"} <= cols:
        return {}, {}
    optional = {name: f'TRY_CAST("{name}" AS {kind})' if name in cols else f'NULL::{kind}'
                for name, kind in (("clicked_asin", "VARCHAR"), ("click_share_rank", "INTEGER"),
                                   ("click_share", "DOUBLE"), ("conversion_share", "DOUBLE"))}
    query = (f'WITH held AS MATERIALIZED (SELECT {_term_sql("search_term")} AS term, '
        'CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR) AS start, '
        'CAST(TRY_CAST("_period_end" AS DATE) AS VARCHAR) AS stop, '
        + ', '.join(f'{expr} AS "{name}"' for name, expr in optional.items()) +
        f' FROM {BA_TABLE} WHERE {_weekly_period_sql()} '
        f'AND {_term_sql("search_term")} IN (SELECT unnest(?::VARCHAR[]))) '
        'SELECT term, COUNT(DISTINCT start) AS weeks, NULL AS start, NULL AS stop, '
        'NULL AS asin, NULL::INTEGER AS rank, NULL::DOUBLE AS share, NULL::DOUBLE AS conversion '
        'FROM held GROUP BY term UNION ALL '
        'SELECT term, NULL, start, stop, clicked_asin, click_share_rank, click_share, conversion_share '
        'FROM held WHERE term = ? AND click_share_rank BETWEEN 1 AND 3')
    rows = cur.execute(query, [wanted, selected]).fetchall()
    counts = {term: weeks for term, weeks, *_rest in rows if weeks is not None}
    history = _ranked_history([(term, *values) for term, weeks, *values in rows if weeks is None])
    return counts, history.get(selected, {})


def term_page_history(tenant_key, page, *, st=None):
    """Share the page's weekly scan with selected-term detail without preparing stored state."""
    st = _rt(tenant_key, st)
    selected = page["term"]
    if not page["terms"] and not selected:
        return {}, {}
    try:
        with _reader(tenant_key, st) as cur:
            counts, history = _page_history(cur, page["terms"], selected)
            detail = term_detail(tenant_key, selected, st=st, reader=cur, history=history) if selected else {}
    except Exception as exc:
        cause = str(exc) if isinstance(exc, _ReadFailed) else type(exc).__name__
        raise SourceNotReady(cause, page=page) from exc
    return counts, detail


def _periods(cur):
    if not {"_period_start", "_period_end"} <= _ba_columns(cur):
        return []
    rows = cur.execute(f'SELECT DISTINCT CAST(TRY_CAST("_period_start" AS DATE) AS VARCHAR) FROM {BA_TABLE} '
                       f'WHERE {_weekly_period_sql()}').fetchall()
    return sorted((str(r[0]) for r in rows if r[0] is not None), reverse=True)


# --------------------------------------------------------------------------- watched terms

def watched_terms(tenant_key, *, st=None):
    """Seeded SQP terms plus terms a person added, minus terms a person removed (store only)."""
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)
    if index is not None and index.ready():
        return index.all()
    if index is not None:
        legacy = index.legacy_all()
        if legacy is not None:
            return legacy
    doc = _doc(st, KEY_TERMS)
    removed = {_norm(t) for t in doc.get("removed") or ()}
    terms = {_norm(t) for t in [*(doc.get("seeded") or ()), *(doc.get("added") or ())]}
    return sorted(t for t in terms if t and t not in removed)


def tracked_terms(tenant_key, *, st=None):
    """Read last known newest-week membership plus current stars, even during an ownership-source failure."""
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)
    if index is None:
        raise TermsNotReady(TERMS_NOT_READY)
    return index.all(tracked=True)


def tracked_count(tenant_key, *, st=None):
    """Count the tracked subset in SQL, raising SourceNotReady when its ownership source is unchecked."""
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)
    if index is None:
        raise TermsNotReady(TERMS_NOT_READY)
    return index.count(tracked=True)


def _brand_source_sql(cur):
    """Share one dated BA/listings join between membership and bulk click-share readers."""
    need = {"search_term", "clicked_asin", "click_share_rank", "_period_start", "_period_end"}
    cols, weekly = _ba_source(cur)
    if cur is None or not need <= cols or "asin1" not in _columns(cur, LISTINGS_TABLE):
        raise SourceNotReady("Tracked terms need dated Brand Analytics and listing ASINs.")
    if not weekly:
        raise SourceNotReady(BA_WEEKLY_MISSING)
    return (f"WITH weekly AS (SELECT * FROM {BA_TABLE} WHERE {_weekly_period_sql()}), "
            f"own_asins AS (SELECT DISTINCT trim(asin1) AS asin FROM {LISTINGS_TABLE} "
            "WHERE asin1 IS NOT NULL AND trim(asin1) <> ''), "
            "own_clicks AS (SELECT b.* FROM weekly b JOIN own_asins o ON trim(b.clicked_asin) = o.asin "
            "WHERE TRY_CAST(b.click_share_rank AS INTEGER) BETWEEN 1 AND 3) ")


def _tracked_terms_source(cur):
    query = _brand_source_sql(cur)
    return {row[0] for row in cur.execute(query +
        f'SELECT DISTINCT {_term_sql("search_term")} FROM own_clicks '
        'WHERE TRY_CAST(_period_start AS TIMESTAMP) = '
        '(SELECT MAX(TRY_CAST(_period_start AS TIMESTAMP)) FROM weekly) '
        f'AND {_term_sql("search_term")} <> \'\'').fetchall()}


def brand_share_source(cur, terms, start=None, end=None):
    """Yield bulk (stored term, week start, week end, own click share) for a caller's selected terms."""
    query = _brand_source_sql(cur)
    if "click_share" not in _columns(cur, BA_TABLE):
        raise SourceNotReady("Own-brand click share needs Brand Analytics click shares.")
    wanted = sorted({_norm(term) for term in terms})
    if not wanted:
        return
    rows = cur.execute(query +
        f'SELECT {_term_sql("search_term")} AS term, CAST(_period_start AS DATE), '
        'CAST(_period_end AS DATE), SUM(TRY_CAST(click_share AS DOUBLE)) FROM own_clicks '
        f'WHERE {_term_sql("search_term")} IN (SELECT unnest(?)) '
        'AND (? IS NULL OR CAST(_period_start AS DATE) >= CAST(? AS DATE)) '
        'AND (? IS NULL OR CAST(_period_end AS DATE) <= CAST(? AS DATE)) '
        'GROUP BY 1, 2, 3 ORDER BY 1, 2, 3', [wanted, start, start, end, end])
    while batch := rows.fetchmany(500):
        yield from batch


def _discover_terms(reader):
    """Union the two source vocabularies without treating SQP coverage as BA membership."""
    if reader is None:
        raise TermsNotReady(TERMS_NOT_READY)
    sources = []
    if "search_query_data_search_query" in _columns(reader, SQP_TABLE):
        sources.append(f'SELECT {_term_sql("search_query_data_search_query")} AS term FROM {SQP_TABLE}')
    if {"search_term", "_period_start", "_period_end"} <= _columns(reader, BA_TABLE):
        sources.append(f'SELECT {_term_sql("search_term")} AS term FROM {BA_TABLE} WHERE {_weekly_period_sql()}')
    if not sources:
        raise TermsNotReady(TERMS_NOT_READY)
    return {row[0] for row in reader.execute(
        'SELECT DISTINCT term FROM (' + ' UNION ALL '.join(sources) + ") WHERE term <> ''").fetchall()}


def seed_terms(tenant_key, *, st=None, cur=None):
    """Discover SQP queries and held weekly BA terms while preserving authored membership."""
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)

    def failure_cause(exc):
        if isinstance(exc, SourceNotReady):
            return str(exc)
        cause = str(exc) if isinstance(exc, _ReadFailed) else type(exc).__name__
        return f"Tracked terms could not be checked ({cause}). The next Amazon sync will retry."

    def source(reader):
        try:
            found = _discover_terms(reader)
        except Exception as exc:
            if index is None:
                raise
            return set(), None, failure_cause(exc)
        try:
            ours = _tracked_terms_source(reader)
        except Exception as exc:                                       # noqa: BLE001
            return found, None, failure_cause(exc)
        return found, ours, None

    if cur is None:
        try:
            with _reader(tenant_key, st) as reader:
                found, ours, tracking_error = source(reader)
        except _ReadFailed as exc:
            if index is None:
                raise
            found, ours, tracking_error = set(), None, failure_cause(exc)
    else:
        found, ours, tracking_error = source(cur)
    if index is not None:
        index.seed(found, _doc(st, KEY_TERMS) if not index.ready() else {}, ours=ours,
                   tracking_error=tracking_error)
        return index.all()

    def _seed(doc):
        doc = doc if isinstance(doc, dict) else {}
        seeded = set(doc.get("seeded") or ()) | found
        doc["seeded"] = sorted(seeded)
        doc.setdefault("added", [])
        doc.setdefault("removed", [])
        doc["seeded_at"] = _stamp(_now())
        return doc
    st.update(KEY_TERMS, _seed)
    return watched_terms(tenant_key, st=st)


def _edit_terms(tenant_key, terms, add, st, page_only=False):
    clean = sorted({_norm(t) for t in terms or () if _norm(t)})
    if not clean:
        raise ValueError("Name at least one search term.")
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)
    if index is not None:
        if not index.ready():
            raise TermsNotReady(TERMS_NOT_READY)
        index.edit(clean, active=add)
        return clean if page_only else index.all()
    if page_only:
        raise TermsNotReady(TERMS_NOT_READY)

    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        added, removed = set(doc.get("added") or ()), set(doc.get("removed") or ())
        if add:
            added |= set(clean)
            removed -= set(clean)
        else:
            removed |= set(clean)
            added -= set(clean)
        doc.setdefault("seeded", [])
        doc["added"], doc["removed"] = sorted(added), sorted(removed)
        return doc
    st.update(KEY_TERMS, _apply)
    return watched_terms(tenant_key, st=st)


def add_terms(tenant_key, terms, *, st=None, page_only=False):
    """Watch these terms. A term a person removed before comes back."""
    return _edit_terms(tenant_key, terms, True, st, page_only)


def remove_terms(tenant_key, terms, *, st=None, page_only=False):
    """Stop watching these terms. A later SQP seed does not bring them back."""
    return _edit_terms(tenant_key, terms, False, st, page_only)


def star_term(tenant_key, term, starred, *, st=None):
    """Merge a star into one authored row without changing its key or active flag."""
    key = _norm(term)
    if not key or type(starred) is not bool:
        raise ValueError("Name a term and a boolean starred value.")
    st = _rt(tenant_key, st)
    index = _term_index(tenant_key, st)
    if index is None or not index.ready():
        raise TermsNotReady(TERMS_NOT_READY)
    index.edit([key], starred=starred)
    return {"term": key, "termLabel": display_term(key), **index.flags([key])[key]}


def terms_summary(tenant_key, *, st=None):
    """Every watched term with its source, newest held period and open alert count. No cap."""
    st = _rt(tenant_key, st)
    doc = _doc(st, KEY_TERMS)
    seeded = {_norm(t) for t in doc.get("seeded") or ()}
    terms = watched_terms(tenant_key, st=st)
    with _reader(tenant_key, st) as cur:
        held = _top3(cur, terms)
    open_counts = _alert_index(tenant_key, st).open_counts()
    return {"terms": [{"term": t, "termLabel": display_term(t), "source": "seeded" if t in seeded else "added",
                       "newestPeriod": max(held.get(t, {}), default=None),
                       "openAlerts": open_counts.get(t, 0)} for t in terms]}


def term_page(tenant_key, *, st=None, search="", offset=0, limit=50, selected=None, tracked=False, termOrder=None):
    """Page watched or tracked terms without materializing the vocabulary or comparing every term."""
    st = _rt(tenant_key, st)
    error, = _paths(tenant_key, st, KEY_WEEKS, [("last_error",)])
    problems = [str(error)] if error else []
    size = max(1, min(int(limit), 100))
    start = max(0, int(offset))
    page_error = None
    try:
        index = _term_index(tenant_key, st)
        if index is None:
            raise TermsNotReady("Search term paging needs the tenant store migration. Ask an administrator to finish it.")
        controls = {}
        if tracked:
            controls["tracked"] = tracked
        if termOrder is not None:
            controls["termOrder"] = termOrder
        page = index.page(_norm(search), start, size, _norm(selected), **controls)
    except TermsNotReady as exc:
        page_error = exc
    source_error = None
    try:
        with _reader(tenant_key, st) as cur:
            weekly = _ba_source(cur)[1]
        if weekly:
            problems = [problem for problem in problems if problem not in SUPERSEDED_BY_WEEKLY]
    except SourceNotReady as exc:
        source_error = exc
        cause = READ_FAILED.format(cause=exc)
        if cause not in problems:
            problems.append(cause)
    except _ReadFailed as exc:
        cause = READ_FAILED.format(cause=exc)
        if cause not in problems:
            problems.append(cause)
    if page_error is not None:
        raise TermsNotReady(str(page_error), problems=problems) from page_error
    page = {**page, "problems": problems}
    if source_error is not None:
        raise SourceNotReady(str(source_error), page=page) from source_error
    return page


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

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


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


def owner_account(st, tenant_key=None):
    """R31: the tenant's earliest active person Administrator by display name, as money-losers use.

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


def settings(tenant_key, *, st=None):
    """Thresholds and the default owner, with defaults filled in."""
    st = _rt(tenant_key, st)
    doc = _doc(st, KEY_SETTINGS)
    out = {k: float(doc.get(k, v)) for k, v in DEFAULTS.items()}
    out["defaultOwnerSetting"] = doc.get("default_owner") or None
    out["defaultOwner"] = out["defaultOwnerSetting"] or owner_account(st, tenant_key)
    out["statuses"] = list(STATUSES)
    out["limit"] = LIMIT
    return out


def set_settings(tenant_key, *, undercut_pct=None, rank_surge_pct=None, default_owner=None, st=None):
    """Set thresholds (percent, above 0 and below 100) or the default owner ('' resets to the owner account)."""
    st = _rt(tenant_key, st)
    changes = {}
    for name, value in (("undercut_pct", undercut_pct), ("rank_surge_pct", rank_surge_pct)):
        if value is None:
            continue
        try:
            number = float(value)
        except (TypeError, ValueError):
            raise ValueError("A threshold must be a number.") from None
        if not 0 < number < 100:
            raise ValueError("A threshold must be above 0 and below 100 percent.")
        changes[name] = number

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


# --------------------------------------------------------------------------- price and rank reads

def _daily_quotes(tenant_key, st, asins):
    """Register demand and read published tenant quotes through core's daily-job interface."""
    _bound_store(tenant_key, st)
    if not asins:
        return {}, None
    try:
        from core import amazon_rivals
    except ImportError:
        return {}, WAIT_QUOTES
    try:
        amazon_rivals.want(st, sorted(asins), source="competitor_watch")
        return amazon_rivals.newest_quotes(st, sorted(asins)), None
    except Exception as exc:                                           # noqa: BLE001
        return {}, f"Daily price job quotes could not be read ({type(exc).__name__})."


def _quote_offers(quote):
    offers = quote.get("offers")
    if isinstance(offers, str):
        offers = json.loads(offers)
    if offers is None:
        return None
    if not isinstance(offers, list) or any(not isinstance(offer, dict) for offer in offers):
        raise ValueError("Invalid daily offer rows.")
    return offers


def _quote_metric(quote, mine, cause=None):
    if not quote:
        return {"price": None, "currency": None, "sellerId": None, "rank": None,
                "priceCause": cause or WAIT_QUOTES, "rankCause": cause or WAIT_QUOTES}
    field = "offer" if mine else "buy_box"
    price = quote.get(field + "_price")
    price = price if isinstance(price, (int, float)) and math.isfinite(price) else None
    rank = quote.get("sales_rank")
    rank = rank if isinstance(rank, int) and rank > 0 else None
    try:
        box = next((row for row in _quote_offers(quote) or () if row.get("buyBox")), {})
    except (ValueError, TypeError):
        box = {}
    return {"price": price, "currency": quote.get("currency"), "sellerId": box.get("sellerId"),
            "priceCause": quote.get(field + "_cause") if price is not None else
                          quote.get(field + "_cause") or "The daily price job returned no price.",
            "rank": rank, "rankCause": quote.get("rank_cause") if rank is not None else
                                      quote.get("rank_cause") or "The daily price job returned no sales rank."}


def _listing_asins(cur):
    if cur is None or "asin1" not in _columns(cur, LISTINGS_TABLE):
        raise SourceNotReady("Own ASINs need Amazon listings.")
    return {str(row[0]).strip() for row in cur.execute(
        f"SELECT DISTINCT asin1 FROM {LISTINGS_TABLE} WHERE asin1 IS NOT NULL AND trim(asin1) <> ''").fetchall()}


def _comparison_asin(week, ours):
    """Use our highest placed listing ASIN when SQP is unavailable."""
    rows = (week or {}).get("rows", {})
    return min(set(rows) & ours, key=lambda asin: (rows[asin][0], asin), default=None)


def _comparison_terms(tenant_key, st):
    index = _term_index(tenant_key, st)
    if index is None:
        raise TermsNotReady(TERMS_NOT_READY)
    index.require_tracking()
    return tracked_terms(tenant_key, st=st)


# --------------------------------------------------------------------------- the weekly comparison

def _seller_id(tenant_key, st):
    """Read only the seller identity from this tenant's saved Amazon credential."""
    from harness import amazon_store
    _bound_store(tenant_key, st)
    fields = amazon_store.credential(tenant_key, st) or {}
    return str(fields.get("seller_id") or "").strip()


def refresh(tenant_key, synced_tables, *, st=None, now=None):
    """Raise one durable alert per other seller from published daily offer rows."""
    if "daily_quotes" not in set(synced_tables or ()):
        return {"state": "not_synced", "created": []}
    st = _rt(tenant_key, st)
    _bound_store(tenant_key, st)
    now = now or _now()
    while not migrate_alerts(tenant_key, st=st):
        pass
    seller_id = _seller_id(tenant_key, st)
    owner = settings(tenant_key, st=st)["defaultOwner"]
    index = _alert_index(tenant_key, st)
    if not seller_id:
        index.record([], [{"term": "", "asin": None, "trigger": TRIGGERS["own_asin_seller"],
            "periodStart": "offers", "cause": "Your Amazon seller ID is unavailable. Reconnect Amazon and sync again."}],
            "offers", owner, now)
        return {"state": "seller_not_ready", "created": []}
    created = []
    with _reader(tenant_key, st) as cur:
        if cur is None:
            return {"state": "no_mirror", "created": []}
        ours = _listing_asins(cur)
        if not ours:
            return {"state": "no_own_asins", "created": []}
    quotes, cause = _daily_quotes(tenant_key, st, ours)
    raised, checks = [], []
    for asin in sorted(ours):
        quote = quotes.get(asin) or {}
        try:
            offers = _quote_offers(quote)
            offer_cause = cause or (WAIT_QUOTES if not quote else quote.get("offer_cause"))
        except (ValueError, TypeError):
            offers, offer_cause = None, "The daily price job returned invalid offer rows."
        if offers is None:
            checks.append({"term": "", "asin": asin, "trigger": TRIGGERS["own_asin_seller"],
                "periodStart": "offers", "cause": offer_cause or "The daily price job returned no offer rows."})
        for offer in offers or ():
            seller = str(offer.get("sellerId") or "").strip()
            if not seller or seller == seller_id or offer.get("mine"):
                continue
            price, buy_box = offer.get("price"), offer.get("buyBox")
            price = price if isinstance(price, (int, float)) and math.isfinite(price) else None
            price_text = f"Price {price:,.2f}." if price is not None else "Price unavailable."
            box_text = "Holds the Buy Box." if buy_box is True else (
                "Does not hold the Buy Box." if buy_box is False else "Buy Box status unavailable.")
            raised.append({"term": "", "asin": asin, "trigger": "own_asin_seller",
                "triggerKey": f"own_asin_seller:{asin}:{seller}", "periodStart": str(quote.get("quote_on") or ""),
                "detail": {"sellerId": seller, "price": price, "isBuyBoxWinner": buy_box,
                           "currency": offer.get("currency") or quote.get("currency")},
                "cause": f"Seller {seller}. {price_text} {box_text}"})
    created.extend(index.record(raised, checks, "offers", owner, now))
    return {"state": "refreshed", "created": created}


def on_amazon_sync(tenant_key, synced_tables):
    """Compare only a new Brand Analytics week without failing the connector sync."""
    failure = None
    for callback in (compare,):
        try:
            callback(tenant_key, synced_tables)
        except Exception as exc:                                       # noqa: BLE001
            failure = (READ_FAILED.format(cause=exc) if isinstance(exc, _ReadFailed) else
                       f"The weekly comparison failed ({type(exc).__name__}): {exc}")
    if failure:
        try:
            def _note(doc):
                doc = doc if isinstance(doc, dict) else {}
                doc["last_error"] = failure
                return doc
            _rt(tenant_key).update(KEY_WEEKS, _note)
        except Exception:                                              # noqa: BLE001
            pass


def on_quotes(tenant, changed):
    """Consume published daily quotes and retry unresolved checks within their original week."""
    st = _rt(tenant)
    # A seller-offer failure must not strand a waiting weekly check.
    try:
        refresh(tenant, ("daily_quotes",), st=st)
    finally:
        compare(tenant, ("daily_quotes",), st=st, quote_asins=changed)


def _clear_error(doc):
    doc = doc if isinstance(doc, dict) else {}
    doc.pop("last_error", None)
    return doc


def _weekly_state(doc):
    """Normalize legacy timestamp week keys before comparing with connector date keys."""
    out = dict(doc)
    if out.get("last_compared"):
        out["last_compared"] = dt.date.fromisoformat(str(out["last_compared"])[:10]).isoformat()
    metrics = {}
    for key, value in (out.get("metrics") or {}).items():
        day = dt.date.fromisoformat(str(key)[:10]).isoformat()
        if day in metrics and metrics[day] != value:
            raise SourceNotReady("Stored weekly metrics disagree for one week.")
        metrics[day] = value
    out["metrics"] = metrics
    return out


def compare(tenant_key, synced_tables=("brand_analytics",), *, st=None, now=None, quote_asins=None):
    """Compare the newest held week with the week before and raise owned alerts. Returns a summary."""
    st = _rt(tenant_key, st)
    now = now or _now()
    while not migrate_alerts(tenant_key, st=st):
        pass
    synced = set(synced_tables or ())
    daily = "daily_quotes" in synced
    with _reader(tenant_key, st) as cur:
        if cur is None:
            return {"state": "no_mirror"}
        if "brand_analytics" in synced:
            _ba_columns(cur)
        if not daily:
            seed_terms(tenant_key, st=st, cur=cur)
        if "brand_analytics" not in synced and not daily:
            return {"state": "seeded"}
        periods = _periods(cur)
        if not periods:
            return {"state": "no_week"}
        terms = _comparison_terms(tenant_key, st)
        held = _top3(cur, terms)
        ours = _listing_asins(cur)
    weeks = _weekly_state(_doc(st, KEY_WEEKS))
    newest = periods[0]
    if daily and weeks.get("last_compared") != newest:
        return {"state": "awaits_weekly_pull", "period": newest}
    retry = set(weeks.get("pending_quotes") or ()) & set(quote_asins or ()) if daily else None
    if daily and not retry:
        return {"state": "already_compared", "period": newest}
    if not daily and weeks.get("last_compared") == newest and not weeks.get("last_error"):
        return {"state": "already_compared", "period": newest}
    previous = periods[1] if len(periods) > 1 else None
    conf = settings(tenant_key, st=st)

    want = {asin for term in terms for asin in ((held.get(term) or {}).get(newest) or {}).get("rows", {})}
    quotes, quote_cause = _daily_quotes(tenant_key, st, want)
    current = (weeks.get("metrics") or {}).get(newest) or {}
    metrics = {a: current[a] if daily and a not in retry and a in current else
               _quote_metric(quotes.get(a), a in ours, quote_cause) for a in sorted(want)}
    prior = ((weeks.get("metrics") or {}).get(previous) or {}) if previous else {}

    raised, term_checks = _term_signals(terms, held, periods, ours, metrics, prior, conf, retry)
    checks = []
    for asin, metric in metrics.items():
        parts = list(dict.fromkeys(c for c in (metric.get("priceCause"), metric.get("rankCause")) if c))
        if metric.get("price") is not None:
            parts.insert(0, f"Price {metric['price']:,.2f} {metric.get('currency') or ''}.".strip())
        checks.append({"term": "", "asin": asin, "trigger": "Daily price", "periodStart": newest,
                       "detail": metric, "cause": " ".join(parts)})
    checks.extend(term_checks)
    created = _alert_index(tenant_key, st).record(raised, checks, newest, conf["defaultOwner"], now)

    ready = previous is not None

    def _weeks(doc):
        doc = _weekly_state(doc if isinstance(doc, dict) else {})
        doc.setdefault("metrics", {})[newest] = metrics
        doc["pending_quotes"] = [asin for asin, metric in metrics.items()
                                 if metric.get("price") is None or metric.get("rank") is None]
        doc["last_compared"] = newest
        doc["comparison"] = {"ready": ready, "message": None if ready else NOT_READY,
                             "periodStart": newest, "previousPeriodStart": previous,
                             "comparedAt": _stamp(now), "alertsRaised": len(created),
                             "checks": len(checks)}
        return _clear_error(doc)
    st.update(KEY_WEEKS, _weeks)
    return {"state": "compared" if ready else "waiting", "period": newest, "previous": previous,
            "created": created, "checks": checks}


def _term_signals(terms, held, periods, ours, metrics, prior, conf, retry):
    """Derive weekly and quote-retry signals without changing alert state."""
    raised, checks = [], []
    if len(periods) < 2:
        return raised, checks
    newest, previous = periods[:2]
    daily = retry is not None
    undercut, surge = conf["undercut_pct"] / 100.0, conf["rank_surge_pct"] / 100.0
    for term in terms:
        now_week = (held.get(term) or {}).get(newest)
        was_week = (held.get(term) or {}).get(previous)
        if not now_week or not was_week:
            continue
        top_now, top_was = now_week["rows"], was_week["rows"]

        def found(asin, key, detail, cause=None):
            raised.append({"term": term, "asin": asin, "trigger": key, "periodStart": newest,
                           "periodEnd": now_week["end"], "previousPeriodStart": previous,
                           "detail": detail, "cause": cause})

        def asin_cause(asin):
            m = metrics.get(asin) or {}
            return " ".join(c for c in (m.get("priceCause"), m.get("rankCause")) if c) or None

        for asin in sorted(set(top_now) - set(top_was)) if not daily else ():
            found(asin, "new_asin", {"rank": top_now[asin][0]}, asin_cause(asin))
        for asin in sorted((set(top_was) - set(top_now)) & ours) if not daily else ():
            found(asin, "lost_spot", {"previousRank": top_was[asin][0]})
        mine = _comparison_asin(now_week, ours)
        mine_m = metrics.get(mine) or {}
        if mine is None and set(top_now) - ours:
            checks.append({"term": term, "asin": None, "trigger": TRIGGERS["undercut"], "periodStart": newest,
                           "cause": "None of our listing ASINs is in this term's top 3, so there is "
                                    "no price of ours to compare."})
        for asin in sorted(set(top_now) - ours):
            m = metrics.get(asin) or {}
            if mine is not None:
                if mine_m.get("price") is None or m.get("price") is None:
                    cause = " ".join(c for c in (mine_m.get("priceCause") and f"Our price: {mine_m['priceCause']}",
                                                m.get("priceCause")) if c)
                    checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["undercut"],
                                   "periodStart": newest, "cause": cause or "No price was read."})
                elif m["price"] <= mine_m["price"] * (1 - undercut) and (not daily or asin in retry or mine in retry):
                    found(asin, "undercut", {"ourAsin": mine, "ourPrice": mine_m["price"], "price": m["price"],
                          "percentUnder": round(100 * (1 - m["price"] / mine_m["price"]), 2)}, asin_cause(asin))
            old = prior.get(asin) or {}
            if m.get("rank") is None:
                checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],
                               "periodStart": newest, "cause": m.get("rankCause") or "No sales rank was read."})
            elif old.get("rank") is None:
                if old.get("rankCause"):
                    checks.append({"term": term, "asin": asin, "trigger": TRIGGERS["rank_surge"],
                                   "periodStart": newest, "cause": f"The week before: {old['rankCause']}"})
            elif m["rank"] <= old["rank"] * (1 - surge) and (not daily or asin in retry):
                found(asin, "rank_surge", {"rank": m["rank"], "previousRank": old["rank"]}, asin_cause(asin))
    return raised, checks


# --------------------------------------------------------------------------- alerts

class _AlertIndex(_DocumentIndex):
    """Separate alert and check rows share the tenant store and one transactional sequence lock."""

    @staticmethod
    def decode(value):
        return json.loads(value) if isinstance(value, str) else value

    def ready(self):
        with self.connection() as con:
            row = con.execute(self.sql("SELECT value ->> 'version' FROM {tbl} WHERE key = %s"),
                              [self.key(KEY_ALERT_INDEX)]).fetchone()
        return bool(row and row[0] == "1")

    def open_counts(self):
        if not self.ready():
            raise AlertsNotReady(ALERTS_NOT_READY)
        with self.connection() as con:
            return dict(con.execute(self.sql("SELECT value ->> 'term', count(*) FROM {tbl} "
                "WHERE starts_with(key, %s) AND (value ->> 'status') = 'Open' GROUP BY value ->> 'term'"),
                [self.key(ALERT_PREFIX)]).fetchall())

    def _put(self, con, key, value, *, keep=False):
        conflict = "DO NOTHING" if keep else "DO UPDATE SET value = excluded.value"
        con.execute(self.sql("INSERT INTO {tbl} (key, value) VALUES (%s, %s::jsonb) "
                             "ON CONFLICT (key) " + conflict), [self.key(key), json.dumps(value)])

    @contextlib.contextmanager
    def _locked(self, *, prepare=False):
        self.pg.check_write(self.slug, "write competitor watch alert rows")
        with self.connection() as con:
            con.execute("SET LOCAL lock_timeout = '10s'")
            con.execute("SET LOCAL statement_timeout = '30s'")
            if prepare:
                self._put(con, KEY_ALERT_INDEX, {"seq": 0, "itemCursor": "", "checkOffset": 0}, keep=True)
            row = con.execute(self.sql("SELECT value FROM {tbl} WHERE key = %s FOR UPDATE"),
                              [self.key(KEY_ALERT_INDEX)]).fetchone()
            meta = self.decode(row[0]) if row else {}
            if not prepare and meta.get("version") != 1:
                raise AlertsNotReady(ALERTS_NOT_READY)
            yield con, meta
            self._put(con, KEY_ALERT_INDEX, meta)

    def _legacy_items(self, con, cursor, size):
        return con.execute(self.sql("SELECT item.key, item.value FROM {tbl}, "
            "LATERAL jsonb_each(value -> 'items') AS item WHERE {tbl}.key = %s "
            "AND item.key COLLATE \"C\" > %s ORDER BY item.key COLLATE \"C\" LIMIT %s"),
            [self.key(KEY_ALERTS), cursor, size]).fetchall()

    def _legacy_checks(self, con, offset, size):
        return con.execute(self.sql("SELECT item.ordinality, item.value FROM {tbl}, "
            "LATERAL jsonb_array_elements(value -> 'checks') WITH ORDINALITY AS item(value, ordinality) "
            "WHERE key = %s AND item.ordinality > %s ORDER BY item.ordinality LIMIT %s"),
            [self.key(KEY_ALERTS), offset, size]).fetchall()

    def migrate(self, size):
        with self._locked(prepare=True) as (con, meta):
            if meta.get("version") == 1:
                return True
            old_seq = con.execute(self.sql("SELECT value ->> 'seq' FROM {tbl} WHERE key = %s"),
                                  [self.key(KEY_ALERTS)]).fetchone()
            meta["seq"] = max(meta["seq"], int(old_seq[0] or 0) if old_seq else 0)
            items = self._legacy_items(con, meta["itemCursor"], size)
            for key, value in items:
                alert = self.decode(value)
                sequence = int(str(alert.get("id") or key)[1:])
                # Missing createdAt stays missing. Copy every other legacy field unchanged.
                self._put(con, ALERT_PREFIX + key, {**alert, "sequence": sequence}, keep=True)
                meta["seq"] = max(meta["seq"], sequence)
                meta["itemCursor"] = key
            checks = self._legacy_checks(con, meta["checkOffset"], size)
            for ordinal, value in checks:
                self._put(con, CHECK_PREFIX + f"legacy/{ordinal}",
                          {**self.decode(value), "sequence": ordinal}, keep=True)
                meta["checkOffset"] = ordinal
            if len(items) < size and len(checks) < size:
                meta["version"] = 1
            return meta.get("version") == 1

    def _page(self, con, prefix, search, status, offset, limit, *, checks=False,
              trigger=None, include_sellers=True):
        order = "period DESC, sequence, key COLLATE \"C\"" if checks else "sequence DESC"
        final_order = "page.period DESC, page.sequence, page.key COLLATE \"C\"" if checks else "page.sequence DESC"
        # Pick page keys before projecting alert bodies and their histories.
        statement = self.sql("WITH matches AS (SELECT key, value ->> 'periodStart' AS period, "
            "coalesce(value ->> 'sequence', '0')::numeric AS sequence FROM {tbl} WHERE starts_with(key, %s) "
            "AND (%s::text IS NULL OR (value ->> 'status') = %s) "
            "AND (%s::text IS NULL OR (value ->> 'trigger') = %s) "
            "AND (%s OR coalesce(value ->> 'trigger', '') <> %s) "
            "AND strpos(lower(concat_ws(' ', value ->> 'term', value ->> 'asin', value ->> 'trigger', "
            "value ->> 'owner', value ->> 'cause')), %s) > 0), "
            "totals AS (SELECT count(*) AS total FROM matches), bounds AS (SELECT total, "
            "CASE WHEN %s >= total THEN greatest(0, floor((total - 1)::numeric / %s)::bigint * %s) "
            "ELSE %s END AS skip FROM totals) SELECT total, skip, "
            "ARRAY(SELECT stored.value::text FROM (SELECT key, sequence, period FROM matches ORDER BY " + order +
            " LIMIT %s OFFSET (SELECT skip FROM bounds)) AS page JOIN {tbl} AS stored ON stored.key = page.key "
            "ORDER BY " + final_order + ") FROM bounds")
        row = con.execute(statement, [self.key(prefix), status, status, trigger, trigger, include_sellers,
            TRIGGERS["own_asin_seller"], search, offset, limit, limit, offset, limit]).fetchone()
        return {"total": row[0], "offset": row[1], "limit": limit,
                "rows": [self.decode(value) for value in row[2]]}

    def page(self, search, status, offset, limit, check_offset, check_limit, *, trigger=None, include_sellers=True):
        if not self.ready():
            raise AlertsNotReady(ALERTS_NOT_READY)
        with self.connection() as con:
            alerts = self._page(con, ALERT_PREFIX, search, status, offset, limit,
                                trigger=trigger, include_sellers=include_sellers)
            checks = self._page(con, CHECK_PREFIX, search, None, check_offset, check_limit, checks=True,
                                trigger=trigger, include_sellers=include_sellers)
        return {"alerts": alerts.pop("rows"), "checks": checks.pop("rows"),
                "alertPage": alerts, "checkPage": checks, "statuses": list(STATUSES)}

    def record(self, raised, checks, newest, owner, now):
        created = []
        with self._locked() as (con, meta):
            for hit in raised:
                seller_hit = hit["trigger"] == "own_asin_seller"
                trigger_key = hit.get("triggerKey") or hit["trigger"]
                latest = con.execute(self.sql("SELECT value ->> 'status' FROM {tbl} "
                    "WHERE starts_with(key, %s) AND (%s OR (value ->> 'term') = %s) AND (value ->> 'asin') = %s "
                    "AND (value ->> 'triggerKey') = %s ORDER BY (value ->> 'sequence')::numeric DESC LIMIT 1"),
                    [self.key(ALERT_PREFIX), seller_hit, hit["term"], hit["asin"], trigger_key]).fetchone()
                if latest and (seller_hit or latest[0] in HOLDING):
                    continue
                meta["seq"] += 1
                aid = f"a{meta['seq']}"
                alert = {**hit, "id": aid, "sequence": meta["seq"], "triggerKey": trigger_key,
                         "trigger": TRIGGERS[hit["trigger"]], "owner": owner, "status": "Open",
                         "due": (now.date() + dt.timedelta(days=DUE_DAYS)).isoformat(),
                         "createdAt": _stamp(now), "updatedAt": _stamp(now), "updatedBy": "system",
                         "history": [{"at": _stamp(now), "by": "system", "event": "created"}]}
                self._put(con, ALERT_PREFIX + aid, alert)
                created.append(aid)
            con.execute(self.sql("DELETE FROM {tbl} WHERE starts_with(key, %s) AND (value ->> 'periodStart') = %s"),
                        [self.key(CHECK_PREFIX), newest])
            for i, check in enumerate(checks):
                self._put(con, CHECK_PREFIX + f"sync/{newest}/{i}", {**check, "sequence": i})
        return created

    def update(self, alert_id, change):
        with self._locked() as (con, _meta):
            row = con.execute(self.sql("SELECT value FROM {tbl} WHERE key = %s"),
                              [self.key(ALERT_PREFIX + alert_id)]).fetchone()
            if row is None:
                raise KeyError(alert_id)
            alert = self.decode(row[0])
            change(alert)
            self._put(con, ALERT_PREFIX + alert_id, alert)
            return alert


def _alert_index(tenant_key, st):
    from core.store_pg import PgStore
    if not isinstance(_bound_store(tenant_key, st), PgStore):
        raise AlertsNotReady("Alert paging needs the tenant Postgres store. Ask an administrator to finish the store migration.")
    return _AlertIndex(tenant_key, st)


def migrate_alerts(tenant_key, *, st=None, batch_size=500):
    """Copy one restartable legacy batch and return whether alert paging is ready, without schema changes."""
    return _alert_index(tenant_key, _rt(tenant_key, st)).migrate(max(1, int(batch_size)))


def alerts(tenant_key, *, status=None, st=None, search="", offset=0, limit=50, check_offset=0, check_limit=50,
           trigger=None, include_sellers=True):
    """Read server-filtered pages of alerts and checks without touching the legacy collection."""
    if status is not None and status not in STATUSES:
        raise ValueError("Unknown alert status.")
    if trigger is not None and trigger not in TRIGGERS:
        raise ValueError("Unknown alert trigger.")
    return _alert_index(tenant_key, _rt(tenant_key, st)).page(
        _norm(search), status, max(0, int(offset)), max(1, min(100, int(limit))),
        max(0, int(check_offset)), max(1, min(100, int(check_limit))),
        trigger=TRIGGERS.get(trigger), include_sellers=include_sellers)


def update_alert(tenant_key, alert_id, *, owner=None, status=None, due=None, user="system", st=None,
                 include_sellers=True):
    """Reassign, move status, or move the due date of one alert. Returns the alert."""
    if status is not None and status not in STATUSES:
        raise ValueError("Status must be one of: " + ", ".join(STATUSES) + ".")
    if due is not None:
        try:
            due = dt.date.fromisoformat(str(due)).isoformat()
        except ValueError:
            raise ValueError("Due must be a date such as 2026-10-27.") from None
    if owner is not None and not str(owner).strip():
        raise ValueError("Owner cannot be empty.")
    st = _rt(tenant_key, st)

    def _apply(alert):
        if not include_sellers and alert.get("trigger") == TRIGGERS["own_asin_seller"]:
            raise PermissionError("Your account cannot change seller alerts.")
        at = _stamp(_now())
        event = {"at": at, "by": user}
        if owner is not None:
            alert["owner"] = event["owner"] = str(owner).strip()
        if status is not None:
            alert["status"] = event["status"] = status
        if due is not None:
            alert["due"] = event["due"] = due
        alert["updatedAt"], alert["updatedBy"] = at, user
        alert.setdefault("history", []).append(event)
    return _alert_index(tenant_key, st).update(alert_id, _apply)


# --------------------------------------------------------------------------- term detail

def term_detail(tenant_key, term, *, st=None, reader=None, history=None):
    """One term's held periods, the newest top 3 with week-over-week change, and the click share trend."""
    st = _rt(tenant_key, st)
    key = _norm(term)
    with contextlib.nullcontext(reader) if reader is not None else _reader(tenant_key, st) as cur:
        sqp = _sqp(cur, key) if cur is not None else []
        weeks_held = _top3(cur, [key]).get(key, {}) if history is None else history
        candidates = {a for week in weeks_held.values() for a in week["rows"]}
        ours = _our_asins(cur, sqp, candidates) if cur is not None else set()
    periods = sorted(weeks_held, reverse=True)
    metric_asins = sorted(weeks_held[periods[0]]["rows"]) if periods else []
    variants = (periods[0], periods[0] + "T00:00:00Z", periods[0] + " 00:00:00") if periods else ()
    state, *values = _paths(tenant_key, st, KEY_WEEKS, [("comparison",)] +
                           [("metrics", week, asin) for asin in metric_asins for week in variants])
    metric = {asin: next((value for value in values[i * 3:i * 3 + 3] if value is not None), None)
              for i, asin in enumerate(metric_asins)}
    top3 = []
    if periods:
        newest = weeks_held[periods[0]]["rows"]
        before = weeks_held[periods[1]]["rows"] if len(periods) > 1 else None
        for asin, (rank, share, conv) in sorted(newest.items(), key=lambda kv: kv[1][0]):
            change = None
            if before is not None:
                if asin not in before:
                    change = {"kind": "new", "previousRank": None, "clickShareDelta": None,
                              "conversionShareDelta": None}
                else:
                    r0, s0, c0 = before[asin]
                    change = {"kind": "up" if rank < r0 else "down" if rank > r0 else "same",
                              "previousRank": r0,
                              "clickShareDelta": None if share is None or s0 is None else share - s0,
                              "conversionShareDelta": None if conv is None or c0 is None else conv - c0}
            m = metric.get(asin) or {}
            top3.append({"asin": asin, "rank": rank, "clickShare": share, "conversionShare": conv,
                         "isOurs": asin in ours, "change": change, "buyBoxPrice": m.get("price"),
                         "currency": m.get("currency"), "salesRank": m.get("rank"),
                         "priceCause": m.get("priceCause"), "rankCause": m.get("rankCause")})
    every = sorted({a for p in periods for a in weeks_held[p]["rows"]})
    trend = [{"asin": a, "isOurs": a in ours,
              "clickShare": [(weeks_held[p]["rows"].get(a) or (None, None, None))[1]
                             if a in weeks_held[p]["rows"] else None for p in periods]} for a in every]
    state = state or {}
    ready = len(periods) > 1 and bool(state.get("ready", True))
    return {"term": key, "termLabel": display_term(key), "periods": periods, "top3": top3, "trend": trend,
            "comparison": {"ready": ready, "message": None if ready else NOT_READY}}


def _dashboard_period(start, end):
    start = dt.date.fromisoformat(str(start)[:10]).isoformat() if start else None
    end = dt.date.fromisoformat(str(end)[:10]).isoformat() if end else None
    if start and end and start > end:
        raise ValueError("The start date must come before the end date.")
    return start, end


def _dashboard_term_count(tenant_key, st, *, omitted=False, independent=False):
    """Count indexed membership and read its readiness in the same tenant-bound statement."""
    index = _term_index(tenant_key, st)
    if index is None:
        raise TermsNotReady(TERMS_NOT_READY)
    membership = ("SELECT term, ours FROM {terms} WHERE tenant = %s AND (ours OR starred)"
                  if not independent else
                  "SELECT term, ours FROM {terms} WHERE tenant = %s AND ours = TRUE UNION "
                  "SELECT term, ours FROM {terms} WHERE tenant = %s AND starred = TRUE")
    query = index.sql(index.term_sql(
        "WITH tracked AS (" + membership + "), counts AS ("
        "SELECT COUNT(*) AS total, COALESCE(SUM(CASE WHEN ours THEN 1 ELSE 0 END), 0) AS owned FROM tracked) "
        "SELECT (SELECT value ->> 'version' FROM {tbl} WHERE key = %s), "
        "(SELECT value ->> 'trackingReady' FROM {tbl} WHERE key = %s), "
        "(SELECT value ->> 'trackingCause' FROM {tbl} WHERE key = %s), "
        + ("total - LEAST(10, owned)" if omitted else "total") + " FROM counts"))
    with index.connection() as con:
        version, ready, cause, value = con.execute(query, [index.slug] * (2 if independent else 1)
            + [index.key(KEY_TERM_INDEX)] * 3).fetchone()
    if version != "2":
        raise TermsNotReady(TERMS_NOT_READY)
    if ready != "true":
        raise SourceNotReady(cause or TRACKING_NOT_READY)
    return int(value)


def _dashboard_open_alerts(tenant_key, st):
    index = _alert_index(tenant_key, st)
    with index.connection() as con:
        rows = con.execute(index.sql(
            "WITH counts AS (SELECT COALESCE(NULLIF(value ->> 'trigger', ''), 'Other') AS trigger, "
            "COUNT(*) AS total FROM {tbl} WHERE starts_with(key, %s) "
            "AND (value ->> 'status') = 'Open' GROUP BY 1) "
            "SELECT (SELECT value ->> 'version' FROM {tbl} WHERE key = %s), trigger, total "
            "FROM (SELECT 1) anchor LEFT JOIN counts ON TRUE ORDER BY trigger"),
            [index.key(ALERT_PREFIX), index.key(KEY_ALERT_INDEX)]).fetchall()
    if not rows or rows[0][0] != "1":
        raise AlertsNotReady(ALERTS_NOT_READY)
    return {trigger: int(total) for _version, trigger, total in rows if trigger is not None}


def _dashboard_click_share(cur, start, end):
    """Read the ten highest term shares and invalid evidence in one bounded BA query."""
    if cur is None:
        raise SourceNotReady("Own-brand click share needs dated Brand Analytics and listing ASINs.")
    query = (
        f"WITH newest AS (SELECT MAX(TRY_CAST(_period_start AS TIMESTAMP)) AS day FROM {BA_TABLE} "
        f"WHERE {_weekly_period_sql()}), "
        "held AS (SELECT b.clicked_asin, b._period_end, " + _term_sql("b.search_term") + " AS term, "
        f"TRY_CAST(b.click_share AS DOUBLE) AS share FROM {BA_TABLE} b "
        f"WHERE {_weekly_period_sql()} AND TRY_CAST(b._period_start AS TIMESTAMP) = (SELECT day FROM newest) "
        "AND TRY_CAST(b.click_share_rank AS INTEGER) BETWEEN 1 AND 3 "
        f"AND EXISTS(SELECT 1 FROM {LISTINGS_TABLE} o WHERE trim(o.asin1) = trim(b.clicked_asin)) "
        "AND (? IS NULL OR CAST(b._period_start AS DATE) >= CAST(? AS DATE)) "
        "AND (? IS NULL OR CAST(b._period_end AS DATE) <= CAST(? AS DATE))), "
        "totals AS (SELECT term, SUM(share) AS share, "
        "COUNT(*) <> COUNT(share) OR COUNT(*) <> COUNT(DISTINCT trim(clicked_asin)) "
        "OR COUNT(DISTINCT _period_end) <> 1 OR term = '' "
        "OR NOT BOOL_AND(isfinite(share) AND share BETWEEN 0 AND 1) "
        "OR SUM(share) > 1 AS invalid FROM held GROUP BY term), "
        "summary AS (SELECT COALESCE(BOOL_OR(invalid), FALSE) AS invalid FROM totals), "
        "top_terms AS (SELECT term, share FROM totals ORDER BY share DESC, term LIMIT 10) "
        "SELECT summary.invalid, term, share FROM summary LEFT JOIN top_terms ON TRUE "
        "ORDER BY share DESC, term")
    rows = cur.execute(query, [start, start, end, end]).fetchall()
    if any(invalid for invalid, _term, _share in rows):
        raise SourceNotReady("An own-brand click share is missing, invalid or duplicated.")
    series = [{"x": display_term(term), "y": round(float(share) * 100, 9)}
              for _invalid, term, share in rows if term is not None]
    if not series:
        raise SourceNotReady("No own-brand click share in the newest dated week.")
    return series


def _check_dashboard_click_share(cur, start, end):
    """Independently rank term totals from per-ASIN weekly evidence in one source read."""
    if cur is None:
        raise SourceNotReady("Own-brand click share needs dated Brand Analytics and listing ASINs.")
    query = (
        "WITH dated AS (SELECT search_term, clicked_asin, click_share_rank, click_share, _period_start, _period_end "
        f"FROM {BA_TABLE} WHERE {_weekly_period_sql()}), "
        "evidence AS (SELECT " + _term_sql("search_term") + " AS term, trim(clicked_asin) AS asin, "
        "_period_end AS stop, TRY_CAST(click_share AS DOUBLE) AS share FROM dated "
        "WHERE TRY_CAST(_period_start AS TIMESTAMP) = (SELECT MAX(TRY_CAST(_period_start AS TIMESTAMP)) FROM dated) "
        "AND TRY_CAST(click_share_rank AS INTEGER) IN (1, 2, 3) "
        f"AND trim(clicked_asin) IN (SELECT DISTINCT trim(asin1) FROM {LISTINGS_TABLE} WHERE asin1 IS NOT NULL) "
        "AND (? IS NULL OR CAST(_period_start AS DATE) >= CAST(? AS DATE)) "
        "AND (? IS NULL OR CAST(_period_end AS DATE) <= CAST(? AS DATE))), "
        "per_asin AS (SELECT term, asin, MIN(share) AS share, COUNT(*) AS n, COUNT(share) AS known, "
        "MIN(stop) AS stop FROM evidence GROUP BY term, asin), "
        "per_term AS (SELECT term, SUM(share) AS share, "
        "MIN(n) = 1 AND MAX(n) = 1 AND MIN(known) = 1 AND term <> '' "
        "AND BOOL_AND(isfinite(share) AND share >= 0 AND share <= 1) "
        "AND COUNT(DISTINCT stop) = 1 AND SUM(share) <= 1 AS valid FROM per_asin GROUP BY term), "
        "bad AS (SELECT COUNT(*) AS n FROM per_term WHERE valid IS NOT TRUE), "
        "ranked AS (SELECT term, share, ROW_NUMBER() OVER (ORDER BY share DESC, term) AS position FROM per_term) "
        "SELECT bad.n, term, share FROM bad LEFT JOIN ranked ON position <= 10 ORDER BY position")
    rows = cur.execute(query, [start, start, end, end]).fetchall()
    if any(bad for bad, _term, _share in rows):
        raise SourceNotReady("The newest Brand Analytics share source is missing or ambiguous.")
    series = [{"x": display_term(term), "y": round(100 * float(share), 9)}
              for _bad, term, share in rows if term is not None]
    if not series:
        raise SourceNotReady("No own-brand click share in the newest dated week.")
    return series


def validate_dashboard_figure(tenant_key, figure, *, start=None, end=None, st=None):
    """Reconcile each figure with separate SQL counts or period sums from its source rows."""
    st = _rt(tenant_key, st)
    _bound_store(tenant_key, st)
    if getattr(st, "key", tenant_key) != tenant_key:
        raise PermissionError("The competitor watch store belongs to another tenant.")
    start, end = _dashboard_period(start, end)
    fid = figure.get("id", "")
    try:
        if fid in ("tracked_terms", "terms_not_shown"):
            value = _dashboard_term_count(tenant_key, st, omitted=fid == "terms_not_shown", independent=True)
            label = "Tracked terms" if fid == "tracked_terms" else "Terms not shown"
            unit, source, series = "count", TERM_TABLE, []
        elif fid == "open_alerts":
            index = _alert_index(tenant_key, st)
            with index.connection() as con:
                rows = con.execute(index.sql(
                    "WITH totals AS (SELECT COALESCE(NULLIF(value ->> 'trigger', ''), 'Other') AS trigger, "
                    "SUM(CASE WHEN value ->> 'status' = 'Open' THEN 1 ELSE 0 END) AS total FROM {tbl} "
                    "WHERE starts_with(key, %s) GROUP BY 1 "
                    "HAVING SUM(CASE WHEN value ->> 'status' = 'Open' THEN 1 ELSE 0 END) > 0) "
                    "SELECT (SELECT value ->> 'version' FROM {tbl} WHERE key = %s), trigger, total "
                    "FROM (SELECT 1) anchor LEFT JOIN totals ON TRUE ORDER BY trigger"),
                    [index.key(ALERT_PREFIX), index.key(KEY_ALERT_INDEX)]).fetchall()
            if not rows or rows[0][0] != "1":
                raise AlertsNotReady(ALERTS_NOT_READY)
            series = [{"x": trigger, "y": int(count)} for _version, trigger, count in rows if trigger is not None]
            value = sum(point["y"] for point in series)
            label, unit, source = "Open alerts", "count", ALERT_PREFIX
        elif fid == "click_share":
            with _reader(tenant_key, st) as cur:
                series = _check_dashboard_click_share(cur, start, end)
            value = max(point["y"] for point in series)
            label, unit, source = "Highest own-brand click share", "percent", BA_TABLE
        else:
            raise ValueError("Unknown dashboard figure.")
        ok = (figure.get("value") == value and figure.get("series") == series and figure.get("label") == label
              and figure.get("unit") == unit and figure.get("source_table") == source)
        return {"ok": ok, "id": fid, "reason": None if ok else "The figure does not tie to its source."}
    except (ValueError, RuntimeError, _ReadFailed) as exc:
        return {"ok": False, "id": fid, "reason": str(exc)}
    except Exception as exc:
        return {"ok": False, "id": fid, "reason": f"The source check failed ({type(exc).__name__})."}


validate_figure = validate_dashboard_figure


def dashboard(tenant_key, start=None, end=None, *, st=None, **_):
    """Produce four bounded raw figures in four reads for the canonical dispatcher to check."""
    st = _rt(tenant_key, st)
    _bound_store(tenant_key, st)
    if getattr(st, "key", tenant_key) != tenant_key:
        raise PermissionError("The competitor watch store belongs to another tenant.")
    start, end = _dashboard_period(start, end)
    figures = []
    tracked = {"id": "tracked_terms", "label": "Tracked terms", "value": None, "unit": "count",
               "series": [], "source_table": TERM_TABLE}
    try:
        tracked["value"] = _dashboard_term_count(tenant_key, st)
    except Exception as exc:
        tracked["reason"] = str(exc) if isinstance(exc, (TermsNotReady, SourceNotReady)) else "Tracked terms could not be read."
    figures.append(tracked)
    share = {"id": "click_share", "label": "Highest own-brand click share", "value": None,
             "unit": "percent", "series": [], "source_table": BA_TABLE}
    try:
        with _reader(tenant_key, st) as cur:
            share["series"] = _dashboard_click_share(cur, start, end)
        share["value"] = max(point["y"] for point in share["series"])
    except Exception as exc:
        share["reason"] = (str(exc) if isinstance(exc, SourceNotReady) else
                           "Own-brand click share needs dated Brand Analytics click shares and listing ASINs.")
    figures.append(share)
    omitted = {"id": "terms_not_shown", "label": "Terms not shown", "value": None,
               "unit": "count", "series": [], "source_table": TERM_TABLE}
    try:
        omitted["value"] = _dashboard_term_count(tenant_key, st, omitted=True)
        # A capacity count depends on a held series; all-starred membership does not.
        if (share["value"] is None and tracked["value"] is not None
                and omitted["value"] < tracked["value"]):
            omitted.update(value=None, reason=share["reason"])
    except Exception as exc:
        omitted["reason"] = str(exc) if isinstance(exc, (TermsNotReady, SourceNotReady)) else "Tracked terms could not be read."
    figures.append(omitted)
    alert = {"id": "open_alerts", "label": "Open alerts", "value": None, "unit": "count",
             "series": [], "source_table": ALERT_PREFIX}
    try:
        counts = _dashboard_open_alerts(tenant_key, st)
        alert.update(value=sum(counts.values()), series=[{"x": k, "y": v} for k, v in sorted(counts.items())])
    except Exception as exc:
        alert["reason"] = str(exc) if isinstance(exc, AlertsNotReady) else "Open alerts could not be read."
    figures.append(alert)
    return {"figures": figures, "start": start, "end": end}


def validate_dashboard(tenant_key, figures=None, *, start=None, end=None, st=None, **_):
    """Expose independent figure checks to the shared dashboard dispatcher."""
    st = _rt(tenant_key, st)
    if figures is None:
        figures = dashboard(tenant_key, start, end, st=st)["figures"]
    detail = [validate_dashboard_figure(tenant_key, figure, start=start, end=end, st=st) for figure in figures]
    return {"ok": bool(detail) and all(check["ok"] for check in detail), "detail": detail}