File size: 128,390 Bytes
d598032
 
 
 
9e15897
d598032
b2aa446
d598032
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
7f72224
62a1265
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62a1265
 
 
 
d598032
 
 
 
7f72224
9e15897
 
 
d598032
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
9e15897
d598032
 
 
9e15897
 
 
 
d598032
 
9e15897
 
 
 
7f72224
d598032
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
9e15897
 
d598032
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
9e15897
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
9e15897
 
d598032
 
 
 
9e15897
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
9e15897
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
9e15897
 
 
d598032
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
b2aa446
d598032
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
b2aa446
 
d598032
9e15897
d598032
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
d598032
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
7f72224
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
62a1265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196dc69
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
d598032
b2aa446
7f72224
 
 
9e15897
 
 
 
 
 
 
d598032
b2aa446
 
 
62a1265
196dc69
62a1265
9e15897
62a1265
7f72224
 
 
b2aa446
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
1adb293
7f72224
 
1adb293
7f72224
 
 
 
 
 
 
1adb293
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1adb293
7f72224
 
 
 
 
 
 
d598032
 
 
 
 
7f72224
d598032
b2aa446
d598032
7f72224
 
 
 
 
 
d598032
7f72224
 
 
d598032
 
 
 
 
7f72224
b2aa446
d598032
b2aa446
7f72224
 
 
 
b2aa446
 
 
 
d598032
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
d598032
b2aa446
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
d598032
 
 
b2aa446
 
d598032
 
7f72224
 
d598032
 
b2aa446
d598032
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
9e15897
 
d598032
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
d598032
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
d598032
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
9e15897
 
d598032
 
9e15897
 
 
 
d598032
9e15897
d598032
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
d598032
 
 
 
 
 
b2aa446
d598032
 
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
"""Aged stock App: Amazon storage and long-term fees per SKU, the next surcharge tier, and one action per SKU.

Store documents (tenant runtime store, App owned, never the mirror and never Amazon):
  aged_stock_settings          {ads_from_days, price_down_from_days, remove_from_days, fee_horizon_days,
                                due_days, default_owner, fba_capacity (cubic feet)}
  aged_stock_items             {state, message, refreshedAt, notices, primaryCurrency, items: {id: item},
                                buckets: {current, previous} (planning snapshot bucket figures), last_error}
  aged_stock_history           {months: ["2026-10", ...]}  (the index of month documents)
  aged_stock_history_<YYYY-MM> {removals: {key: {snapshot: point}}, stranded: {key: {day: point}}}
  aged_stock_approval_<id>      one exact C3 approval and receipt, retained for reconciliation

Sources, read only from the tenant mirror: `amzn_storage_fees`, `amzn_long_term_storage_fees`,
`amzn_recommended_removals`, `amzn_stranded_inventory`, `amzn_inventory_planning` (and
`amzn_fba_inventory` for the FNSKU to SKU map only), plus the user table `ut_amazon_sku_profit` for
the unit margin. Removal and stranded reports keep one snapshot, so their history is this App's own.
Deleting this module and its documents (`remove_app_data`) leaves every connector table (rule 13).

Money is kept per currency and never added across currencies.

Limit (rule 1): each document is one JSON value, and the Postgres store refuses a document over
`core.store_pg.DOCUMENT_CEILING_BYTES` (128 MB). Nothing here caps SKUs, months, items or history.
"""
import base64
import contextlib
import datetime as dt
import hashlib
import json
import math
import re
import time
import uuid
from pathlib import Path

APP_LABEL = "Aged stock"
SOURCE_KIND = "aged_stock"
STATUSES = ("Open", "Accepted", "In progress", "Done", "Dismissed", "Watching")
REMOVE = "Remove"
PRICE_DOWN = "Price down"
ADS = "Push with ads"
ACTIONS = (REMOVE, PRICE_DOWN, ADS)
#: An item in one of these statuses reopens when its SKU gains a different recommended action.
REOPEN_FROM = ("Watching", "Done", "Dismissed")
DECISIONS = {"approved": "Accepted", "dismissed": "Dismissed"}
DEFAULTS = {"ads_from_days": 91, "price_down_from_days": 181, "remove_from_days": 271,
            "fee_horizon_days": 90, "due_days": 7}
NOT_READY = "The aged stock view starts after the next Amazon storage fee sync."
#: The App opened before any refresh: the summary read queued one, so the mirror is being read now.
READING = "Reading your Amazon storage fees now. The view fills in when they are read."
#: A queued or running refresh younger than this is kept, never queued twice.
REFRESH_HOLD_SECONDS = 600
LIMIT = ("Each aged stock document is limited to 128 MB by the store. About 40,000 SKUs with two years "
         "of monthly fees fit in the items document, and history splits by month. Split the items "
         "document by action when it nears that size.")
UNKNOWN_CURRENCY = "UNKNOWN"
MAX_PAGE_SIZE = 200
VOLUME_UNIT = "ft3"
VOLUME_SOURCES = {"unit": "amzn_storage_fees.item_volume", "fallback": "amzn_inventory_planning.item_volume",
                  "current": "amzn_inventory_planning.storage_volume"}

KEY_SETTINGS = "aged_stock_settings"
KEY_ITEMS = "aged_stock_items"
KEY_HISTORY = "aged_stock_history"
KEY_REFRESH = "aged_stock_refresh"
HISTORY_PREFIX = "aged_stock_history_"

STORAGE = "amzn_storage_fees"
LONG_TERM = "amzn_long_term_storage_fees"
REMOVALS = "amzn_recommended_removals"
STRANDED = "amzn_stranded_inventory"
PLANNING = "amzn_inventory_planning"
FBA_INVENTORY = "amzn_fba_inventory"
MARGIN_TABLE = "ut_amazon_sku_profit"
SOURCES = (STORAGE, LONG_TERM, REMOVALS, STRANDED, PLANNING)
SOURCE_NAMES = {STORAGE: "Amazon storage fees", LONG_TERM: "Amazon long term storage fees",
                REMOVALS: "Amazon recommended removals", STRANDED: "Amazon stranded inventory",
                PLANNING: "Amazon inventory planning"}
SYNC_TRIGGERS = tuple(t[len("amzn_"):] for t in SOURCES)

#: (column stem, label, youngest age in days) for the five age bands read from inventory planning.
BANDS = (("0_to_90", "0 to 90 days", 0), ("91_to_180", "91 to 180 days", 91),
         ("181_to_270", "181 to 270 days", 181), ("271_to_365", "271 to 365 days", 271),
         ("365_plus", "over 365 days", 366))
#: The next surcharge tiers in age order. `365_plus` is the coarse tier read only when 366 and up are blank.
TIERS = ("181_210", "211_240", "241_270", "271_300", "301_330", "331_365", "365_plus", "366_455", "456_plus")
FINE_FROM_366 = ("366_455", "456_plus")
#: The surcharge tiers each age bucket holds. The two youngest buckets carry no surcharge.
BUCKET_TIERS = {"181_to_270": ("181_210", "211_240", "241_270"),
                "271_to_365": ("271_300", "301_330", "331_365"),
                "365_plus": ("365_plus", "366_455", "456_plus")}
BUCKETS_UNAVAILABLE = "Amazon inventory age is unavailable."
BUCKET_MISMATCH = "This bucket does not match Amazon inventory planning."


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


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


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 {}


def _sql_scope(st):
    """Resolve the bound Postgres store and its tenant namespace without a default tenant."""
    from core import store_pg
    backend = st._document_store() if callable(getattr(st, "_document_store", None)) else st
    if not isinstance(backend, store_pg.PgStore):
        raise RuntimeError("The aged stock screen requires a store with server paging.")
    tenant = backend.tenant_slug
    if getattr(st, "key", tenant) != tenant:
        raise PermissionError("The aged stock store belongs to another tenant.")
    return store_pg, tenant, getattr(st, "store_key", str)


def _select(st, sql, params):
    """Read one bounded SQL result through the tenant store's checked pool."""
    from core import request_timing
    pg, tenant, key = _sql_scope(st)
    started = time.perf_counter()
    with pg._pool().connection() as con:
        row = con.execute(pg._q(sql, "store_kv", tenant), params(key)).fetchone()
    value = row[0] if row else None
    value = json.loads(value) if isinstance(value, str) else value
    request_timing.record_store("aged_stock_page", key(KEY_ITEMS), bytes_read=len(json.dumps(value).encode()),
                               milliseconds=(time.perf_counter() - started) * 1000)
    return value


def _paths(st, name, paths):
    """Read selected nested values without transferring their document."""
    pg, tenant, key = _sql_scope(st)
    return pg._get_json_paths(key(name), paths, tenant_slug=tenant)


def item_id_for(key):
    """A stable item id from the SKU (or the FNSKU when no SKU is known), so a refresh never duplicates."""
    return "as_" + hashlib.sha1(str(key).encode("utf-8")).hexdigest()[:10]


def _num(value):
    try:
        return None if value is None or str(value).strip() == "" else float(value)
    except (TypeError, ValueError):
        return None


def _text(value):
    text = None if value is None else str(value).strip()
    return text or None


def _nonnegative(value):
    number = _num(value)
    return number if number is not None and math.isfinite(number) and number >= 0 else None


def _volume(value, unit):
    """Convert a named cubic unit to cubic feet, leaving unrecognised units unknown."""
    name = re.sub(r"[\s_^-]+", "", str(unit or "").lower()).replace("³", "3")
    factor = {"ft3": 1.0, "cubicfeet": 1.0, "cubicfoot": 1.0, "cuft": 1.0,
              "m3": 35.31466672148859, "cubicmeters": 35.31466672148859,
              "cubicmetres": 35.31466672148859, "cubicmeter": 35.31466672148859,
              "cubicmetre": 35.31466672148859}.get(name)
    number = _nonnegative(value)
    result = number * factor if number is not None and factor is not None else None
    return result if result is not None and math.isfinite(result) else None


def _consistent_volume(values):
    """Keep one unit volume only when all observations agree after conversion."""
    if not values or any(value is None for value in values):
        return None
    return values[0] if all(math.isclose(value, values[0], rel_tol=1e-9, abs_tol=1e-9) for value in values) else None


def _fmt(value):
    number = float(value)
    return str(int(round(number))) if abs(number - round(number)) < 0.005 else f"{number:.2f}"


def _money(value, currency):
    if currency == "USD":
        return f"${float(value):,.2f}"
    return f"{currency} {float(value):,.2f}"


def _tier_label(tier):
    if tier.endswith("_plus"):
        return f"over {int(tier.split('_')[0]) - (0 if tier == '365_plus' else 1)} days"
    low, high = tier.split("_")
    return f"{low} to {high} days"


def _iso_date(value):
    """An ISO date from `MM/DD/YYYY` text or an ISO timestamp, else None."""
    text = _text(value)
    if not text:
        return None
    found = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{4})", text)
    try:
        if found:
            return dt.date(int(found.group(3)), int(found.group(1)), int(found.group(2))).isoformat()
        return dt.date.fromisoformat(text[:10]).isoformat()
    except ValueError:
        return None


# --------------------------------------------------------------------------- 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)


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


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


def _read_rows(cur, sql, params=(), size=200):
    """Consume background mirror reads in bounded batches."""
    result = cur.execute(sql, params)
    while True:
        rows = result.fetchmany(size)
        if not rows:
            return
        yield from rows


def _newest(cols, table):
    """A WHERE clause that keeps the newest `_snapshot_date` only, or every row without one."""
    if "_snapshot_date" not in cols:
        return "TRUE"
    return (f'CAST("_snapshot_date" AS VARCHAR) = '
            f'(SELECT MAX(CAST("_snapshot_date" AS VARCHAR)) FROM {table})')


def _col(cols, name):
    """A column as trimmed text, NULL when blank or absent."""
    return f'NULLIF(TRIM(CAST("{name}" AS VARCHAR)), \'\')' if name in cols else "NULL"


def _dbl(cols, name):
    return f'TRY_CAST("{name}" AS DOUBLE)' if name in cols else "NULL"


def _first_of(cols, names, width):
    """The first non-blank of several text columns, cut to `width` characters."""
    parts = [f'NULLIF(LEFT(TRIM(CAST("{n}" AS VARCHAR)), {width}), \'\')' for n in names if n in cols]
    if not parts:
        return "NULL"
    return parts[0] if len(parts) == 1 else f"COALESCE({', '.join(parts)})"


def _currency_sql(cols):
    return f"COALESCE({_col(cols, 'currency')}, '{UNKNOWN_CURRENCY}')"


def storage_month_sql(cols):
    """The month of a storage fee row: `month`, else `month_of_charge`, as `YYYY-MM`."""
    return _first_of(cols, ("month", "month_of_charge"), 7)


def long_term_month_sql(cols):
    """The month of a long-term charge: the first 7 characters of `snapshot_date`, else `_period_start`."""
    return _first_of(cols, ("snapshot_date", "_period_start"), 7)


def _fnsku_map(cur):
    """{fnsku: sku}, first match in order: planning, long-term fees, removals, stranded, FBA inventory."""
    out = {}
    for table, sku_col, fn_col in ((PLANNING, "sku", "fnsku"), (LONG_TERM, "sku", "fnsku"),
                                   (REMOVALS, "sku", "fnsku"), (STRANDED, "sku", "fnsku"),
                                   (FBA_INVENTORY, "seller_sku", "fn_sku")):
        cols = _columns(cur, table)
        if not {sku_col, fn_col} <= cols:
            continue
        rows = _read_rows(cur, f"SELECT {_col(cols, fn_col)}, MIN({_col(cols, sku_col)}) FROM {table} "
                           f"WHERE {_col(cols, fn_col)} IS NOT NULL AND {_col(cols, sku_col)} IS NOT NULL "
                           f"GROUP BY 1")
        for fnsku, sku in rows:
            out.setdefault(fnsku, sku)
    return out


def _storage(cur):
    """[(month, fnsku, asin, title, currency, fee, rows)], or None when the table is absent."""
    cols = _columns(cur, STORAGE)
    if "estimated_monthly_storage_fee" not in cols:
        return None
    sql = (f"SELECT {storage_month_sql(cols)}, {_col(cols, 'fnsku')}, {_col(cols, 'asin')}, "
           f"MAX({_col(cols, 'product_name')}), {_currency_sql(cols)}, "
           f"SUM({_dbl(cols, 'estimated_monthly_storage_fee')}), COUNT(*) FROM {STORAGE} GROUP BY 1, 2, 3, 5")
    return _read_rows(cur, sql)


def _storage_unit_volumes(cur):
    """Read per-unit volume from the latest fee month, without summing months or fulfilment centres."""
    cols = _columns(cur, STORAGE)
    if not {"item_volume", "volume_units"} <= cols:
        return {}
    sql = (f"SELECT {storage_month_sql(cols)}, {_col(cols, 'fnsku')}, {_col(cols, 'asin')}, "
           f"{_dbl(cols, 'item_volume')}, {_col(cols, 'volume_units')} FROM {STORAGE}")
    latest = {}
    for month, fnsku, asin, value, unit in _read_rows(cur, sql):
        key = fnsku or asin
        if not key:
            continue
        month = month or ""
        if key not in latest or month > latest[key][0]:
            latest[key] = (month, [])
        if month == latest[key][0]:
            latest[key][1].append(_volume(value, unit))
    return {key: _consistent_volume(values) for key, (_month, values) in latest.items()}


def _long_term(cur):
    """[(month, sku, fnsku, asin, title, currency, tier, amount, qty, rows)], or None when absent."""
    cols = _columns(cur, LONG_TERM)
    if "amount_charged" not in cols:
        return None
    sql = (f"SELECT {long_term_month_sql(cols)}, {_col(cols, 'sku')}, {_col(cols, 'fnsku')}, "
           f"{_col(cols, 'asin')}, MAX({_col(cols, 'product_name')}), {_currency_sql(cols)}, "
           f"{_col(cols, 'surcharge_age_tier')}, SUM({_dbl(cols, 'amount_charged')}), "
           f"SUM({_dbl(cols, 'qty_charged')}), COUNT(*) FROM {LONG_TERM} GROUP BY 1, 2, 3, 4, 6, 7")
    return _read_rows(cur, sql)


def _removals(cur):
    """Read removal snapshots with known sellable quantities and their marketplace scope."""
    cols = _columns(cur, REMOVALS)
    if not cols & {"sku", "fnsku"}:
        return None
    market = next((c for c in ("marketplace_id", "marketplaceId", "_marketplace_id") if c in cols), None)
    scope = _col(cols, market) if market else "NULL"
    valid = f"isfinite({_dbl(cols, 'sellable_quantity')}) AND {_dbl(cols, 'sellable_quantity')} >= 0 " \
            f"AND floor({_dbl(cols, 'sellable_quantity')}) = {_dbl(cols, 'sellable_quantity')}"
    sql = (f"SELECT {_first_of(cols, ('snapshot_date', '_snapshot_date'), 10)}, {_col(cols, 'sku')}, "
           f"{_col(cols, 'fnsku')}, {_col(cols, 'asin')}, MAX({_col(cols, 'product_name')}), "
           f"CASE WHEN COUNT(*) = COUNT(*) FILTER (WHERE {valid}) "
           f"THEN SUM({_dbl(cols, 'sellable_quantity')}) END, SUM({_dbl(cols, 'sellable_removal_quantity')}), "
           f"SUM({_dbl(cols, 'unsellable_quantity')}), CASE WHEN COUNT(DISTINCT {scope}) = 1 "
           f"AND COUNT(*) = COUNT({scope}) THEN MIN({scope}) END FROM {REMOVALS} GROUP BY 1, 2, 3, 4")
    return _read_rows(cur, sql)


def _sellable_stock(cur, sku):
    """Read current sellable stock for one SKU with an explicit, single marketplace."""
    cols = _columns(cur, REMOVALS)
    market = next((c for c in ("marketplace_id", "marketplaceId", "_marketplace_id") if c in cols), None)
    if (not {"sku", "sellable_quantity"} <= cols or not market
            or not cols & {"_snapshot_date", "snapshot_date"}):
        raise ValueError("Sellable stock needs its marketplace id. Sync a marketplace-scoped removal report, then reload.")
    rows = list(_read_rows(cur, f"SELECT {_col(cols, market)}, {_dbl(cols, 'sellable_quantity')} "
                           f"FROM {REMOVALS} WHERE {_newest(cols, REMOVALS)} AND {_col(cols, 'sku')} = ?", [sku]))
    markets = {m for m, _q in rows}
    if len(markets) != 1 or None in markets:
        raise ValueError("Sellable stock has missing or multiple marketplaces. Sync one marketplace for this SKU, then reload.")
    quantities = [_nonnegative(q) for _m, q in rows]
    if not quantities or any(q is None or q != int(q) for q in quantities):
        raise ValueError("Current sellable stock is missing or ambiguous. Sync the removal report, then reload.")
    return {"marketplace": markets.pop(), "sellable": int(sum(quantities))}


STRANDED_COLS = ("sku", "fnsku", "asin", "product_name", "stranded_reason", "primary_action", "fulfillable_qty",
                 "unfulfillable_qty", "reserved_quantity", "date_stranded", "date_to_take_auto_removal",
                 "your_price")


def _stranded(cur):
    """[row dict] from the newest stranded snapshot, or None when the table is absent."""
    cols = _columns(cur, STRANDED)
    if not cols & {"sku", "fnsku"}:
        return None
    sql = (f"SELECT {', '.join(_col(cols, c) for c in STRANDED_COLS)} FROM {STRANDED} "
           f"WHERE {_newest(cols, STRANDED)}")
    return (dict(zip(STRANDED_COLS, r)) for r in _read_rows(cur, sql))


PLANNING_COLS = (("sku", "fnsku", "asin", "product_name", "currency", "recommended_action")
                 + tuple(f"inv_age_{b}_days" for b, _l, _d in BANDS)
                 + ("inv_age_366_to_455_days", "inv_age_456_plus_days")
                 + tuple(f"{p}_{t}_days" for t in TIERS for p in ("quantity_to_be_charged_ais", "estimated_ais"))
                 + ("estimated_storage_cost_next_month", "inventory_supply_at_fba", "available",
                    "recommended_removal_quantity", "recommended_sales_price", "your_price",
                    "item_volume", "storage_volume", "volume_unit_measurement"))


def _planning(cur):
    """{sku: planning values} from the newest snapshot, summed per SKU; None when the table is absent."""
    cols = _columns(cur, PLANNING)
    if "sku" not in cols:
        return None
    sql = (f"SELECT {', '.join(_col(cols, c) for c in PLANNING_COLS)} FROM {PLANNING} "
           f"WHERE {_newest(cols, PLANNING)} AND {_col(cols, 'sku')} IS NOT NULL")
    out = {}
    for raw in _read_rows(cur, sql):
        r = dict(zip(PLANNING_COLS, raw))
        p = out.setdefault(r["sku"], {"bands": {b: None for b, _l, _d in BANDS}, "tiers": {},
                                      "nums": {}, "text": {}, "unit_volumes": [], "storage_volumes": []})
        p["unit_volumes"].append(_volume(r["item_volume"], r["volume_unit_measurement"]))
        p["storage_volumes"].append(_volume(r["storage_volume"], r["volume_unit_measurement"]))
        for key in ("fnsku", "asin", "product_name", "currency", "recommended_action"):
            p["text"].setdefault(key, None)
            p["text"][key] = p["text"][key] or r[key]
        for stem, _label, _days in BANDS:
            value = _num(r[f"inv_age_{stem}_days"])
            if stem == "365_plus" and value is None:
                parts = [_num(r["inv_age_366_to_455_days"]), _num(r["inv_age_456_plus_days"])]
                value = None if all(v is None for v in parts) else sum(v or 0 for v in parts)
            if value is not None:
                p["bands"][stem] = (p["bands"][stem] or 0) + value
        fine_blank = all(_num(r[f"{pre}_{t}_days"]) is None for t in FINE_FROM_366
                         for pre in ("quantity_to_be_charged_ais", "estimated_ais"))
        for tier in TIERS:
            if tier == "365_plus" and not fine_blank:
                continue
            qty, est = _num(r[f"quantity_to_be_charged_ais_{tier}_days"]), _num(r[f"estimated_ais_{tier}_days"])
            if qty is None and est is None:
                continue
            got = p["tiers"].setdefault(tier, [None, None])
            got[0] = None if qty is None and got[0] is None else (got[0] or 0) + (qty or 0)
            got[1] = None if est is None and got[1] is None else (got[1] or 0) + (est or 0)
        for key in ("estimated_storage_cost_next_month", "inventory_supply_at_fba", "available",
                    "recommended_removal_quantity"):
            value = _num(r[key])
            if value is not None:
                p["nums"][key] = (p["nums"].get(key) or 0) + value
        for key in ("recommended_sales_price", "your_price"):
            if p["nums"].get(key) is None:
                p["nums"][key] = _num(r[key])
    return out


def _bucket_fees(plan):
    """{bucket stem: Amazon's estimated surcharge} for one SKU's planning tiers; empty without a planning row."""
    if plan is None:
        return {}
    tiers = plan.get("tiers") or {}
    return {stem: sum((tiers[t][1] or 0) for t in names if t in tiers) for stem, names in BUCKET_TIERS.items()}


def _margins(st):
    """{sku: unit margin} from the user table, data only (no App code import). Unknown margins are absent."""
    from core import user_tables
    try:
        table = user_tables.get_one(MARGIN_TABLE, st) or {}
    except Exception:                                                  # noqa: BLE001
        table = {}
    rows = table.get("rows") or {}
    sums = {}
    for row in (rows.values() if isinstance(rows, dict) else rows):
        if not isinstance(row, dict):
            continue
        sku = str(row.get("sku") or "").strip()
        profit, units = _num(row.get("net_profit")), _num(row.get("units_sold"))
        if sku and profit is not None and units is not None:
            got = sums.setdefault(sku, [0.0, 0.0])
            got[0] += profit
            got[1] += units
    return {sku: profit / units for sku, (profit, units) in sums.items() if units > 0}


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

#: Accounts that sign in for a process, never a person who can own an item.
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):
    """P22: the tenant's earliest active person Administrator, else `admin`, 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):
    """The age thresholds, the fee horizon, the due window and the default owner, with defaults filled in."""
    st = _rt(tenant_key, st)
    doc = _doc(st, KEY_SETTINGS)
    owner_setting = doc.get("default_owner") or None
    return {"adsFromDays": int(doc.get("ads_from_days", DEFAULTS["ads_from_days"])),
            "priceDownFromDays": int(doc.get("price_down_from_days", DEFAULTS["price_down_from_days"])),
            "removeFromDays": int(doc.get("remove_from_days", DEFAULTS["remove_from_days"])),
            "feeHorizonDays": int(doc.get("fee_horizon_days", DEFAULTS["fee_horizon_days"])),
            "dueDays": int(doc.get("due_days", DEFAULTS["due_days"])),
            "defaultOwnerSetting": owner_setting,
            "defaultOwner": owner_setting or owner_account(st, tenant_key),
            "fbaCapacity": _nonnegative(doc.get("fba_capacity")), "volumeUnit": VOLUME_UNIT,
            "capacitySource": "Typed",
            "removalDisposition": doc.get("removal_disposition", "Return"),
            "shipTo": doc.get("ship_to") or {},
            "statuses": list(STATUSES), "actions": list(ACTIONS), "limit": LIMIT}


def _whole(value, low, high, message):
    number = _num(value)
    if number is None or number != int(number) or not low <= number <= high:
        raise ValueError(message)
    return int(number)


def set_settings(tenant_key, *, ads_from_days=None, price_down_from_days=None, remove_from_days=None,
                 fee_horizon_days=None, due_days=None, default_owner=None, fba_capacity=None,
                 ship_to=None, removal_disposition=None, st=None):
    """Set the age thresholds in days, the fee horizon, the due window, or the default owner ('' resets it)."""
    st = _rt(tenant_key, st)
    now = settings(tenant_key, st=st)
    changes = {}
    if ship_to is not None:
        changes["ship_to"] = _ship_to(ship_to)
    if removal_disposition is not None:
        if removal_disposition not in ("Return", "Disposal", "Liquidate"):
            raise ValueError("Choose Return, Disposal or Liquidate.")
        changes["removal_disposition"] = removal_disposition
    for name, value in (("ads_from_days", ads_from_days), ("price_down_from_days", price_down_from_days),
                        ("remove_from_days", remove_from_days)):
        if value is not None:
            changes[name] = _whole(value, 1, 3650, "An age threshold must be a whole number of days from 1 to 3650.")
    ads = changes.get("ads_from_days", now["adsFromDays"])
    price = changes.get("price_down_from_days", now["priceDownFromDays"])
    remove = changes.get("remove_from_days", now["removeFromDays"])
    if not ads < price < remove:
        raise ValueError("The thresholds must rise: push with ads, then price down, then remove.")
    if fee_horizon_days is not None:
        changes["fee_horizon_days"] = _whole(fee_horizon_days, 1, 365,
                                             "The fee horizon must be a whole number of days from 1 to 365.")
    if due_days is not None:
        changes["due_days"] = _whole(due_days, 1, 365, "Days to act must be a whole number from 1 to 365.")
    if fba_capacity is not None:
        capacity = None if fba_capacity == "" else _nonnegative(fba_capacity)
        if fba_capacity != "" and (capacity is None or isinstance(fba_capacity, bool)):
            raise ValueError("FBA capacity must be a non-negative number of cubic feet.")
        changes["fba_capacity"] = capacity

    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)


# --------------------------------------------------------------------------- the row builder

def _tier_rank(tier):
    found = re.match(r"\d+", str(tier or ""))
    return (int(found.group(0)) if found else -1, str(tier or ""))


def _recommend(row, conf):
    """(recommended action or None, reason, fee per unit or None) for one SKU row under the settings."""
    units = row["units"]
    if units is None:
        return None, "Amazon inventory planning has no units for this SKU, so no action.", None
    if units <= 0:
        return None, "No units at Amazon, so no action.", None
    oldest = None
    for stem, label, days in BANDS:
        if (row["age_bands"].get(stem) or 0) > 0:
            oldest = (label, days)
    head = f"{_fmt(units)} units at Amazon"
    age_action = None
    if oldest is None:
        head += ", with no inventory age reported."
    else:
        head += f", the oldest {oldest[0]} old."
        if oldest[1] >= conf["removeFromDays"]:
            age_action = REMOVE
        elif oldest[1] >= conf["priceDownFromDays"]:
            age_action = PRICE_DOWN
        elif oldest[1] >= conf["adsFromDays"]:
            age_action = ADS
    margin, cur = row["unit_margin"], row["currency"]
    per_unit = None
    if margin is not None:
        stake = row["at_stake"].get(cur) or 0
        per_unit = conf["feeHorizonDays"] / 30.0 * ((row["storage_next_month"] or 0) + stake) / units
    if per_unit is not None and per_unit > 0 and per_unit > margin and age_action != REMOVE:
        return REMOVE, (f"{head} {conf['feeHorizonDays']} days of storage fees cost {_money(per_unit, cur)} "
                        f"per unit, over the unit margin of {_money(margin, cur)}."), per_unit
    rule = {REMOVE: f"Remove at {conf['removeFromDays']} days or older.",
            PRICE_DOWN: f"Lower the price at {conf['priceDownFromDays']} days or older.",
            ADS: f"Push with ads at {conf['adsFromDays']} days or older."}
    if age_action is None:
        return None, f"{head} No action under {conf['adsFromDays']} days.", per_unit
    return age_action, f"{head} {rule[age_action]}", per_unit


def _proposal_units(item):
    """Use the removal proposal's quantity, or all reported units for a price reduction."""
    if item.get("action") == REMOVE:
        sellable = _nonnegative((item.get("removal") or {}).get("sellable_quantity"))
        if sellable is None or sellable != int(sellable):
            return None
        for value in ((item.get("removal") or {}).get("sellable_removal_quantity"),
                      item.get("recommended_removal_quantity"), sellable):
            number = _nonnegative(value)
            if number is not None and number > 0 and number == int(number):
                return int(min(number, sellable))
    if item.get("action") == PRICE_DOWN:
        return _nonnegative(item.get("units"))
    return None


def _volume_fields(item):
    """Keep each proposal's volume consistent with its current authored action."""
    units, volume = _proposal_units(item), _nonnegative(item.get("unit_volume"))
    freed = volume * units if volume is not None and units is not None else None
    return {"proposal_units": units, "volume_freed": freed if freed is not None and math.isfinite(freed) else None}


def build_rows(cur, margins, conf):
    """(rows, notices, primary currency): one row per SKU in any source, or (None, notices, None) when none synced."""
    planning, storage, long_term = _planning(cur), _storage(cur), _long_term(cur)
    removals, stranded = _removals(cur), _stranded(cur)
    got = {PLANNING: planning, STORAGE: storage, LONG_TERM: long_term, REMOVALS: removals, STRANDED: stranded}
    notices = [f"{SOURCE_NAMES[t]} has not synced yet." for t in SOURCES if got[t] is None]
    if all(v is None for v in got.values()):
        return None, notices, None
    fmap = _fnsku_map(cur)
    storage_volumes = _storage_unit_volumes(cur)
    rows = {}
    counts = {}

    def row_for(sku, fnsku, asin=None, title=None):
        sku = sku or fmap.get(fnsku)
        key = sku or fnsku or asin or "Unidentified"
        row = rows.get(key)
        if row is None:
            row = rows[key] = {"key": key, "sku": sku, "fnsku": fnsku, "asin": asin, "title": title,
                               "_fees": {}, "_lt": {}, "_cur": {}}
        row["fnsku"] = row["fnsku"] or fnsku
        row["asin"] = row["asin"] or asin
        row["title"] = row["title"] or title
        return row

    for sku, p in (planning or {}).items():
        t = p["text"]
        row = row_for(sku, t["fnsku"], t["asin"], t["product_name"])
        row["_plan"] = p
    for source_key, volume in storage_volumes.items():
        row = row_for(None, source_key) if source_key in fmap else None
        if row is not None:
            row.setdefault("_unit_volumes", []).append(volume)
    for month, fnsku, asin, title, cur, fee, n in storage or ():
        row = row_for(None, fnsku, asin, title)
        point = row["_fees"].setdefault((month or "", cur), {"storage": 0.0, "long_term": 0.0, "tier": None,
                                                              "units": None})
        point["storage"] += fee or 0.0
        row["_cur"][cur] = row["_cur"].get(cur, 0) + n
        counts[cur] = counts.get(cur, 0) + n
    for month, sku, fnsku, asin, title, cur, tier, amount, qty, n in long_term or ():
        row = row_for(sku, fnsku, asin, title)
        point = row["_fees"].setdefault((month or "", cur), {"storage": 0.0, "long_term": 0.0, "tier": None,
                                                              "units": None})
        point["long_term"] += amount or 0.0
        if qty is not None:
            point["units"] = (point["units"] or 0) + qty
        if tier and _tier_rank(tier) > _tier_rank(point["tier"]):
            point["tier"] = tier
        row["_cur"][cur] = row["_cur"].get(cur, 0) + n
        counts[cur] = counts.get(cur, 0) + n
    snapshots = {}
    for snap, sku, fnsku, asin, title, sellable, removal, unsellable, marketplace in removals or ():
        row = row_for(sku, fnsku, asin, title)
        point = snapshots.setdefault(row["key"], {}).setdefault(
            snap or "", {"sellable_quantity": 0.0, "sellable_removal_quantity": 0.0, "unsellable_quantity": 0.0,
                         "marketplace_id": marketplace})
        if not marketplace or point["marketplace_id"] != marketplace:
            point["sellable_quantity"], point["marketplace_id"] = None, None
        point["sellable_quantity"] = (point["sellable_quantity"] + sellable
                                      if point["sellable_quantity"] is not None and sellable is not None else None)
        point["sellable_removal_quantity"] += removal or 0
        point["unsellable_quantity"] += unsellable or 0
    for r in stranded or ():
        row = row_for(r["sku"], r["fnsku"], r["asin"], r["product_name"])
        s = row.setdefault("stranded", {"reasons": [], "primary_actions": [], "fulfillable": 0.0,
                                        "unfulfillable": 0.0, "reserved": 0.0, "units": 0.0,
                                        "date_stranded": None, "auto_removal_date": None})
        for key, src in (("reasons", "stranded_reason"), ("primary_actions", "primary_action")):
            if r[src] and r[src] not in s[key]:
                s[key].append(r[src])
        for key, src in (("fulfillable", "fulfillable_qty"), ("unfulfillable", "unfulfillable_qty"),
                         ("reserved", "reserved_quantity")):
            s[key] += _num(r[src]) or 0
        s["units"] = s["fulfillable"] + s["unfulfillable"]
        for key, src in (("date_stranded", "date_stranded"), ("auto_removal_date", "date_to_take_auto_removal")):
            day = _iso_date(r[src])
            if day and (s[key] is None or day < s[key]):
                s[key] = day
    primary = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] if counts else None

    out = []
    for key in sorted(rows):
        row = rows.pop(key)
        p = row.pop("_plan", None)
        fees, seen = row.pop("_fees"), row.pop("_cur")
        plan_cur = (p or {}).get("text", {}).get("currency")
        cur = plan_cur or (sorted(seen.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] if seen else None) \
            or primary or UNKNOWN_CURRENCY
        history = [{"month": m, "currency": c, **v} for (m, c), v in sorted(fees.items())]
        totals = {}
        for point in history:
            t = totals.setdefault(point["currency"], {"storage": 0.0, "long_term": 0.0, "total": 0.0})
            t["storage"] += point["storage"]
            t["long_term"] += point["long_term"]
            t["total"] += point["storage"] + point["long_term"]
        charged = [pt for pt in history if pt["long_term"] or pt["tier"]]
        nums = (p or {}).get("nums", {})
        fee_volumes = row.pop("_unit_volumes", [])
        if not fee_volumes:
            fee_volumes = [storage_volumes[k] for k in (row["fnsku"], row["asin"]) if k in storage_volumes]
        plan_volumes = (p or {}).get("unit_volumes", [])
        unit_volume = _consistent_volume(fee_volumes)
        unit_source = VOLUME_SOURCES["unit"] if unit_volume is not None else None
        if unit_volume is None:
            unit_volume = _consistent_volume(plan_volumes)
            unit_source = VOLUME_SOURCES["fallback"] if unit_volume is not None else None
        storage_parts = (p or {}).get("storage_volumes", [])
        storage_volume = _nonnegative(sum(storage_parts)) if storage_parts and all(v is not None for v in storage_parts) else None
        bands = dict((p or {}).get("bands") or {b: None for b, _l, _d in BANDS})
        units = nums.get("inventory_supply_at_fba")
        if units is None:
            units = nums.get("available")
        if units is None and p is not None and any(v is not None for v in bands.values()):
            units = sum(v or 0 for v in bands.values())
        next_tier = None
        tiers = [(t, q, e) for t, (q, e) in ((p or {}).get("tiers") or {}).items() if q and q > 0]
        if tiers:
            tiers.sort(key=lambda x: TIERS.index(x[0]))
            estimates = [e for _t, _q, e in tiers if e is not None]
            next_tier = {"tier": _tier_label(tiers[-1][0]), "units": sum(q for _t, q, _e in tiers),
                         "at_stake": sum(estimates) if estimates else None, "currency": cur,
                         "last_charged_tier": charged[-1]["tier"] if charged else None}
        snaps = snapshots.get(key) or {}
        newest = max(snaps) if snaps else None
        row.update({
            "title": row["title"] or row["sku"] or row["fnsku"] or key, "currency": cur, "units": units,
            "age_bands": bands, "age_fees": _bucket_fees(p), "fee_history": history, "fees": totals, "next_tier": next_tier,
            "at_stake": ({cur: next_tier["at_stake"]} if next_tier and next_tier["at_stake"] is not None else {}),
            "storage_next_month": nums.get("estimated_storage_cost_next_month"),
            "unit_margin": margins.get(row["sku"]) if row["sku"] else None,
            "amazon_action": (p or {}).get("text", {}).get("recommended_action"),
            "recommended_removal_quantity": nums.get("recommended_removal_quantity"),
            "recommended_sales_price": nums.get("recommended_sales_price"),
            "your_price": nums.get("your_price"),
            "unit_volume": unit_volume, "unit_volume_source": unit_source, "volume_unit": VOLUME_UNIT,
            "storage_volume": storage_volume,
            "storage_volume_source": VOLUME_SOURCES["current"] if p is not None else None,
            "removal": {"snapshot": newest or None, **snaps[newest]} if newest is not None else None,
            "stranded": row.get("stranded"),
            "_removal_points": snaps})
        row["recommended_action"], row["reason"], row["fee_per_unit"] = _recommend(row, conf)
        row.update(_volume_fields({**row, "action": row["recommended_action"]}))
        if row["stranded"]:
            s = row["stranded"]
            row["reason"] += f" {_fmt(s['units'])} units are stranded"
            row["reason"] += (f": {', '.join(s['reasons'])}." if s["reasons"] else ".")
        out.append(row)
    return out, notices, primary


# --------------------------------------------------------------------------- module table (C4)

TABLE_KEY = "ut_amazon_aged_stock"
TABLE_LABEL = "Aged stock"
TABLE_SOURCES = tuple("ut_" + t for t in SOURCES)
TABLE_WRITER = "automation"
TABLE_VIA = "aged_stock"
#: People edit these in the Grid. The refresh never writes them.
OWNED_KEYS = ("action", "proposed_price")


def _register_table():
    """The table is the module's, not a person's, so it takes no MAX_TABLES slot."""
    from core import user_tables
    user_tables.register_module_tables(TABLE_KEY)


_register_table()


def _module_tables():
    """The shared module table helper of contract C4, imported on first use."""
    from core import module_tables
    return module_tables


def band_column(stem):
    return "age_" + stem


def _table_field(key, label, ftype, description, *, owned=False, **extra):
    out = {"key": key, "label": label, "type": ftype, "origin": "loopable",
           "valueAuthority": "user-entered" if owned else "computed", "scope": "tenant",
           "description": description, "editRole": "admins"}
    if ftype == "currency":
        out["format"] = {"decimals": 2}
    out.update(extra)
    if not owned:
        out["automation"] = {"preset": True, "flowId": TABLE_VIA}
    return out


def table_fields():
    """The declared columns of the aged stock table. `BANDS` builds one int column per age bucket."""
    bands = tuple(_table_field(band_column(stem), label[:1].upper() + label[1:], "int", f"Units aged {label}.")
                  for stem, label, _days in BANDS)
    return [
        _table_field("product", "Product", "text", "Listing title.",
                     format={"display": "product", "pictureKey": "picture", "subKey": "sku"}),
        _table_field("sku", "SKU", "text", "Amazon seller SKU."),
        _table_field("asin", "ASIN", "text", "Amazon product id."),
        _table_field("picture", "Picture", "image", "Main Amazon listing picture."),
        *bands,
        _table_field("units", "Units", "int", "Units at Amazon."),
        _table_field("monthly_fee", "Monthly fee", "currency", "Estimated storage fee next month."),
        _table_field("currency", "Currency", "text", "Currency of the fees."),
        _table_field("next_tier", "Next tier", "text", "Next aged surcharge tier."),
        _table_field("at_stake", "At stake", "currency", "Surcharge at the next tier."),
        _table_field("recommended_action", "Recommended", "select", "From Amazon removals and the App rule.",
                     options=list(ACTIONS)),
        _table_field("reason", "Reason", "text", "Why this action."),
        _table_field("status", "Status", "select", "Where the action stands.", options=list(STATUSES)),
        _table_field("owner", "Owner", "text", "Who owns the action."),
        _table_field("due", "Due date", "date", "When the action is due."),
        _table_field("item_id", "Item", "text", "Aged stock item id."),
        _table_field("action", "Action", "select", "The action you chose.", owned=True, options=list(ACTIONS)),
        _table_field("proposed_price", "Proposed price", "currency", "The price you propose.", owned=True),
    ]


def _whole_units(value):
    number = _num(value)
    return int(round(number)) if number is not None and math.isfinite(number) else None


def table_row(item, pictures=None):
    """The computed cells of one item. An item out of the report keeps its row with no bucket units."""
    key = str(item.get("key") or "")
    live = item.get("inReport") is not False
    bands = item.get("age_bands") if isinstance(item.get("age_bands"), dict) else {}
    tier = item.get("next_tier") if isinstance(item.get("next_tier"), dict) else {}
    asin = _text(item.get("asin"))
    rec, status = item.get("recommended_action"), item.get("status")
    row = {"product": item.get("title") or key, "sku": key, "asin": asin,
           "picture": (pictures or {}).get(asin) if asin else None}
    for stem, _label, _days in BANDS:
        row[band_column(stem)] = _whole_units(bands.get(stem)) if live else None
    row.update(units=_whole_units(item.get("units")), monthly_fee=_num(item.get("storage_next_month")),
               currency=_text(item.get("currency")), next_tier=_text(tier.get("tier")),
               at_stake=_num(tier.get("at_stake")), recommended_action=rec if rec in ACTIONS else None,
               reason=_text(item.get("reason")), status=status if status in STATUSES else None,
               owner=_text(item.get("owner")), due=_text(item.get("due")), item_id=item_id_for(key))
    return row


def _pictures(st):
    try:
        from harness import amazon_pictures
        return amazon_pictures.picture_refs(st) or {}
    except Exception:                                                  # noqa: BLE001
        return {}


def table_limit_message(limit, count):
    return (f"The aged stock table holds at most {limit:,} rows and Amazon has {count:,} SKUs, so the table "
            "was not written. Fix: ask support to serve this table from the Amazon mirror, which has no row cap. "
            "The aged stock list still shows every SKU.")


def write_table(st, items):
    """Write one row per item to the aged stock table. Returns {rows} or {refused}. Never raises."""
    from core import user_tables
    computed = {}
    pictures = _pictures(st)
    for item in (items or {}).values():
        row = table_row(item, pictures) if isinstance(item, dict) else None
        if row and row["sku"]:
            computed[row["sku"]] = row
    count = len(computed)
    try:
        # Rule 1: the refusal names the count and the fix, whatever the helper does.
        limit = user_tables.row_limit(TABLE_KEY, st)
        if limit and count > limit:
            return {"refused": table_limit_message(limit, count), "rows": count, "limit": limit}
        helper = _module_tables()
        helper.ensure_module_table(st, TABLE_WRITER, table_key=TABLE_KEY, label=TABLE_LABEL, fields=table_fields(),
                                   owned_keys=OWNED_KEYS, sources=TABLE_SOURCES)
        helper.ensure_everyone_grant(st, [TABLE_KEY])
        written = helper.write_module_rows(st, computed, table_key=TABLE_KEY, key_column="sku", label=TABLE_LABEL)
    except Exception as exc:                                           # noqa: BLE001
        return {"refused": f"The aged stock table was not written ({type(exc).__name__}): {exc}", "rows": count}
    return {"rows": count, **(written if isinstance(written, dict) else {})}


# --------------------------------------------------------------------------- refresh and history

def _month_key(month):
    return HISTORY_PREFIX + month


def refresh(tenant_key, *, st=None, now=None):
    """Compute every SKU row from the mirror, write removal and stranded history, and merge items."""
    st = _rt(tenant_key, st)
    _apply_grid(tenant_key, st)
    now = now or _now()
    conf = settings(tenant_key, st=st)
    margins = _margins(st)
    snapshots = None
    with _reader(tenant_key, st) as cur:
        if cur is None:
            rows, notices, primary = None, ["The tenant mirror does not exist yet."], None
        else:
            rows, notices, primary = build_rows(cur, margins, conf)
            snapshots = bucket_snapshots(cur, primary) if rows is not None else None
    if rows is None:
        message = notices[0] if notices else NOT_READY

        def _waiting(doc):
            doc = doc if isinstance(doc, dict) else {}
            doc.update(state="not_ready", message=message, notices=notices, checkedAt=_stamp(now))
            doc.pop("last_error", None)
            return doc
        st.update(KEY_ITEMS, _waiting)
        return {"state": "not_ready", "message": message, "notices": notices}

    day = now.date().isoformat()
    by_month = {}
    for row in rows:
        for snap, point in row.pop("_removal_points").items():
            if snap:
                by_month.setdefault(snap[:7], {"removals": {}, "stranded": {}})["removals"].setdefault(
                    row["key"], {})[snap] = point
        by_month.setdefault(day[:7], {"removals": {}, "stranded": {}})["stranded"][row["key"]] = {
            day: {"units": (row["stranded"] or {}).get("units", 0.0), "at_stake": row["at_stake"]}}
    for month, adds in by_month.items():
        def _history(doc, adds=adds):
            doc = doc if isinstance(doc, dict) else {}
            for kind in ("removals", "stranded"):
                bucket = doc.setdefault(kind, {})
                for key, points in adds[kind].items():
                    bucket.setdefault(key, {}).update(points)
            return doc
        st.update(_month_key(month), _history)

    def _index(doc):
        doc = doc if isinstance(doc, dict) else {}
        doc["months"] = sorted(set(doc.get("months") or ()) | set(by_month))
        return doc
    st.update(KEY_HISTORY, _index)

    owner = conf["defaultOwner"]
    due = (now.date() + dt.timedelta(days=conf["dueDays"])).isoformat()
    counts = {"created": 0, "reopened": 0}
    merged = {}

    def _items(doc):
        doc = doc if isinstance(doc, dict) else {}
        items = doc.setdefault("items", {})
        merged["items"] = items
        seen = set()
        for row in rows:
            iid = item_id_for(row["key"])
            seen.add(iid)
            old = items.get(iid)
            rec = row["recommended_action"]
            if old is None:
                item = {"id": iid, "owner": owner, "status": "Open" if rec else "Watching",
                        "due": due if rec else None, "action": rec, "createdAt": _stamp(now),
                        "history": [{"at": _stamp(now), "by": "system", "event": "created",
                                     "recommended_action": rec}]}
                counts["created"] += 1
            else:
                item = old
                if rec and rec != old.get("recommended_action") and old.get("status") in REOPEN_FROM:
                    item["status"], item["due"] = "Open", due
                    item.setdefault("history", []).append(
                        {"at": _stamp(now), "by": "system", "event": "reopened", "recommended_action": rec,
                         "status": "Open", "due": due})
                    counts["reopened"] += 1
                # The action follows the recommendation until a person chooses one.
                if not item.get("actionChosenBy"):
                    item["action"] = rec
            item.update(row)
            item.update(_volume_fields(item))
            item["inReport"] = True
            item["refreshedAt"] = _stamp(now)
            items[iid] = item
        for iid, item in items.items():
            if iid not in seen:
                item["inReport"] = False
        # The newest and the previous planning snapshot's bucket figures: the tiles' change compares them.
        doc["buckets"] = snapshots
        doc.update(state="ready", message=None, notices=notices, primaryCurrency=primary,
                   refreshedAt=_stamp(now), storageVolumeReady=f"{SOURCE_NAMES[PLANNING]} has not synced yet." not in notices)
        doc.pop("last_error", None)
        return doc
    st.update(KEY_ITEMS, _items)
    # The table follows the merged items, so people's status and chosen action reach it.
    table = write_table(st, merged.get("items"))

    def _table_note(doc):
        doc = doc if isinstance(doc, dict) else {}
        if table.get("refused"):
            doc["tableError"] = table["refused"]
        else:
            doc.pop("tableError", None)
        return doc
    try:
        st.update(KEY_ITEMS, _table_note)
    except Exception:                                                  # noqa: BLE001
        pass
    return {"state": "ready", "skus": len(rows), "notices": notices, **counts, "table": table}


def _short(name):
    name = str(name or "").strip().lower()
    for prefix in ("ut_", "amzn_"):
        if name.startswith(prefix):
            name = name[len(prefix):]
    return name


def on_amazon_sync(tenant_key, synced_tables):
    """Contract C5 callback: refresh when a fee, removal, stranded or planning report synced. Never raises."""
    try:
        names = {_short(t) for t in (synced_tables or ())}
    except Exception:                                                  # noqa: BLE001
        return
    if not names & set(SYNC_TRIGGERS):
        return
    try:
        refresh(tenant_key)
    except Exception as exc:                                           # noqa: BLE001
        try:
            def _note(doc):
                doc = doc if isinstance(doc, dict) else {}
                doc["last_error"] = f"The aged stock refresh failed ({type(exc).__name__}): {exc}"
                return doc
            _rt(tenant_key).update(KEY_ITEMS, _note)
        except Exception:                                              # noqa: BLE001
            pass


def history(tenant_key, key, *, st=None):
    """{removals, stranded}: every stored point for one SKU key, oldest first."""
    st = _rt(tenant_key, st)
    out = {"removals": [], "stranded": []}
    for month in _doc(st, KEY_HISTORY).get("months") or ():
        selected = _paths(st, _month_key(month), [(kind, key) for kind in out])
        for (kind, field), points in zip((("removals", "snapshot"), ("stranded", "date")), selected):
            for at, point in (points or {}).items():
                out[kind].append({field: at, **point})
    out["removals"].sort(key=lambda p: p["snapshot"])
    out["stranded"].sort(key=lambda p: p["date"])
    return out


# --------------------------------------------------------------------------- summary

SUMMARY_SQL = """
WITH doc AS MATERIALIZED (SELECT value FROM {tbl} WHERE key = %s),
live AS MATERIALIZED (
    SELECT e.value AS v FROM doc, LATERAL jsonb_each(COALESCE(doc.value->'items', '{{}}'::jsonb)) e
    WHERE COALESCE(e.value->>'inReport', 'true') <> 'false'
), trend AS MATERIALIZED (
    SELECT p.value->>'currency' AS currency, p.value->>'month' AS month,
        SUM(CAST(p.value->>'storage' AS DOUBLE PRECISION)) AS storage,
        SUM(CAST(p.value->>'long_term' AS DOUBLE PRECISION)) AS long_term
    FROM live, LATERAL jsonb_array_elements(COALESCE(v->'fee_history', '[]'::jsonb)) p
    GROUP BY 1, 2
), stakes AS (
    SELECT s.key AS currency, SUM(CAST(s.value AS DOUBLE PRECISION)) AS at_stake
    FROM live, LATERAL jsonb_each_text(COALESCE(v->'at_stake', '{{}}'::jsonb)) s GROUP BY 1
), bands AS (
    SELECT b.key AS stem, SUM(CAST(b.value AS DOUBLE PRECISION)) AS units
    FROM live, LATERAL jsonb_each_text(COALESCE(v->'age_bands', '{{}}'::jsonb)) b GROUP BY 1
), bucket_fees AS (
    SELECT COALESCE(v->>'currency', 'UNKNOWN') AS currency, f.key AS stem, SUM(CAST(f.value AS DOUBLE PRECISION)) AS fee
    FROM live, LATERAL jsonb_each_text(COALESCE(v->'age_fees', '{{}}'::jsonb)) f GROUP BY 1, 2
), currencies AS (SELECT currency FROM trend UNION SELECT currency FROM stakes),
totals AS (
    SELECT c.currency, COALESCE(SUM(t.storage), 0) AS storage, COALESCE(SUM(t.long_term), 0) AS long_term,
        COALESCE(MAX(s.at_stake), 0) AS at_stake FROM currencies c
    LEFT JOIN trend t ON t.currency = c.currency LEFT JOIN stakes s ON s.currency = c.currency GROUP BY 1
), months AS MATERIALIZED (SELECT DISTINCT month FROM trend), bounds AS (
    SELECT count(*) AS total, CASE WHEN count(*) = 0 THEN 0
        ELSE LEAST(%s, ((count(*) - 1) / %s)::bigint * %s) END AS start FROM months
), month_page AS (SELECT month FROM months ORDER BY month LIMIT %s OFFSET (SELECT start FROM bounds))
SELECT jsonb_build_object(
    'meta', (SELECT value - 'items' FROM doc), 'empty', NOT EXISTS(SELECT 1 FROM live),
    'nextTierCount', (SELECT count(*) FROM live WHERE v->>'next_tier' IS NOT NULL),
    'bandUnits', (SELECT jsonb_object_agg(stem, units) FROM bands WHERE units IS NOT NULL),
    'bandFees', (SELECT jsonb_object_agg(currency, stems) FROM
        (SELECT currency, jsonb_object_agg(stem, fee) AS stems FROM bucket_fees WHERE fee IS NOT NULL GROUP BY 1) c),
    'statusCounts', (SELECT jsonb_object_agg(status, n) FROM
        (SELECT v->>'status' AS status, count(*) AS n FROM live WHERE v->>'status' IS NOT NULL GROUP BY 1) c),
    'actionCounts', (SELECT jsonb_object_agg(action, n) FROM
        (SELECT v->>'action' AS action, count(*) AS n FROM live WHERE v->>'action' IS NOT NULL GROUP BY 1) c),
    'volume', (SELECT jsonb_build_object(
        'freed', CASE WHEN COUNT(CASE WHEN (v->>'status') = 'Open' AND (v->>'action') IN ('Remove', 'Price down')
            AND ((v->>'volume_freed') IS NULL OR COALESCE((v->>'volume_unit'), '') <> 'ft3') THEN 1 END) > 0
            THEN NULL ELSE COALESCE(SUM(CASE WHEN (v->>'status') = 'Open'
                AND (v->>'action') IN ('Remove', 'Price down') THEN CAST((v->>'volume_freed') AS DOUBLE PRECISION) END), 0) END,
        'unknownProposals', COUNT(CASE WHEN (v->>'status') = 'Open' AND (v->>'action') IN ('Remove', 'Price down')
            AND ((v->>'volume_freed') IS NULL OR COALESCE((v->>'volume_unit'), '') <> 'ft3') THEN 1 END),
        'current', CASE WHEN COUNT(CASE WHEN (v->>'storage_volume_source') IS NOT NULL
            AND ((v->>'storage_volume') IS NULL OR COALESCE((v->>'volume_unit'), '') <> 'ft3') THEN 1 END) > 0
            THEN NULL ELSE COALESCE(SUM(CASE WHEN (v->>'storage_volume_source') IS NOT NULL
                THEN CAST((v->>'storage_volume') AS DOUBLE PRECISION) END), 0) END,
        'unknownStorage', COUNT(CASE WHEN (v->>'storage_volume_source') IS NOT NULL
            AND ((v->>'storage_volume') IS NULL OR COALESCE((v->>'volume_unit'), '') <> 'ft3') THEN 1 END)) FROM live),
    'totals', (SELECT jsonb_object_agg(currency, jsonb_build_object('storage', storage, 'long_term', long_term,
        'total', storage + long_term, 'at_stake', at_stake)) FROM totals),
    'trend', (SELECT jsonb_object_agg(currency, points) FROM
        (SELECT currency, jsonb_agg(jsonb_build_object('month', month, 'storage', storage, 'long_term', long_term,
            'total', storage + long_term) ORDER BY month) AS points
         FROM trend WHERE month IN (SELECT month FROM month_page) GROUP BY currency) c),
    'firstMonth', (SELECT MIN(month) FROM months), 'lastMonth', (SELECT MAX(month) FROM months),
    'totalMonths', (SELECT total FROM bounds), 'offset', (SELECT start FROM bounds))
"""


def _bucket_dates(cur, cols):
    """The newest and the previous planning snapshot dates, newest first; [None] when rows carry no date."""
    if "_snapshot_date" not in cols:
        return [None]
    return [r[0] for r in cur.execute(
        f'SELECT DISTINCT CAST("_snapshot_date" AS VARCHAR) AS d FROM {PLANNING} '
        'WHERE "_snapshot_date" IS NOT NULL ORDER BY d DESC LIMIT 2').fetchall()]


def _bucket_source(cur, cols, date, primary):
    """Bucket units and estimated fees summed in SQL over one planning snapshot, apart from the items document.

    The fee per bucket sums `estimated_ais_<tier>_days` over the bucket's tiers, with `_planning`'s rule
    for over 365 days. A row with a blank currency counts in `primary`, as `build_rows` gives such a SKU."""
    def dbl(name):
        return _dbl(cols, name)
    units = []
    for stem, _label, _days in BANDS:
        value = dbl(f"inv_age_{stem}_days")
        if stem == "365_plus":
            a, b = dbl("inv_age_366_to_455_days"), dbl("inv_age_456_plus_days")
            value = (f"COALESCE({value}, CASE WHEN {a} IS NULL AND {b} IS NULL THEN NULL "
                     f"ELSE COALESCE({a}, 0) + COALESCE({b}, 0) END)")
        units.append(f"SUM({value})")
    fine_blank = " AND ".join(f"{dbl(f'{pre}_{t}_days')} IS NULL" for t in FINE_FROM_366
                              for pre in ("quantity_to_be_charged_ais", "estimated_ais"))
    fees = []
    for stem, tiers in BUCKET_TIERS.items():
        parts = " + ".join(f"COALESCE({dbl(f'estimated_ais_{t}_days')}, 0)" for t in tiers if t != "365_plus")
        if "365_plus" in tiers:
            parts = f"CASE WHEN {fine_blank} THEN COALESCE({dbl('estimated_ais_365_plus_days')}, 0) ELSE {parts} END"
        fees.append(f"SUM({parts})")
    where, args = ('CAST("_snapshot_date" AS VARCHAR) = ?', [date]) if date is not None else ("TRUE", [])
    rows = cur.execute(f"SELECT {_col(cols, 'currency')}, {', '.join(units + fees)} FROM {PLANNING} "
                       f"WHERE {where} AND {_col(cols, 'sku')} IS NOT NULL GROUP BY 1", args).fetchall()
    out = {"asOf": date, "units": {stem: 0.0 for stem, _l, _d in BANDS}, "fees": {}}
    for currency, *values in rows:
        for (stem, _l, _d), value in zip(BANDS, values[:len(BANDS)]):
            out["units"][stem] += float(value or 0)
        got = out["fees"].setdefault(currency or primary or UNKNOWN_CURRENCY, {stem: 0.0 for stem in BUCKET_TIERS})
        for stem, value in zip(BUCKET_TIERS, values[len(BANDS):]):
            got[stem] += float(value or 0)
    return out if rows else None


def bucket_snapshots(cur, primary=None):
    """{current, previous}: the two newest planning snapshots' bucket figures, or None without planning."""
    cols = _columns(cur, PLANNING)
    if "sku" not in cols:
        return None
    dates = _bucket_dates(cur, cols)
    snaps = dict(zip(("current", "previous"), (_bucket_source(cur, cols, d, primary) for d in dates)))
    return snaps if snaps.get("current") else None


def bucket_tiles(out, doc):
    """One tile per age bucket in band order: the items' units and fees, and the previous snapshot's."""
    primary = doc.get("primaryCurrency")
    snaps = doc.get("buckets") if isinstance(doc.get("buckets"), dict) else {}
    newest = snaps.get("current") if isinstance(snaps.get("current"), dict) else {}
    prev = snaps.get("previous") if isinstance(snaps.get("previous"), dict) else None
    units = out.get("bandUnits") or {}
    fees = (out.get("bandFees") or {}).get(primary) or {}
    tiles = []
    for stem, label, _days in BANDS:
        surcharge = stem in BUCKET_TIERS
        tile = {"stem": stem, "label": label, "units": float(units.get(stem) or 0),
                "fee": float(fees.get(stem) or 0) if surcharge else None, "currency": primary,
                "surcharge": surcharge, "asOf": newest.get("asOf"), "previous": None,
                "validated": False, "reason": BUCKETS_UNAVAILABLE}
        if prev is not None:
            prev_fee = ((prev.get("fees") or {}).get(primary) or {}).get(stem)
            tile["previous"] = {"asOf": prev.get("asOf"), "units": float((prev.get("units") or {}).get(stem) or 0),
                                "fee": float(prev_fee or 0) if surcharge else None}
        tiles.append(tile)
    return tiles


def check_buckets(tenant_key, st, tiles, primary):
    """Rule 8: a tile is validated only when its units and fee tie to an independent SQL sum over the
    newest planning snapshot in the mirror. Returns that source, or None when it cannot be read."""
    try:
        with _reader(tenant_key, st) as cur:
            cols = _columns(cur, PLANNING)
            dates = _bucket_dates(cur, cols) if "sku" in cols else []
            source = _bucket_source(cur, cols, dates[0], primary) if dates else None
    except Exception:                                                  # noqa: BLE001
        source = None
    for tile in tiles:
        if source is None:
            tile.update(validated=False, reason=BUCKETS_UNAVAILABLE)
            continue
        units = source["units"].get(tile["stem"], 0.0)
        fee = (source["fees"].get(primary) or {}).get(tile["stem"], 0.0) if tile["surcharge"] else None
        ok = (math.isclose(tile["units"], units, rel_tol=0, abs_tol=1e-6)
              and (fee is None and tile["fee"] is None
                   or fee is not None and tile["fee"] is not None
                   and math.isclose(tile["fee"], fee, rel_tol=0, abs_tol=1e-6)))
        tile.update(validated=ok, reason=None if ok else BUCKET_MISMATCH, source={"units": units, "fee": fee})
    return source


def _page_size(value):
    """Bound one page without limiting the number of reachable records."""
    try:
        size = int(value)
    except (TypeError, ValueError):
        raise ValueError("The page size must be a whole number.") from None
    if size < 1:
        raise ValueError("The page size must be at least 1.")
    return min(size, MAX_PAGE_SIZE)


def queue_refresh(st, *, now=None):
    """Queue one durable refresh intent for the sync worker, or keep the one already queued or running."""
    identity, stamp = uuid.uuid4().hex, time.time() if now is None else now

    def enqueue(doc):
        doc = doc if isinstance(doc, dict) else {}
        if (doc.get("state") in ("queued", "running")
                and stamp - float(doc.get("requestedAt") or 0) < REFRESH_HOLD_SECONDS):
            return doc
        return {"state": "queued", "requestId": identity, "requestedAt": stamp}
    return st.update(KEY_REFRESH, enqueue)


def _first_open(st, now=None):
    """The waiting line when no refresh ever wrote the items doc. Queues the refresh POST /refresh queues."""
    stamp = time.time() if now is None else now
    try:
        pending = _doc(st, KEY_REFRESH)
        if (pending.get("state") == "failed"
                and stamp - float(pending.get("finishedAt") or 0) < REFRESH_HOLD_SECONDS):
            return pending.get("message") or NOT_READY
        queued = queue_refresh(st, now=stamp)
    except Exception:                                                  # noqa: BLE001
        return NOT_READY
    return READING if (queued or {}).get("state") in ("queued", "running") else NOT_READY


def _stale_wait(st, doc, now=None):
    """A not ready doc whose queued refresh found nothing more than the hold ago is read again.

    That refresh may have run while the mirror was still restoring at boot."""
    if doc.get("state") != "not_ready":
        return False
    pending = _doc(st, KEY_REFRESH)
    if pending.get("state") != "done" or (pending.get("result") or {}).get("state") != "not_ready":
        return False
    stamp = time.time() if now is None else now
    return stamp - float(pending.get("finishedAt") or 0) >= REFRESH_HOLD_SECONDS


def summary(tenant_key, *, offset=0, limit=24, st=None):
    """Aggregate fees and counts in SQL and return one month page without SKU rows."""
    st = _rt(tenant_key, st)
    _apply_grid(tenant_key, st)
    offset, limit = max(0, int(offset)), _page_size(limit)
    out = _select(st, SUMMARY_SQL, lambda key: (key(KEY_ITEMS), offset // limit * limit, limit, limit, limit))
    doc = out.pop("meta") or {}
    volume = out.get("volume") or {}
    if not doc.get("storageVolumeReady"):
        volume["current"] = None
    capacity = _nonnegative(_paths(st, KEY_SETTINGS, [("fba_capacity",)])[0])
    volume.update(unit=VOLUME_UNIT, capacity=capacity, capacitySource="Typed", sources=VOLUME_SOURCES,
                  remaining=capacity - volume["current"] if capacity is not None and volume.get("current") is not None
                  else None)
    ready = doc.get("state") == "ready"
    tiles = bucket_tiles(out, doc)
    if ready:
        check_buckets(tenant_key, st, tiles, doc.get("primaryCurrency"))
    waiting = None if ready else (doc.get("message") or NOT_READY)
    if not ready and (not doc.get("state") or _stale_wait(st, doc)):
        waiting = _first_open(st)
    return {**out, "volume": volume, "trend": out.get("trend") or {}, "totals": out.get("totals") or {}, "monthLimit": limit,
            "ready": ready, "notReady": waiting,
            "notices": list(doc.get("notices") or ()), "primaryCurrency": doc.get("primaryCurrency"),
            "statusCounts": {s: int((out.get("statusCounts") or {}).get(s, 0)) for s in STATUSES},
            "actionCounts": {a: int((out.get("actionCounts") or {}).get(a, 0)) for a in ACTIONS},
            "bandUnits": {stem: float((out.get("bandUnits") or {}).get(stem) or 0) for stem, _l, _d in BANDS},
            "buckets": tiles,
            "tableError": doc.get("tableError"),
            "refreshedAt": doc.get("refreshedAt"), "lastError": doc.get("last_error"), "limit": LIMIT}


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

def _order(item):
    action = item.get("action")
    rank = ACTIONS.index(action) if action in ACTIONS else len(ACTIONS)
    stake = max((item.get("at_stake") or {}).values(), default=0) or 0
    return (not item.get("inReport", True), rank, -stake, str(item.get("key") or ""))


def _cursor_offset(cursor):
    if not cursor:
        return 0
    try:
        return max(0, int(json.loads(base64.urlsafe_b64decode(str(cursor).encode()).decode())["o"]))
    except Exception:                                                  # noqa: BLE001
        raise ValueError("The page cursor is not valid. Start from the first page.") from None


def _cursor(offset):
    return base64.urlsafe_b64encode(json.dumps({"o": offset}).encode()).decode()


def _public(item):
    out = {k: v for k, v in item.items() if k not in ("history", "fee_history", "fees")}
    out.setdefault("title", item.get("sku") or item.get("key"))
    return out


def _matches(item, needle):
    """True when the lowercased needle is a substring of the item's sku, fnsku, title or asin."""
    return any(needle in str(item.get(k) or "").lower() for k in ("sku", "fnsku", "title", "asin"))


# `items` holds the map once: reading it from `doc` per page row detoasted the whole document each time.
PAGE_SQL = """
WITH doc AS MATERIALIZED (SELECT value FROM {tbl} WHERE key = %s),
items AS MATERIALIZED (SELECT COALESCE(value->'items', '{{}}'::jsonb) AS v FROM doc),
searched AS MATERIALIZED (
    SELECT e.key AS iid, e.value->>'status' AS status, e.value->>'action' AS action,
        COALESCE(e.value->>'inReport', 'true') AS report, COALESCE(e.value->>'key', '') AS sku,
        e.value->>'next_tier' IS NOT NULL AS has_tier,
        CAST(e.value->'next_tier'->>'at_stake' AS DOUBLE PRECISION) AS tier_stake,
        (SELECT MAX(CAST(value AS DOUBLE PRECISION)) FROM
            jsonb_each_text(COALESCE(e.value->'at_stake', '{{}}'::jsonb))) AS stake
    FROM items, LATERAL jsonb_each(items.v) e
    WHERE %s = '' OR strpos(lower(COALESCE(e.value->>'sku', '')), %s) > 0
        OR strpos(lower(COALESCE(e.value->>'fnsku', '')), %s) > 0
        OR strpos(lower(COALESCE(e.value->>'title', '')), %s) > 0
        OR strpos(lower(COALESCE(e.value->>'asin', '')), %s) > 0
), filtered AS MATERIALIZED (
    SELECT * FROM searched WHERE (CAST(%s AS TEXT) IS NULL OR status = %s)
        AND (CAST(%s AS TEXT) IS NULL OR action = %s)
        AND (NOT %s OR (has_tier AND report <> 'false'))
), bounds AS (
    SELECT count(*) AS total, CASE WHEN count(*) = 0 THEN 0
        ELSE LEAST(%s, ((count(*) - 1) / %s)::bigint * %s) END AS start FROM filtered
), ranked AS (
    SELECT iid, row_number() OVER (ORDER BY
        CASE WHEN %s THEN 'true' ELSE report END DESC,
        CASE WHEN %s THEN 0 ELSE CASE action WHEN 'Remove' THEN 0 WHEN 'Price down' THEN 1
            WHEN 'Push with ads' THEN 2 ELSE 3 END END,
        CASE WHEN %s THEN tier_stake ELSE COALESCE(stake, 0) END DESC NULLS LAST, sku COLLATE "C", iid) AS n
    FROM filtered
), page AS (SELECT iid, n FROM ranked ORDER BY n LIMIT %s OFFSET (SELECT start FROM bounds)),
projected AS (SELECT items.v->page.iid AS v, page.n FROM page CROSS JOIN items)
SELECT jsonb_build_object('meta', (SELECT value - 'items' FROM doc),
    'total', (SELECT total FROM bounds), 'offset', (SELECT start FROM bounds),
    'items', (SELECT jsonb_agg(v - 'history' - 'fee_history' - 'fees' ORDER BY n) FROM projected))
"""


def items(tenant_key, user=None, *, status=None, action=None, next_tier=False, cursor=None, limit=200, q=None, st=None):
    """C4: every item matching q, filtered by status and action, paged by an opaque cursor with no total cap."""
    if status is not None and status not in STATUSES:
        raise ValueError("Status must be one of: " + ", ".join(STATUSES) + ".")
    if action is not None and action not in ACTIONS:
        raise ValueError("Action must be one of: " + ", ".join(ACTIONS) + ".")
    limit = _page_size(limit)
    st = _rt(tenant_key, st)
    _apply_grid(tenant_key, st)
    needle = str(q or "").strip().lower()
    start = _cursor_offset(cursor) // limit * limit
    result = _select(st, PAGE_SQL, lambda key: (key(KEY_ITEMS), needle, needle, needle, needle, needle,
                     status, status, action, action, next_tier, start, limit, limit,
                     next_tier, next_tier, next_tier, limit))
    doc = result.get("meta") or {}
    start, total = int(result["offset"]), int(result["total"])
    ready = doc.get("state") == "ready"
    return {"items": result.get("items") or [], "total": total, "offset": start, "limit": limit,
            "cursor": _cursor(start + limit) if start + limit < total else None,
            "previousCursor": _cursor(max(0, start - limit)) if start else None,
            "ready": ready, "message": None if ready else (doc.get("message") or NOT_READY),
            "notices": list(doc.get("notices") or ()), "refreshedAt": doc.get("refreshedAt"),
            "lastError": doc.get("last_error"), "statuses": list(STATUSES), "actions": list(ACTIONS)}


def item_detail(tenant_key, item_id, *, offset=0, limit=50, st=None):
    """Read one SKU and a page of its fees, events, removal and stranded history. A SKU names its item too."""
    st = _rt(tenant_key, st)
    _apply_grid(tenant_key, st)
    offset, limit = max(0, int(offset)), _page_size(limit)
    base = "WITH item AS (SELECT value #> %s::text[] AS v FROM {tbl} WHERE key=%s) "
    item = _select(st, base + "SELECT v - 'history' - 'fee_history' - 'fees' FROM item",
                   lambda key: (["items", item_id], key(KEY_ITEMS)))
    if not item and item_id_for(item_id) != item_id:
        item_id = item_id_for(item_id)
        item = _select(st, base + "SELECT v - 'history' - 'fee_history' - 'fees' FROM item",
                       lambda key: (["items", item_id], key(KEY_ITEMS)))
    if not item:
        raise KeyError(item_id)
    totals, children = {}, {}
    for field, public in (("fee_history", "fee_history"), ("history", "events")):
        result = _select(st, base + "SELECT jsonb_build_object('total', "
            "jsonb_array_length(COALESCE(v->%s, '[]'::jsonb)), 'rows', "
            "(SELECT jsonb_agg(value ORDER BY n) FROM (SELECT value, n FROM jsonb_array_elements("
            "COALESCE(v->%s, '[]'::jsonb)) WITH ORDINALITY a(value, n) ORDER BY n DESC "
            "LIMIT %s OFFSET %s) p)) FROM item",
            lambda key: (["items", item_id], key(KEY_ITEMS), field, field, limit, offset))
        totals[public] = int(result.get("total") or 0)
        children[public] = result.get("rows") or []
    for kind, public, stamp in (("removals", "removal_history", "snapshot"),
                                ("stranded", "stranded_history", "date")):
        sql = """WITH points AS MATERIALIZED (
            SELECT e.key AS day, e.value AS point FROM {tbl} kv,
            LATERAL jsonb_each(COALESCE(kv.value #> %s::text[], '{{}}'::jsonb)) e
            WHERE kv.key LIKE %s
        ), page AS (SELECT day, point FROM points ORDER BY day DESC LIMIT %s OFFSET %s)
        SELECT jsonb_build_object('total', (SELECT count(*) FROM points),
            'rows', (SELECT jsonb_agg(point || jsonb_build_object(%s::text, day) ORDER BY day) FROM page))"""
        # The fixed prefix contains underscores, so escape LIKE metacharacters before the suffix wildcard.
        key_prefix = _sql_scope(st)[2](HISTORY_PREFIX)
        pattern = key_prefix.replace("\\", "\\\\").replace("_", "\\_").replace("%", "\\%") + "%"
        result = _select(st, sql, lambda key: ([kind, item.get("key")], pattern, limit, offset, stamp))
        totals[public] = int(result.get("total") or 0)
        children[public] = result.get("rows") or []
    total = max(totals.values())
    start = min(offset // limit * limit, max(0, (total - 1) // limit * limit))
    if start != offset:
        return item_detail(tenant_key, item_id, offset=start, limit=limit, st=st)
    review = removal_review(tenant_key, item_id, st=st) if item.get("action") == REMOVE else None
    if review and review.get("quantity") is not None and review.get("fingerprint"):
        item["proposal_units"] = review["quantity"]
        volume = _nonnegative(item.get("unit_volume"))
        item["volume_freed"] = volume * review["quantity"] if volume is not None else None
    return {**item, **children, "removalReview": review, "detailOffset": offset, "detailLimit": limit,
            "detailTotal": total, "detailTotals": totals}


def _uname(user):
    if isinstance(user, dict):
        return str(user.get("username") or user.get("name") or "")
    return str(user or "")


def _may_change(st, user):
    """A known viewer or inactive account may not change an item (the App grant is the caller's check)."""
    try:
        users = st.get("users") or {}
    except Exception:                                                  # noqa: BLE001
        users = {}
    rec = users.get(_uname(user)) if isinstance(users, dict) else None
    if isinstance(rec, dict) and (str(rec.get("role") or "").lower() == "viewer" or rec.get("active") is False):
        return False
    return True


def _price(value):
    """A proposed price: blank clears it, else a finite number of 0 or more."""
    if value is None or (isinstance(value, str) and not value.strip()):
        return None
    number = None if isinstance(value, bool) else _num(value)
    if number is None or not math.isfinite(number) or number < 0:
        raise ValueError("Price must be a number of 0 or more.")
    return number


def update_item(tenant_key, item_id, *, owner=None, status=None, due=None, action=None, note=None,
                price=None, user="system", st=None):
    """Reassign, move status, move the due date, choose the action or propose a price. Returns the item.

    A price is a proposal kept on the item. Nothing here sends it to Amazon.
    """
    return _update_item(tenant_key, item_id, owner=owner, status=status, due=due, action=action, note=note,
                        price=price, user=user, st=st)


def _update_item(tenant_key, item_id, *, owner=None, status=None, due=None, action=None, note=None,
                 price=None, user="system", st=None, row_id=None, rows=None):
    new_price = _price(price) if price is not None else None
    if status is not None and status not in STATUSES:
        raise ValueError("Status must be one of: " + ", ".join(STATUSES) + ".")
    if action is not None and action not in ACTIONS:
        raise ValueError("Action must be one of: " + ", ".join(ACTIONS) + ".")
    if due is not None and due != "":
        try:
            due = dt.date.fromisoformat(str(due)).isoformat()
        except ValueError:
            raise ValueError("Due must be a date such as 2026-10-30.") from None
    if owner is not None and not str(owner).strip():
        raise ValueError("Owner cannot be empty.")
    st = _rt(tenant_key, st)
    if not _may_change(st, user):
        raise PermissionError("Your account can view this App but not change it.")
    name = _uname(user) or "unknown"
    out = {}

    def _apply(item):
        at = _stamp(_now())
        event = {"at": at, "by": name}
        if owner is not None:
            item["owner"] = event["owner"] = str(owner).strip()
        if status is not None:
            item["status"] = event["status"] = status
        if due is not None:
            item["due"] = event["due"] = due or None
        if action is not None:
            item["action"] = event["action"] = action
            item["actionChosenBy"] = name
        if price is not None:
            item["proposedPrice"] = event["proposedPrice"] = new_price
        item.update(_volume_fields(item))
        if note:
            event["note"] = str(note)
        item["updatedAt"], item["updatedBy"] = at, name
        # The table row gets these owned cells below, so a stale Grid cell never undoes this change.
        item["gridApplied"] = {"action": item.get("action"), "price": item.get("proposedPrice")}
        item.setdefault("history", []).append(event)
        out["item"] = _public(item)
        return item
    _update_one(st, item_id, _apply)
    if "item" not in out:
        raise KeyError(item_id)
    _sync_table_row(st, out["item"], rid=row_id, rows=rows)
    return out["item"]


def _update_one(st, item_id, apply):
    """Lock the document but transfer and patch only the selected item's scalar fields."""
    pg, tenant, key = _sql_scope(st)
    name, path = key(KEY_ITEMS), ["items", item_id]
    pg.check_write(tenant, "update aged stock item")
    try:
        with pg._pool().connection() as con, con.transaction():
            con.execute("SELECT set_config('lock_timeout', %s, true)", (f"{int(pg._lock_timeout_s() * 1000)}ms",))
            row = con.execute(pg._q("SELECT (value #> %s::text[]) - 'history' - 'fee_history' - 'fees', "
                                   "octet_length(value::text) FROM {tbl} WHERE key=%s FOR UPDATE",
                                   "store_kv", tenant), (path, name)).fetchone()
            item = row[0] if row else None
            if not item:
                raise KeyError(item_id)
            item = json.loads(item) if isinstance(item, str) else item
            changed = apply(item)
            events = json.dumps(changed.pop("history", []), ensure_ascii=False, allow_nan=False)
            payload = json.dumps(changed, ensure_ascii=False, allow_nan=False)
            saved = con.execute(pg._q("UPDATE {tbl} SET value=jsonb_set(value, %s::text[], "
                "(value #> %s::text[]) || %s::jsonb || jsonb_build_object('history', "
                "COALESCE(value #> %s::text[], '[]'::jsonb) || %s::jsonb)), "
                "rev=rev+1, updated_at=now() WHERE key=%s RETURNING octet_length(value::text)",
                "store_kv", tenant), (path, path, payload, path + ["history"], events, name)).fetchone()
            if saved[0] > pg.DOCUMENT_CEILING_BYTES and saved[0] > row[1]:
                raise pg.StoreDocumentTooLarge(name, saved[0])
    finally:
        pg._bump_write_generation(name, tenant)


# --------------------------------------------------------------------------- Grid edits (S82-T36)

def _price_text(value):
    number = _num(value)
    return None if number is None else repr(round(number, 6))


def _table_rows(st):
    from core import user_tables
    table = user_tables.get_one(TABLE_KEY, st)
    return table if isinstance(table, dict) else {}


def _sync_table_row(st, item, rid=None, rows=None):
    """Write an item's people cells to its table row as the App. Never raises."""
    try:
        from core import user_tables
        sku = str(item.get("key") or item.get("sku") or "")
        rows = rows if rows is not None else (_table_rows(st).get("rows") or {})
        if rid is None:
            rid = next((r for r, row in rows.items() if str(row.get("sku") or "") == sku), None)
        if rid is None or rid not in rows:
            return False
        status = item.get("status")
        values = {"status": status if status in STATUSES else None, "owner": _text(item.get("owner")),
                  "due": _text(item.get("due")), "action": item.get("action") if item.get("action") in ACTIONS else None,
                  "proposed_price": _price_text(item.get("proposedPrice"))}
        # Only changed cells are written, so an equal Grid value keeps its own form and its editor.
        current = rows[rid] or {}
        same = {k for k, v in values.items()
                if (_num(current.get(k)) == _num(v) if k == "proposed_price" else _text(current.get(k)) == v)}
        values = {k: v for k, v in values.items() if k not in same}
        if not values:
            return True
        return user_tables.patch_cells(TABLE_KEY, rid, values, st, by=TABLE_WRITER, via=TABLE_VIA)
    except Exception:                                                  # noqa: BLE001
        return False


def _grid_editor(audit):
    from core import user_tables
    name = str((audit or {}).get("last_modified_by") or "").strip()
    return name if name and name not in (TABLE_WRITER, *user_tables.MACHINE_OWNERS) else None


def apply_grid_edits(tenant_key, st=None):
    """Apply each owned Grid cell that differs from the value last applied from its row, through update_item.

    A Grid Remove only sets the proposal. A removal order goes only through approve_removal.
    """
    st = _rt(tenant_key, st)
    table = _table_rows(st)
    audit = table.get("_rowAudit") if isinstance(table.get("_rowAudit"), dict) else {}
    wanted, rows = [], table.get("rows") or {}
    for rid, row in rows.items():
        sku = str((row or {}).get("sku") or "")
        if not sku:
            continue
        action = row.get("action") if row.get("action") in ACTIONS else None
        price = _num(row.get("proposed_price"))
        editor = _grid_editor(audit.get(rid))
        if action is None and price is None and editor is None:
            continue
        wanted.append((rid, str(row.get("item_id") or item_id_for(sku)), action, price, editor))
    if not wanted:
        return {"applied": 0}
    seen = _paths(st, KEY_ITEMS, [("items", iid, "gridApplied") for _rid, iid, *_rest in wanted])
    applied = 0
    for (rid, iid, action, price, editor), last in zip(wanted, seen):
        last = last if isinstance(last, dict) else {}
        change = {}
        if action is not None and action != last.get("action"):
            change["action"] = action
        if price != _num(last.get("price")):
            change["price"] = "" if price is None else price
        if not change:
            continue
        try:
            _update_item(tenant_key, iid, user=editor or "Grid", st=st, row_id=rid, rows=rows, **change)
            applied += 1
        except (KeyError, ValueError, PermissionError):
            continue
    return {"applied": applied}


def _apply_grid(tenant_key, st):
    """Reads apply pending Grid edits first. A failure never breaks the read."""
    try:
        return apply_grid_edits(tenant_key, st=st)
    except Exception:                                                  # noqa: BLE001
        return None


def set_status(tenant_key, user, item_id, status, *, note=None, st=None):
    """C4: move one item's status with an optional note."""
    return update_item(tenant_key, item_id, status=status, note=note, user=user, st=st)


def _proposal_text(item):
    action = item.get("action")
    if action == REMOVE:
        qty = _proposal_units(item)
        return f"Remove {_fmt(qty)} sellable units" if qty is not None else "Review sellable stock"
    if action == PRICE_DOWN:
        price = item.get("recommended_sales_price")
        if price is not None and price > 0:
            return f"Lower the price to {_money(price, item.get('currency') or UNKNOWN_CURRENCY)}"
        return "Lower the price"
    return "Push with ads"


def proposals(tenant_key, *, st=None):
    """C7: one proposal per Open item with an action, each listed once."""
    st = _rt(tenant_key, st)
    out, seen = [], set()
    def pages():
        cursor = None
        while True:
            page = items(tenant_key, status="Open", cursor=cursor, st=st)
            yield from page["items"]
            cursor = page["cursor"]
            if not cursor:
                break
    for item in pages():
        if (item.get("status") != "Open" or item.get("action") not in ACTIONS
                or item.get("inReport") is False or item["id"] in seen):
            continue
        seen.add(item["id"])
        review = removal_review(tenant_key, item["id"], st=st) if item.get("action") == REMOVE else None
        reason = item.get("reason")
        if review:
            details = review.get("reason")
            if not details:
                details = f"{review['disposition']} {review['quantity']} sellable units. Marketplace {review['marketplace']}."
                if review["disposition"] == "Return":
                    details += " Ship-to: " + ", ".join(review["ship_to"].values()) + "."
                item = {**item, "proposal_units": review["quantity"]}
                volume = _nonnegative(item.get("unit_volume"))
                item["volume_freed"] = volume * review["quantity"] if volume is not None else None
            reason = " ".join(part for part in (reason, details) if part)
        out.append({"source_kind": SOURCE_KIND, "item_id": item["id"], "sku": item.get("sku") or item.get("fnsku"),
                    "action": (f"Remove {review['quantity']} sellable units" if review and review.get("quantity") is not None
                               else _proposal_text(item)), "reason": reason,
                    "volume_freed": item.get("volume_freed"), "volume_unit": item.get("volume_unit"),
                    "unit_volume_source": item.get("unit_volume_source"), "proposal_units": item.get("proposal_units"),
                    **({"removal_review": review} if review else {})})
    return out


SHIP_FIELDS = ("AddressName", "AddressFieldOne", "AddressCity", "AddressCountryCode", "AddressPostalCode")
SHIP_OPTIONAL = ("AddressFieldTwo", "AddressStateOrRegion")
APPROVAL_PREFIX = "aged_stock_approval_"


def _ship_to(value):
    """Accept only typed address fields without embedded file delimiters."""
    if not isinstance(value, dict) or set(value) - set(SHIP_FIELDS + SHIP_OPTIONAL):
        raise ValueError("Use the Aged stock ship-to fields.")
    out = {}
    for key, text in value.items():
        if not isinstance(text, str) or len(text) > 180 or any(ord(c) < 32 or c == '"' for c in text):
            raise ValueError("Ship-to fields must be plain text without tabs or line breaks.")
        if text.strip():
            out[key] = text.strip()
    if out.get("AddressCountryCode") and not re.fullmatch(r"[A-Z]{2}", out["AddressCountryCode"]):
        raise ValueError("Use a two-letter uppercase country code.")
    return out


def _removal_user(st, tenant_key, user):
    """Require one known active editor through the canonical account row reader."""
    name = _uname(user).strip()
    if not name:
        raise PermissionError("Removal approval needs its named approver.")
    try:
        try:
            from core.account_rows import get as get_account
        except ModuleNotFoundError as exc:
            if exc.name != "core.account_rows":
                raise
            rec = st.get_entry("users", name)
        else:
            rec = get_account(name, st=st, fresh=True)
    except Exception as exc:
        raise PermissionError("The approver account could not be verified. Reload and try again.") from exc
    if (not isinstance(rec, dict) or rec.get("active") is not True
            or str(rec.get("role") or "").lower() not in ("admin", "user", "editor")
            or str(rec.get("tenant") or tenant_key) != tenant_key):
        raise PermissionError("Removal approval needs an active editor account in this workspace.")
    return name


def removal_review(tenant_key, item_id, *, st=None, claim_id=None):
    """Return the exact removal details a person must review before approval."""
    st = _rt(tenant_key, st)
    fields = ("id", "sku", "action", "inReport", "removal", "recommended_removal_quantity", "removalApproval")
    item = dict(zip(fields, _paths(st, KEY_ITEMS, [("items", item_id, field) for field in fields])))
    if not item.get("id"):
        raise KeyError(item_id)
    conf = dict(zip(("removal_disposition", "ship_to"),
                    _paths(st, KEY_SETTINGS, [("removal_disposition",), ("ship_to",)])))
    review = {"tenant_key": tenant_key, "item_id": item_id, "sku": item.get("sku"),
              "disposition": conf.get("removal_disposition") or "Return",
              "ship_to": conf.get("ship_to") or {}, "quantity": None, "sellable": None,
              "marketplace": None, "fingerprint": None, "reason": None}
    try:
        if item.get("action") != REMOVE or item.get("inReport") is False:
            raise ValueError("Reload the current Remove proposal before approval.")
        if (item.get("removalApproval")
                and (item["removalApproval"].get("approvalId") != claim_id or not claim_id)
                and not _validated_removal(tenant_key, item, st)):
            raise ValueError("This item already has a removal claim. Reconcile its saved receipt before another removal.")
        if review["disposition"] not in ("Return", "Disposal"):
            raise ValueError("Liquidate is record-only. Record its outcome in the item note.")
        address = _ship_to(review["ship_to"])
        if review["disposition"] == "Return" and any(not address.get(k) for k in SHIP_FIELDS):
            raise ValueError("Save the complete Aged stock ship-to before approving a Return.")
        if not isinstance(review["sku"], str) or not review["sku"] or any(
                ord(c) < 32 or c == '"' for c in review["sku"]):
            raise ValueError("This removal needs a valid merchant SKU. Sync the removal report.")
        with _reader(tenant_key, st) as cur:
            stock = _sellable_stock(cur, item["sku"])
        review.update(stock)
        quantity = _proposal_units({**item, "removal": {**(item.get("removal") or {}),
                                                        "sellable_quantity": stock["sellable"]}})
        if quantity is None or quantity <= 0:
            raise ValueError("No known sellable units can be removed. Sync the removal report, then reload.")
        review.update(quantity=quantity, ship_to=address)
        review["fingerprint"] = hashlib.sha256(json.dumps(review, sort_keys=True).encode()).hexdigest()
    except ValueError as exc:
        review["reason"] = str(exc)
    return review


def _approval_key(approval_id):
    if not isinstance(approval_id, str) or not re.fullmatch(r"asr_[a-f0-9]{32}", approval_id):
        raise ValueError("A saved removal approval id is required.")
    return APPROVAL_PREFIX + approval_id


def removal_approval(tenant_key, approval_id, *, st=None):
    """Read one keyed C3 approval without scanning other approvals or users."""
    record = _doc(_rt(tenant_key, st), _approval_key(approval_id))
    return record if record.get("tenant_key") == tenant_key else None


def _removal_payload(review, item_id, requested_id, validate_only):
    """Build the exact C3 file from the saved review and requested merchant id."""
    metadata = {"MerchantRemovalOrderID": requested_id, "RemovalDisposition": review["disposition"].upper()}
    if review["disposition"] == "Return":
        metadata.update(review["ship_to"])
    content = "".join(f"{k}\t{v}\n" for k, v in metadata.items())
    content += f"MerchantSKU\tSellableQuantity\tUnsellableQuantity\n{review['sku']}\t{review['quantity']}\t0\n"
    return {"operation": "createFeed", "item_ids": [item_id],
            "feedType": "POST_FLAT_FILE_FBA_CREATE_REMOVAL", "marketplaceIds": [review["marketplace"]],
            "content": content, "validate_only": validate_only}


def _validated_removal(tenant_key, item, st):
    """Permit replacement only when the keyed audit proves an exact local no-send validation."""
    try:
        claim = item.get("removalApproval") or {}
        saved = removal_approval(tenant_key, claim.get("approvalId"), st=st)
        if not saved:
            return None
        prior, receipt, review = saved["claim"], saved["receipt"], saved["review"]
        fingerprint = hashlib.sha256(json.dumps({**review, "fingerprint": None}, sort_keys=True).encode()).hexdigest()
        if (prior != claim or prior["state"] != "Validated" or prior["review"] != review
                or saved["decision"] != "approved" or not saved["approved_by"]
                or saved["approved_by"] != prior["approvedBy"] or saved["item_ids"] != [item["id"]]
                or review["tenant_key"] != tenant_key or review["item_id"] != item["id"]
                or review["fingerprint"] != fingerprint or review.get("reason") is not None
                or receipt.get("sent") is not False or receipt.get("validated") is not True
                or receipt.get("approval_checked") is not False or type(receipt.get("rows")) is not int
                or receipt["rows"] != 1 or receipt.get("response") or prior.get("feedId")
                or set(receipt) - {"sent", "validated", "approval_checked", "rows", "tenant_key", "approval_id",
                                   "item_ids", "kind", "operation", "method", "path"}
                or review["disposition"] not in ("Return", "Disposal")
                or type(review["quantity"]) is not int or review["quantity"] <= 0
                or not re.fullmatch(r"[A-Z0-9]{1,10}", prior["requestedRemovalId"])):
            return None
        payload = _removal_payload(review, item["id"], prior["requestedRemovalId"], True)
        if json.dumps(saved["writes"], sort_keys=True, allow_nan=False) != json.dumps(
                [{"kind": "removal_order", "payload": payload}], sort_keys=True, allow_nan=False):
            return None
        for field, expected in (("tenant_key", tenant_key), ("approval_id", prior["approvalId"]),
                                ("item_ids", [item["id"]]), ("kind", "removal_order"),
                                ("operation", "createFeed"), ("method", "POST"),
                                ("path", "feeds/2021-06-30/feeds")):
            if field in receipt and receipt[field] != expected:
                return None
        return saved
    except (KeyError, TypeError, ValueError):
        return None


def approve_removal(tenant_key, item_id, *, user, reviewed, validate_only=True, st=None):
    """Claim one reviewed sellable removal and call only the C3 named-write door."""
    st = _rt(tenant_key, st)
    if getattr(st, "key", tenant_key) != tenant_key:
        raise PermissionError("The approval store belongs to another workspace.")
    name = _removal_user(st, tenant_key, user)
    if not isinstance(reviewed, str) or not reviewed.strip() or type(validate_only) is not bool:
        raise ValueError("Reload and review this removal before approval.")
    review = removal_review(tenant_key, item_id, st=st)
    if review["reason"]:
        raise ValueError(review["reason"])
    if review["fingerprint"] != reviewed:
        raise ValueError("The sellable stock, disposition or ship-to changed. Reload and review this removal again.")
    approval_id = "asr_" + uuid.uuid4().hex
    requested_id = uuid.uuid4().hex[:10].upper()
    payload = _removal_payload(review, item_id, requested_id, validate_only)
    claim = {"approvalId": approval_id, "approvedBy": name, "approvedAt": _stamp(_now()),
             "state": "Claimed", "review": review, "requestedRemovalId": requested_id,
             "reason": "Approval claimed. Reconcile its saved receipt before another removal."}

    replay = {}

    def take(item):
        prior = _validated_removal(tenant_key, item, st) if item.get("removalApproval") else None
        if item.get("removalApproval") and not prior:
            raise ValueError("This item already has a removal claim. Reconcile its saved receipt.")
        current = removal_review(tenant_key, item_id, st=st)
        if current.get("reason") or current.get("fingerprint") != reviewed:
            raise ValueError("The removal changed. Reload and review it again.")
        if prior and validate_only and prior["review"]["fingerprint"] == reviewed:
            replay.update(_public(item))
            return item
        item["removal"] = {**(item.get("removal") or {}), "sellable_quantity": review["sellable"]}
        item.update(_volume_fields(item))
        item["removalApproval"] = claim
        item["status"] = "Accepted"
        return item
    _update_one(st, item_id, take)
    if replay:
        return replay
    approval = {"tenant_key": tenant_key, "decision": "approved", "approved_by": name,
                "item_ids": [item_id], "writes": [{"kind": "removal_order", "payload": payload}],
                "review": review, "claim": claim}
    st.update(_approval_key(approval_id), lambda _old: approval)
    from harness import amazon_client
    attempted = False
    try:
        latest = removal_review(tenant_key, item_id, st=st, claim_id=approval_id)
        if latest.get("reason") or latest.get("fingerprint") != reviewed:
            raise ValueError("The reviewed removal changed before send. Reconcile the claim and review the latest stock and settings.")
        attempted = True
        receipt = amazon_client.send_named_write(tenant_key, "removal_order", payload, approval_id=approval_id)
        if receipt.get("sent") is False and receipt.get("validated") is True and validate_only:
            result = {"state": "Validated", "reason": "File validated locally. No removal order was created."}
        elif (not validate_only and receipt.get("sent") is True and receipt.get("approval_checked") is True
              and (receipt.get("response") or {}).get("feedId")):
            result = {"state": "Submitted", "feedId": receipt["response"]["feedId"],
                      "reason": "Feed submitted. Await Amazon processing before confirming an order."}
        else:
            result = {"state": "Reconcile", "reason": "The send outcome is uncertain. Reconcile this approval before another removal."}
    except Exception as exc:
        refused = isinstance(exc, getattr(amazon_client, "AmazonWriteRefused", ()))
        blocked = not attempted or refused or getattr(exc, "status", None) in (400, 403)
        receipt = {"sent": False if blocked else None}
        result = {"state": "Blocked" if blocked else "Reconcile",
                  "reason": (str(exc) if not attempted else
                             "Check this workspace's removal use case and settings. Reconcile this approval."
                             if blocked else "The send outcome is unknown. Reconcile this approval with Amazon before another removal.")}
    final = {**claim, **result}
    st.update(_approval_key(approval_id), lambda doc: {**doc, "receipt": receipt, "claim": final})
    out = {}

    def finish(item):
        if (item.get("removalApproval") or {}).get("approvalId") != approval_id:
            raise ValueError("The removal claim changed. Reconcile its receipt.")
        item["removalApproval"] = final
        if result["state"] == "Validated":
            item["status"] = "Open"
        out.update(_public(item))
        return item
    _update_one(st, item_id, finish)
    return out


def on_decision(tenant_key, item_id, decision, reason, *, user=None, reviewed=None, validate_only=None, st=None):
    """Approve a reviewed removal through C3 or record another App decision without sending."""
    if decision not in DECISIONS:
        raise ValueError("Decision must be approved or dismissed.")
    st = _rt(tenant_key, st)
    action = _paths(st, KEY_ITEMS, [("items", item_id, "action")])[0]
    if decision == "approved" and action == REMOVE:
        return approve_removal(tenant_key, item_id, user=user, reviewed=reviewed, validate_only=validate_only, st=st)
    return update_item(tenant_key, item_id, status=DECISIONS[decision], note=reason or None,
                       user=user or "operator", st=st)


# --------------------------------------------------------------------------- rule 8 and rule 13

_MONTH = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")


def _dashboard_period(start, end):
    """Use inclusive calendar dates, defaulting to the last 30 days."""
    def day(value, last=False):
        if value is None:
            return None
        value = str(value)
        try:
            if _MONTH.fullmatch(value):
                first = dt.date.fromisoformat(value + "-01")
                return ((first.replace(day=28) + dt.timedelta(days=4)).replace(day=1) - dt.timedelta(days=1)
                        if last else first)
            parsed = dt.date.fromisoformat(value)
            if parsed.isoformat() == value:
                return parsed
        except ValueError:
            pass
        raise ValueError("Use a date like 2026-10-20.")
    finish = day(end, True) or _now().date()
    begin = day(start) or finish - dt.timedelta(days=29)
    if begin > finish:
        raise ValueError("The period start must not be after its end.")
    return begin.isoformat(), finish.isoformat()


def _dashboard_snapshot(cols, end):
    """Select one planning snapshot as of the period end."""
    date = f"TRY_CAST({_first_of(cols, ('_snapshot_date', 'snapshot_date'), 10)} AS DATE)"
    return (f"{date} = (SELECT MAX({date}) FROM {PLANNING} WHERE {date} <= CAST(? AS DATE)) "
            f"AND {_col(cols, 'sku')} IS NOT NULL", [end])


def _dashboard_band_columns(cols):
    bands = [_dbl(cols, f"inv_age_{stem}_days") for stem, _label, _days in BANDS]
    fine = [_dbl(cols, "inv_age_366_to_455_days"), _dbl(cols, "inv_age_456_plus_days")]
    bands[-1] = f"COALESCE({bands[-1]}, {fine[0]} + {fine[1]})"
    return bands


def _dashboard_units_sql(cols):
    bands = _dashboard_band_columns(cols)
    return (f"COALESCE({_dbl(cols, 'inventory_supply_at_fba')}, {_dbl(cols, 'available')}, "
            f"{' + '.join(f'({b})' for b in bands)})")


def _dashboard_action_sql(cols):
    action = _col(cols, "recommended_action")
    return (f"{action} IS NOT NULL AND LOWER({action}) NOT IN "
            "('none', 'no action', 'no action required', 'no recommendation')")


def _dashboard_has_age(cols):
    return ("sku" in cols and bool(cols & {"_snapshot_date", "snapshot_date"})
            and all(f"inv_age_{stem}_days" in cols for stem, _label, _days in BANDS[:-1])
            and ("inv_age_365_plus_days" in cols
                 or {"inv_age_366_to_455_days", "inv_age_456_plus_days"} <= cols))


def _dashboard_figure(identity, label, unit, source, points=(), reason=None):
    points = [{"label": str(key), "value": float(value)} for key, value in points]
    return {"id": identity, "label": label, "value": None if reason else sum(p["value"] for p in points),
            "unit": unit, "series": [] if reason else points, "source_table": "ut_" + source,
            "validated": False, "reason": reason}


def _dashboard_planning(cur, end):
    cols = _columns(cur, PLANNING)
    bands = _dashboard_band_columns(cols)
    available = _dashboard_has_age(cols)
    reason = None if available else "Amazon inventory age is unavailable."
    age = _dashboard_figure("aged_units", "Units by age", "units", PLANNING, reason=reason)
    action = _dashboard_figure("proposed_action_units", "Units with a proposed action", "units", PLANNING,
                               reason="Amazon proposed actions are unavailable.")
    if not available:
        return [age, action]
    where, args = _dashboard_snapshot(cols, end)
    sums = ", ".join(f"SUM({b})" for b in bands)
    missing = " OR ".join(f"({b}) IS NULL" for b in bands)
    count, unknown, *totals = cur.execute(
        f"SELECT COUNT(*), COUNT(*) FILTER (WHERE {missing}), {sums} FROM {PLANNING} WHERE {where}",
        args).fetchone()
    if not count:
        for figure in (age, action):
            figure.update(value=None, series=[], reason="No Amazon inventory snapshot on or before this date.")
        return [age, action]
    if unknown:
        age.update(value=None, series=[], reason="Amazon inventory age measurements are missing.")
    else:
        age = _dashboard_figure("aged_units", "Units by age", "units", PLANNING,
                                zip((label for _stem, label, _days in BANDS), totals))
    if "recommended_action" in cols:
        units = _dashboard_units_sql(cols)
        sql = (f"SELECT {_col(cols, 'recommended_action')}, SUM({units}), "
               f"COUNT(*) FILTER (WHERE {units} IS NULL) "
               f"FROM {PLANNING} WHERE {where} AND {_dashboard_action_sql(cols)} "
               "GROUP BY 1 ORDER BY 1")
        actions = list(_read_rows(cur, sql, args))
        if any(missing for _label, _units, missing in actions):
            action["reason"] = "Amazon proposed action quantities are missing."
        else:
            action = _dashboard_figure("proposed_action_units", "Units with a proposed action", "units", PLANNING,
                                       ((label, units) for label, units, _missing in actions
                                        if units is not None and units > 0))
        action["basis"] = "Amazon recommended actions in the planning snapshot"
    return [age, action]


_DASHBOARD_FEES = ((STORAGE, "storage_fees", "Storage fees", "estimated_monthly_storage_fee", storage_month_sql),
                   (LONG_TERM, "long_term_storage_fees", "Long term fees", "amount_charged", long_term_month_sql))


def _dashboard_fees(cur, start, end):
    figures = []
    for table, identity, label, fee, month_sql in _DASHBOARD_FEES:
        cols = _columns(cur, table)
        if fee not in cols or not cols & ({"month", "month_of_charge"} if table == STORAGE
                                         else {"snapshot_date", "_period_start"}):
            figures.append(_dashboard_figure(identity, label, "currency", table,
                                             reason=f"{SOURCE_NAMES[table]} is unavailable."))
            continue
        sql = (f"SELECT {_currency_sql(cols)}, {month_sql(cols)}, SUM({_dbl(cols, fee)}) FROM {table} "
               f"WHERE {month_sql(cols)} BETWEEN ? AND ? GROUP BY 1, 2 ORDER BY 1, 2")
        currencies = {}
        for currency, month, total in _read_rows(cur, sql, [start[:7], end[:7]]):
            currencies.setdefault(currency, []).append((month, total if total is not None else float('nan')))
        if not currencies:
            figures.append(_dashboard_figure(identity, label, "currency", table,
                                             reason="No fee months in this period."))
        for currency, points in currencies.items():
            figures.append(_dashboard_figure(f"{identity}_{currency}", f"{label} ({currency})", currency, table,
                                             points, reason="The fee currency is unknown."
                                             if currency == UNKNOWN_CURRENCY else None))
    return figures


def _dashboard_expected(cur, start, end):
    """Reconcile displayed aggregates through separate source queries."""
    expected = {}
    cols = _columns(cur, PLANNING)
    if _dashboard_has_age(cols):
        where, args = _dashboard_snapshot(cols, end)
        bands = _dashboard_band_columns(cols)
        values = ", ".join(f"('{label}', {value})"
                           for (_stem, label, _days), value in zip(BANDS, bands))
        sql = (f"SELECT b.label, SUM(b.units), COUNT(*), COUNT(b.units) FROM {PLANNING} "
               f"CROSS JOIN LATERAL (VALUES {values}) b(label, units) WHERE {where} GROUP BY b.label")
        source_bands = list(_read_rows(cur, sql, args))
        if source_bands and all(count == known for _label, _units, count, known in source_bands):
            expected["aged_units"] = ("ut_" + PLANNING, "units",
                                      {label: units for label, units, _count, _known in source_bands})
        if source_bands and "recommended_action" in cols:
            # Group each SKU before the action total so a history row cannot multiply its units.
            units = _dashboard_units_sql(cols)
            sql = (f"WITH skus AS (SELECT {_col(cols, 'sku')} AS sku, {_col(cols, 'recommended_action')} AS action, "
                   f"SUM({units}) AS units, COUNT(*) FILTER (WHERE {units} IS NULL) AS missing "
                   f"FROM {PLANNING} WHERE {where} AND {_dashboard_action_sql(cols)} GROUP BY 1, 2) "
                   "SELECT action, SUM(units), SUM(missing) FROM skus GROUP BY action")
            actions = list(_read_rows(cur, sql, args))
            if not any(missing for _label, _units, missing in actions):
                expected["proposed_action_units"] = ("ut_" + PLANNING, "units",
                                                     {label: units for label, units, _missing in actions
                                                      if units is not None and units > 0})
        names = [name for name in cols if name.startswith("inv_age_")
                 or name in ("inventory_supply_at_fba", "available")]
        invalid = " OR ".join(f"({_col(cols, name)} IS NOT NULL AND ({_dbl(cols, name)} IS NULL "
                              f"OR NOT isfinite({_dbl(cols, name)}) OR {_dbl(cols, name)} < 0))" for name in names)
        bad = cur.execute(f"SELECT COUNT(*) FROM {PLANNING} WHERE {where} AND ({invalid})", args).fetchone()[0]
        if bad:
            expected.pop("aged_units", None)
            expected.pop("proposed_action_units", None)
    for table, identity, _label, fee, month_sql in _DASHBOARD_FEES:
        cols = _columns(cur, table)
        if fee not in cols:
            continue
        sql = (f"SELECT currency, month, SUM(amount), COUNT(*) FILTER (WHERE amount IS NULL OR NOT isfinite(amount)) "
               f"FROM (SELECT {_currency_sql(cols)} AS currency, "
               f"{month_sql(cols)} AS month, {_dbl(cols, fee)} AS amount FROM {table}) source "
               "WHERE month >= ? AND month <= ? GROUP BY currency, month")
        for currency, month, amount, invalid in _read_rows(cur, sql, [start[:7], end[:7]]):
            identity_key = f"{identity}_{currency}"
            expected.setdefault(identity_key, ("ut_" + table, currency, {}))[2][month] = None if invalid else amount
    return expected


def _dashboard_checks(cur, figures, start, end):
    expected = _dashboard_expected(cur, start, end)
    checks = []
    for figure in figures:
        source = expected.get(figure.get("id"))
        reason = figure.get("reason")
        ok = source is not None and not reason
        if ok:
            table, unit, values = source
            points = figure.get("series") or []
            observed = {p.get("label"): p.get("value") for p in points}
            def equal(left, right):
                return (isinstance(left, (int, float)) and isinstance(right, (int, float))
                        and not isinstance(left, bool) and not isinstance(right, bool)
                        and math.isfinite(left) and math.isfinite(right)
                        and math.isclose(left, right, rel_tol=0, abs_tol=1e-6))
            ok = (figure.get("source_table") == table and figure.get("unit") == unit
                  and len(points) == len(observed) and observed.keys() == values.keys()
                  and all(equal(observed[key], value) for key, value in values.items())
                  and all(isinstance(value, (int, float)) for value in values.values())
                  and equal(figure.get("value"), sum(values.values())))
        checks.append({"id": figure.get("id"), "ok": bool(ok),
                       "reason": None if ok else reason or "The figure does not match its source table."})
    return {"ok": bool(checks) and all(check["ok"] for check in checks), "figures": checks}


def dashboard(tenant_key, start=None, end=None, *, st=None, runtime=None):
    """Read one planning snapshot and full fee months intersecting the selected period."""
    start, end = _dashboard_period(start, end)
    st = _rt(tenant_key, st if st is not None else runtime)
    with _reader(tenant_key, st) as cur:
        figures = _dashboard_planning(cur, end) + _dashboard_fees(cur, start, end)
        checks = _dashboard_checks(cur, figures, start, end)
    for figure, check in zip(figures, checks["figures"]):
        figure.update(validated=check["ok"], reason=check["reason"])
        if not check["ok"]:
            figure.update(value=None, series=[])
    return {"kind": SOURCE_KIND, "start": start, "end": end, "figures": figures,
            "validated": checks["ok"], "feePeriod": {"start": start[:7], "end": end[:7]},
            "snapshotAsOf": end}


def _period(start, end):
    for value in (start, end):
        if value is not None and not _MONTH.match(str(value)):
            raise ValueError("A period month must read like 2026-09.")
    if start and end and start > end:
        raise ValueError("The period start must not be after its end.")
    return start or None, end or None


def _in_period(month, start, end):
    if start is None and end is None:
        return True
    return bool(month) and (start is None or month >= start) and (end is None or month <= end)


def _validate_volume(cur, st, rows, tenant_key):
    """Reconcile current Open proposals with source volumes and source quantities, independently of served products."""
    planning, fees, fmap = _planning(cur), _storage_unit_volumes(cur), _fnsku_map(cur)
    fee_by_key = {}
    for key, value in fees.items():
        fee_by_key.setdefault(fmap.get(key) or key, []).append(value)
    removals = {}
    for snap, sku, fnsku, _asin, _title, sellable, quantity, _unsellable, market in _removals(cur) or ():
        key, snap = sku or fmap.get(fnsku) or fnsku, snap or ""
        if key not in removals or snap > removals[key][0]:
            removals[key] = (snap, 0.0, 0.0, market)
        if snap == removals[key][0]:
            old = removals[key]
            removals[key] = (snap, old[1] + (quantity or 0),
                             old[2] + sellable if old[2] is not None and sellable is not None
                             and market and market == old[3] else None, market if market == old[3] else None)
    persisted = _paths(st, KEY_ITEMS, [("state",)])[0] == "ready"
    if persisted:
        proposed, cursor = [], None
        while True:
            page = items(tenant_key, status="Open", cursor=cursor, st=st)
            proposed.extend(i for i in page["items"] if i.get("inReport", True) and i.get("action") in (REMOVE, PRICE_DOWN))
            cursor = page["cursor"]
            if not cursor:
                break
    else:
        proposed = [{**r, "action": r["recommended_action"]} for r in rows or ()
                    if r["recommended_action"] in (REMOVE, PRICE_DOWN)]
    expected, served, matched = [], [], True
    for item in proposed:
        key = item["key"]
        p = (planning or {}).get(item.get("sku")) or {}
        nums, texts = p.get("nums", {}), p.get("text", {})
        candidates = fee_by_key.get(key) or [fees[k] for k in (texts.get("fnsku"), texts.get("asin")) if k in fees]
        unit_volume = candidates[0] if candidates and all(v is not None for v in candidates) \
            and all(math.isclose(v, candidates[0], rel_tol=1e-9, abs_tol=1e-9) for v in candidates) else None
        source = VOLUME_SOURCES["unit"] if unit_volume is not None else None
        if unit_volume is None:
            values = p.get("unit_volumes", [])
            unit_volume = values[0] if values and all(v is not None for v in values) \
                and all(math.isclose(v, values[0], rel_tol=1e-9, abs_tol=1e-9) for v in values) else None
            source = VOLUME_SOURCES["fallback"] if unit_volume is not None else None
        quantity = nums.get("inventory_supply_at_fba")
        if quantity is None:
            quantity = nums.get("available")
        if quantity is None and any(v is not None for v in p.get("bands", {}).values()):
            quantity = sum(v or 0 for v in p["bands"].values())
        if item["action"] == REMOVE:
            _snap, recommended, sellable, _market = removals.get(key, (None, None, None, None))
            wanted = next((v for v in (recommended, nums.get("recommended_removal_quantity"), sellable)
                           if _nonnegative(v) is not None and v > 0 and v == int(v)), None)
            quantity = (int(min(wanted, sellable)) if wanted is not None and _nonnegative(sellable) is not None
                        and sellable == int(sellable) else None)
        quantity = _nonnegative(quantity)
        value = _nonnegative(unit_volume * quantity) if unit_volume is not None and quantity is not None else None
        expected.append(value)
        served.append(_nonnegative(item.get("volume_freed")))
        matched = matched and item.get("volume_unit") == VOLUME_UNIT and item.get("unit_volume_source") == source
        for left, right in ((item.get("unit_volume"), unit_volume), (item.get("proposal_units"), quantity),
                            (item.get("volume_freed"), value)):
            matched = matched and (left is None and right is None or left is not None and right is not None
                                   and math.isclose(left, right, rel_tol=1e-9, abs_tol=1e-9))
    independent = sum(expected) if all(v is not None for v in expected) else None
    app_total = sum(served) if all(v is not None for v in served) else None
    parts = [v for p in (planning or {}).values() for v in p["storage_volumes"]]
    current = _nonnegative(sum(parts)) if planning is not None and all(v is not None for v in parts) else None
    if persisted:
        screen = summary(tenant_key, st=st)["volume"]
        for left, right in ((screen.get("freed"), app_total), (screen.get("current"), current)):
            matched = matched and (left is None and right is None or left is not None and right is not None
                                   and math.isclose(left, right, rel_tol=1e-9, abs_tol=1e-9))
    tied = app_total is None and independent is None or app_total is not None and independent is not None \
        and math.isclose(app_total, independent, rel_tol=1e-9, abs_tol=1e-9)
    return {"ok": bool(matched and tied), "app_total": app_total,
            "independent_total": independent, "unit": VOLUME_UNIT, "proposals": len(proposed),
            "unknown_proposals": sum(v is None for v in expected), "current": current,
            "sources": VOLUME_SOURCES}


def _validate_buckets(tenant_key, st):
    """The served age bucket tiles against `check_buckets`' independent planning sums. With no planning
    source, the tie holds only when every tile serves nothing."""
    if _paths(st, KEY_ITEMS, [("state",)])[0] != "ready":
        return {"ok": True, "tiles": [], "summary": "No refreshed items to tie."}
    tiles = summary(tenant_key, st=st)["buckets"]
    unavailable = all(t["reason"] == BUCKETS_UNAVAILABLE and not t["units"] and not t["fee"] for t in tiles)
    return {"ok": bool(tiles) and (all(t["validated"] for t in tiles) or unavailable),
            "tiles": [{k: t.get(k) for k in ("stem", "units", "fee", "currency", "validated", "reason", "source")}
                      for t in tiles]}


def validate(tenant_key, *, start=None, end=None, st=None, runtime=None, figures=None, figure=None, **period):
    """Reconcile dashboard figures or legacy fees and proposal volume against source queries."""
    st = st if st is not None else runtime
    if figures is not None or figure is not None:
        start, end = _dashboard_period(start, end)
        st = _rt(tenant_key, st)
        with _reader(tenant_key, st) as cur:
            return _dashboard_checks(cur, [figure] if figure is not None else figures, start, end)
    start, end = _period(start, end)
    st = _rt(tenant_key, st)
    conf = settings(tenant_key, st=st)
    with _reader(tenant_key, st) as cur:
        s_cols, l_cols = _columns(cur, STORAGE), _columns(cur, LONG_TERM)
        has_s, has_l = "estimated_monthly_storage_fee" in s_cols, "amount_charged" in l_cols
        if cur is None or not (has_s or has_l):
            return {"ok": False, "app_total": None, "independent_total": None, "currency": None,
                    "detail": {"summary": f"{SOURCE_NAMES[STORAGE]} has not synced yet.", "currencies": {}}}
        rows, _notices, _primary = build_rows(cur, _margins(st), conf)
        volume = _validate_volume(cur, st, rows, tenant_key)
        independent, n_rows = {}, {}
        for has, cols, table, fee, month_sql in (
                (has_s, s_cols, STORAGE, "estimated_monthly_storage_fee", storage_month_sql),
                (has_l, l_cols, LONG_TERM, "amount_charged", long_term_month_sql)):
            if not has:
                continue
            where, args = "TRUE", []
            if start is not None:
                where += f" AND {month_sql(cols)} >= ?"
                args.append(start)
            if end is not None:
                where += f" AND {month_sql(cols)} <= ?"
                args.append(end)
            for currency, total, n in cur.execute(
                    f'SELECT {_currency_sql(cols)}, SUM(TRY_CAST("{fee}" AS DOUBLE)), COUNT(*) FROM {table} '
                    f'WHERE {where} GROUP BY 1', args).fetchall():
                independent[currency] = independent.get(currency, 0.0) + (total or 0.0)
                n_rows[currency] = n_rows.get(currency, 0) + n
    app = {}
    for row in rows or ():
        for point in row.get("fee_history") or ():
            if _in_period(point["month"], start, end):
                app[point["currency"]] = app.get(point["currency"], 0.0) + point["storage"] + point["long_term"]
    currencies = sorted(set(app) | set(independent))
    detail = {cur: {"app_total": round(app.get(cur, 0.0), 2), "independent_total": round(independent.get(cur, 0.0), 2),
                    "ok": abs(app.get(cur, 0.0) - independent.get(cur, 0.0)) < 0.005} for cur in currencies}
    primary = sorted(n_rows.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] if n_rows else None
    buckets = _validate_buckets(tenant_key, st)
    ok = all(d["ok"] for d in detail.values()) and volume["ok"] and buckets["ok"]
    span = (f"{start or 'the first month'} to {end or 'the last month'}" if start or end else "every month")
    tied = ", ".join(f"{c} {d['app_total']:,.2f} against {d['independent_total']:,.2f}" for c, d in detail.items())
    return {"ok": ok, "app_total": detail[primary]["app_total"] if primary else 0.0,
            "independent_total": detail[primary]["independent_total"] if primary else 0.0,
            "currency": primary,
            "detail": {"summary": f"Storage plus long term fees for {span}: {tied or 'no fees'}.",
                       "currencies": detail, "volume": volume, "buckets": buckets, "start": start, "end": end}}


def app_keys(st):
    """Every store document this App owns."""
    months = _doc(st, KEY_HISTORY).get("months") or ()
    return [KEY_SETTINGS, KEY_ITEMS, KEY_HISTORY, KEY_REFRESH, *(_month_key(m) for m in months)]


def remove_app_data(tenant_key, *, st=None):
    """Rule 13: delete this App's own documents. No mirror table and no other document is touched."""
    st = _rt(tenant_key, st)
    deleted, emptied = [], []
    for key in app_keys(st):
        try:
            present = st.get(key) not in (None, {}, [])
        except Exception:                                              # noqa: BLE001
            present = True
        if not present:
            continue
        remover = getattr(st, "delete_document", None)
        if callable(remover):
            try:
                remover(key)
                deleted.append(key)
                continue
            except Exception:                                          # noqa: BLE001
                pass
        # A store without a delete door keeps an empty document in place of the App's data.
        st.update(key, lambda _doc: {})
        emptied.append(key)
    return {"deleted": deleted, "emptied": emptied}