File size: 163,449 Bytes
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
d598032
9e15897
 
d598032
 
 
bea2cff
d598032
 
 
bea2cff
d598032
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
d598032
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
d598032
 
 
9e15897
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
d598032
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
9e15897
d598032
 
9e15897
 
d598032
 
 
 
 
 
9e15897
 
d598032
 
 
9e15897
 
 
d598032
 
 
 
 
 
 
9e15897
 
d598032
 
 
9e15897
 
d598032
 
 
 
9e15897
d598032
 
 
 
9e15897
 
d598032
 
 
9e15897
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
b2aa446
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
7f72224
 
 
9e15897
7f72224
 
 
 
 
 
 
 
 
 
 
9e15897
7f72224
9e15897
 
 
7f72224
 
 
 
 
 
b2aa446
 
 
 
 
 
 
7f72224
 
 
 
 
b2aa446
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
b2aa446
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
b2aa446
7f72224
 
 
b2aa446
7f72224
 
b2aa446
 
7f72224
 
d598032
7f72224
 
 
 
 
 
 
b2aa446
 
 
 
 
 
7f72224
 
 
b2aa446
 
d598032
 
b2aa446
7f72224
 
 
b2aa446
 
7f72224
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
b2aa446
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
9e15897
 
 
 
d598032
9e15897
d598032
 
 
 
 
 
 
9e15897
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
85f794d
 
d598032
 
9e15897
d598032
 
 
 
 
 
b2aa446
 
 
9e15897
 
 
 
d598032
 
 
 
7f72224
d598032
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
9e15897
 
 
d598032
 
 
 
9e15897
d598032
 
 
 
9e15897
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
9e15897
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
b2aa446
 
 
 
 
85f794d
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
b2aa446
 
d598032
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
d598032
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
d598032
 
b2aa446
d598032
b2aa446
 
 
 
 
 
d598032
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
b2aa446
 
d598032
b2aa446
 
 
 
 
 
 
 
d598032
 
b2aa446
85f794d
b2aa446
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
b2aa446
85f794d
b2aa446
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
85f794d
 
d598032
 
 
 
 
 
 
 
 
b2aa446
 
 
 
85f794d
b2aa446
d598032
 
 
 
 
b2aa446
 
d598032
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
b2aa446
85f794d
d598032
 
 
b2aa446
 
 
d598032
 
 
b2aa446
 
d598032
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
9e15897
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
b2aa446
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
9e15897
d598032
9e15897
d598032
 
 
 
 
 
9e15897
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
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
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
"""Amazon operator App: daily ad proposals on SP, SB and SD, gated by profit after COGS and stock cover.

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

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

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

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

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

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

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

#: C7: the App modules whose C4 proposals() feed the inbox, imported lazily by name, in this order.
PROPOSAL_SOURCES = ("modules.restock_planner", "modules.reimbursements", "modules.payouts",
                    "modules.account_health", "modules.returns_refunds", "modules.aged_stock",
                    "modules.opportunity_finder")
#: The App's label when its module carries no APP_LABEL.
APP_LABELS = {"restock_planner": "Restock planner", "reimbursements": "Reimbursements", "payouts": "Payouts and cash",
              "account_health": "Account health", "returns_refunds": "Returns and refunds",
              "aged_stock": "Aged stock", "opportunity_finder": "Opportunity finder"}
#: Inbox statuses. `stale` is an item its App no longer lists; it cannot be approved.
INBOX_OPEN = ("proposed",)
#: The `kind` of an inbox item, and the `source` of a decision record on App items.
APP_KIND = "app"
STALE = "This item is no longer open in its App."
APPROVED_NOTE = "Approved in the Operator inbox."
#: A removal approval names the snapshot its person reviewed, or nothing is decided.
NEED_REVIEW = "Open each removal and review it before you approve."
REVIEW_CHANGED = "This removal changed since you reviewed it. Open it again and review the new numbers."
VALIDATED = "Removal file checked. No removal order was sent to Amazon."
#: The Restock App: its approved batch is one inbound plan, read back by app_approval.
RESTOCK_SOURCE = "modules.restock_planner"
#: The retired Returns and repeat buyers source, and the registry marker holding its item id map.
LEGACY_RETURNS = ("modules.returns_repeat", "returns_repeat")
RETURNS_SOURCE = "modules.returns_refunds"
RETURNS_SPLIT_MARKER = "applications_returns_split_v1"

PROFIT_TABLE = "ut_amazon_sku_profit"
PLANNING_TABLE = "amzn_inventory_planning"

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

_log = logging.getLogger(__name__)


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


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


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


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


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


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


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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


def account_get(username, *, st, fresh=False):
    """Read one tenant-bound account, allowing legacy documents only in explicit offline fixtures."""
    if getattr(st, "operator_legacy_accounts", False):
        return _fixture_accounts(st).get(str(username or "").strip().lower())
    from core import account_rows
    return account_rows.get(username, st=_account_store(st), fresh=fresh)


def account_registry(*, st):
    """Return the tenant-bound lazy account roster for owner resolution."""
    if getattr(st, "operator_legacy_accounts", False):
        return _fixture_accounts(st)
    from core import account_rows
    return account_rows.registry(st=_account_store(st))


def _account_store(st):
    resolve = getattr(st, "_document_store", None)
    if callable(resolve):
        if getattr(st, "store_namespace", ""):
            raise PermissionError("Accounts require an unprefixed tenant store.")
        return resolve()
    return st


def _fixture_accounts(st):
    accounts = _doc(st, "users")
    if accounts.get("__layout__") == "rows" or "accountRows" in accounts:
        raise RuntimeError("The account migration marker is not a roster.")
    return accounts


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


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


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


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

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


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

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


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


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


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


def _held(unit):
    return {"ad_type": unit["ad_type"], "campaign_id": unit["campaign_id"], "campaign": unit["campaign"],
            "ad_group_id": unit["ad_group_id"], "sku": unit["sku"], "asin": unit["asin"],
            **{f: unit.get(f) for f in ("connection_id", "profile_id")}}


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


def _campaign_budgets(cur, data_date):
    """Read each campaign's latest reported daily budget without substituting spend."""
    out = {}
    for ad_type in AD_TYPES:
        table = _ads_table(ad_type, "campaigns")
        cols = _columns(cur, table)
        if not {"date", "campaign_id", "campaign_budget_amount", "profile_id"} <= cols or not ({"_connection_id", "connection_id"} & cols):
            continue
        connection = _text(cols, '_connection_id', 'connection_id')
        cursor = cur.execute(f'SELECT {connection}, CAST(profile_id AS VARCHAR), CAST(campaign_id AS VARCHAR), '
                             f'TRY_CAST(campaign_budget_amount AS DOUBLE) '
                             f'FROM {table} WHERE {_DATE} <= ? QUALIFY ROW_NUMBER() OVER '
                             f'(PARTITION BY {connection}, profile_id, campaign_id ORDER BY {_DATE} DESC) = 1', [data_date])
        while batch := cursor.fetchmany(256):
            for conn, profile, campaign_id, budget in batch:
                out[(conn, profile, ad_type, campaign_id)] = _num(budget)
    return out


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


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


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

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


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


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

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


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


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


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

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


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


def _proposal_values(record):
    """Expose recorded amounts or transitions without guessing a missing value or currency."""
    payload = record.get("payload") if isinstance(record.get("payload"), dict) else {}
    old, new = _change_values(payload)
    old = record.get("current_value") if record.get("current_value") is not None else old
    new = record.get("proposed_value") if record.get("proposed_value") is not None else new
    operation = payload.get("operation")
    unit = record.get("value_unit") or ("currency" if operation in ("set_bid", "set_daily_budget") else "")
    delta = record.get("value_change")
    if delta is None and old is not None and new is not None:
        if (isinstance(old, (int, float)) and not isinstance(old, bool)
                and isinstance(new, (int, float)) and not isinstance(new, bool)):
            delta = round(new - old, 6)
        elif isinstance(old, str) and isinstance(new, str):
            delta = f"{old} to {new}"
    reason = record.get("values_reason") or ("Current value not recorded" if old is None
                                            else "Proposed value not recorded" if new is None else "")
    return {"current_value": old, "proposed_value": new, "value_change": delta,
            "value_unit": unit, "values_reason": reason,
            "currency": record.get("currency") or payload.get("currency")}


def _inbound_fields(record):
    """Retain only the supplied plan link, address and this SKU's prep owner."""
    payload = record.get("payload") if isinstance(record.get("payload"), dict) else {}
    rows = payload.get("items") if isinstance(payload.get("items"), list) else []
    item = next((row for row in rows if isinstance(row, dict) and row.get("msku") == record.get("sku")), {})
    return {"plan_link": record.get("plan_link") or record.get("planLink")
            or payload.get("plan_link") or payload.get("planLink"),
            "ship_from": copy.deepcopy(record.get("ship_from") or record.get("shipFrom") or payload.get("sourceAddress")),
            "prep_owner": record.get("prep_owner") or record.get("prepOwner") or item.get("prepOwner")}


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


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


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


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


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


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


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


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


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


def _stored_sql(pg):
    def entries(expression):
        # Expand in the SELECT list so a join never repeats the parent document per child.
        return (f"jsonb_each({expression})" if pg else
                f"unnest(map_entries(CAST({expression} AS MAP(VARCHAR, JSON))))")

    held_rows = "COALESCE(r -> 'held', '[]')"
    held_rows = f"jsonb_array_elements({held_rows})" if pg else f"unnest(CAST({held_rows} AS JSON[]))"
    placeholder = "%s" if pg else "?"
    docs = f"SELECT key AS name, value FROM {{tbl}} WHERE key IN ({placeholder}, {placeholder})" if pg else (
        f"SELECT * FROM docs WHERE name IN ({placeholder}, {placeholder})")
    return f"""WITH documents AS ({docs}),
      day_doc AS (SELECT value FROM documents ORDER BY (value ->> 'latest') IS NULL LIMIT 1),
      day_entries AS MATERIALIZED (SELECT {entries("COALESCE(value -> 'days', '{}')")} AS entry FROM day_doc),
      day_rows AS MATERIALIZED (SELECT (entry).key AS day, (entry).value AS r FROM day_entries),
      ad_entries AS MATERIALIZED (SELECT day, {entries("COALESCE(r -> 'items', '{}')")} AS entry FROM day_rows),
      ad AS (SELECT (entry).value AS r, day FROM ad_entries),
      app_entries AS MATERIALIZED (SELECT {entries("COALESCE(value -> 'items', '{}')")} AS entry FROM documents),
      app_rows AS MATERIALIZED (SELECT (entry).value AS r FROM app_entries),
      apps AS (SELECT r, left(COALESCE(r ->> 'decided_at', ''), 10) AS day FROM app_rows),
      held AS (SELECT {held_rows} AS r, day FROM day_rows)
      """


_SCREEN_FIELDS = ("id", "status", "owner", "due", "reason", "sku", "asin", "kind", "action", "change", "gate",
                  "ad_type", "campaign", "campaign_id", "day", "data_date", "spend", "decision_id", "decided_by",
                  "decided_at", "note", "cause", "outcome_at", "app", "source_kind", "source_module", "item_id",
                  "first_seen", "last_seen", "undo_of", "review", "current_value", "proposed_value", "value_change",
                  "value_unit", "values_reason", "currency", "plan_link", "ship_from", "prep_owner")


def _screen_expression(field, pg=False):
    """Project legacy payload leaves in SQL without returning its full document."""
    fallback = {
        "first_seen": "r -> 'firstSeen'",
        "currency": "r -> 'payload' -> 'currency'",
        "current_value": "CASE r -> 'payload' ->> 'operation' "
                         "WHEN 'set_bid' THEN r -> 'payload' -> 'previous_bid' "
                         "WHEN 'set_daily_budget' THEN COALESCE(NULLIF(r -> 'payload' -> 'previous_daily_budget', 'null'), r -> 'payload' -> 'previous_budget') "
                         "WHEN 'pause_ads' THEN r -> 'payload' -> 'previous_state' "
                         "WHEN 'enable_ads' THEN r -> 'payload' -> 'previous_state' END",
        "proposed_value": "CASE r -> 'payload' ->> 'operation' "
                          "WHEN 'set_bid' THEN r -> 'payload' -> 'bid' "
                          "WHEN 'set_daily_budget' THEN r -> 'payload' -> 'daily_budget' "
                          "WHEN 'pause_ads' THEN r -> 'payload' -> 'state' "
                          "WHEN 'enable_ads' THEN r -> 'payload' -> 'state' "
                          "WHEN 'add_negative_keyword' THEN r -> 'payload' -> 'keyword_text' END",
        "value_unit": "CASE WHEN (r -> 'payload' ->> 'operation') IN ('set_bid', 'set_daily_budget') "
                      f"THEN {'jsonb_build_object' if pg else 'json_object'}('unit', 'currency') -> 'unit' END",
        "plan_link": "COALESCE(NULLIF(r -> 'planLink', 'null'), r -> 'payload' -> 'planLink', r -> 'payload' -> 'plan_link')",
        "ship_from": "COALESCE(NULLIF(r -> 'shipFrom', 'null'), r -> 'payload' -> 'sourceAddress')",
        "prep_owner": "COALESCE(NULLIF(r -> 'prepOwner', 'null'), "
                      f"(SELECT entry.value -> 'prepOwner' FROM {'jsonb_array_elements' if pg else 'json_each'}"
                      "(COALESCE(NULLIF(r -> 'payload' -> 'items', 'null'), '[]')) entry "
                      "WHERE entry.value ->> 'msku' = r ->> 'sku' LIMIT 1))",
    }.get(field)
    return f"COALESCE(NULLIF(r -> '{field}', 'null'), {fallback})" if fallback else f"r -> '{field}'"


def withheld(count):
    """Return only the count of proposals the viewer cannot read."""
    return {"withheldCount": count, "withheldMessage": f"{count} items need access you do not have" if count else ""}


def _source_ok(predicate, source):
    try:
        return predicate(source) is True
    except Exception:
        return False


def _blocked_ids(tenant_key, st, ids, source_allowed):
    """Check each requested proposal before a refresh, claim or decision can write."""
    if source_allowed is None:
        return 0
    with _screen_store(tenant_key, st) as (execute, pg, _names):
        p = "%s" if pg else "?"
        blocked = 0
        for pid in ids:
            row = execute(_stored_sql(pg) + f"SELECT r, source_app FROM (SELECT r, TRUE AS source_app FROM apps "
                          f"UNION ALL SELECT r, FALSE AS source_app FROM ad) t "
                          f"WHERE r ->> 'id' = {p} LIMIT 1", [pid]).fetchone()
            rec = (row[0] if isinstance(row[0], dict) else json.loads(row[0])) if row else None
            source = rec.get("source_module") if row and row[1] else SOURCE_KIND
            blocked += not _source_ok(source_allowed, source)
    return blocked


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


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


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


# --------------------------------------------------------------------------- sent change results and Undo

def _result_proposal(tenant_key, st, proposal_id):
    """Project one proposal in SQL instead of loading the days document."""
    if str(proposal_id).startswith("run_"):
        return _row_get(_schedule_store(tenant_key, st), KEY_SCHEDULE_RUNS, proposal_id)
    with _screen_store(tenant_key, st) as (execute, pg, _names):
        p = "%s" if pg else "?"
        row = execute(_stored_sql(pg) + f"SELECT r FROM ad WHERE r ->> 'id' = {p} LIMIT 1",
                      [str(proposal_id)]).fetchone()
    return (row[0] if isinstance(row[0], dict) else json.loads(row[0])) if row else None


def _sent_change(tenant_key, st, proposal_id):
    prop = _result_proposal(tenant_key, st, proposal_id)
    if prop is None:
        raise KeyError(NOT_FOUND)
    if prop.get("status") != "sent" or not isinstance(prop.get("sent_payload"), dict):
        raise ValueError("Results and Undo need a sent change with its saved payload.")
    try:
        sent = dt.datetime.fromisoformat(prop["outcome_at"].replace("Z", "+00:00"))
    except (KeyError, TypeError, ValueError):
        raise ValueError("The send date is missing. Results and Undo cannot be dated.") from None
    return prop, sent.date()


def _result_scope(prop, cols, start, end):
    payload = prop["sent_payload"]
    where = f"{_DATE} BETWEEN ? AND ? AND {_text(cols, 'campaign_id')} = ?"
    args = [start.isoformat(), end.isoformat(), payload.get("campaign_id")]
    where += f" AND {_text(cols, '_connection_id', 'connection_id')} = ?"
    args.append(str(payload.get("connection_id") or ""))
    for field in ("profile_id", "ad_group_id"):
        if payload.get(field):
            where += f" AND {_text(cols, field)} = ?"
            args.append(str(payload[field]))
    if payload.get("ad_ids") and "ad_id" in cols:
        where += ' AND CAST("ad_id" AS VARCHAR) IN (' + ", ".join("?" for _ in payload["ad_ids"]) + ")"
        args.extend(str(ad_id) for ad_id in payload["ad_ids"])
    if payload.get("sku") or payload.get("asin"):
        sku, asin = _text(cols, "advertised_sku"), _text(cols, "asin", "advertised_asin")
        where += f" AND ({sku} = ? OR (({sku} IS NULL OR {sku} = '') AND {asin} = ?))"
        args.extend([payload.get("sku") or "", payload.get("asin") or ""])
    # Advertised-product reports often carry no target id. Name that scope in results().
    if payload.get("target_id") and "target_id" in cols:
        where += ' AND CAST("target_id" AS VARCHAR) = ?'
        args.append(str(payload["target_id"]))
    return where, args


def _result_cogs(tenant_key, st, pairs):
    """Read COGS only for the current result page's SKUs and ASINs."""
    backend = _screen_backend(st, tenant_key)
    if backend is None:
        return _profit(st)
    from core import store_pg, user_table_rows
    name = getattr(st, "store_key", lambda key: key)("user_tables")
    skus = sorted({str(sku) for sku, _asin in pairs if sku})
    asins = sorted({str(asin) for _sku, asin in pairs if asin})
    if not skus and not asins:
        return {}
    if user_table_rows.rows_mode(name, backend.tenant_slug):
        source = "SELECT value AS r FROM {tbl} WHERE table_key = %s"
        table, args = "user_table_records", [PROFIT_TABLE]
    else:
        source = ("SELECT p.value AS r FROM {tbl} d, LATERAL "
                  "jsonb_each(COALESCE(d.value -> %s -> 'rows', '{{}}')) p WHERE d.key = %s")
        table, args = "store_kv", [PROFIT_TABLE, name]
    tests = []
    for field, values in (("sku", skus), ("asin", asins)):
        if values:
            tests.append(f"trim(r ->> '{field}') IN (" + ", ".join("%s" for _ in values) + ")")
            args.extend(values)
    sql = ("WITH cells AS (" + source + ") SELECT trim(r ->> 'sku'), trim(r ->> 'asin'), "
           "r ->> 'cogs_per_unit' FROM cells WHERE " + " OR ".join(tests) + " GROUP BY 1, 2, 3")
    out = {}
    with store_pg._pool().connection() as con:
        cursor = con.execute(store_pg._q(sql, table, backend.tenant_slug), args)
        while batch := cursor.fetchmany(256):
            for sku, asin, raw in batch:
                cogs = _num(raw)
                old = out.get(sku)
                if old and old["cogs_per_unit"] != cogs:
                    cogs = None
                out[sku] = {"linked": cogs is not None, "cogs_per_unit": cogs, "asin": asin or ""}
    return out


def _result_window(tenant_key, st, cur, prop, start, end, *, spend_only=False):
    days = (end - start).days + 1
    out = {"start_on": start.isoformat(), "end_on": end.isoformat(), "expected_days": days,
           "days_with_data": 0, "ad_profit_after_cogs": None, "acos": None, "ad_cost": None,
           "ad_sales": None, "cogs": None, "unlinked_skus": 0, "rows_without_sku": 0,
           "state": "unavailable", "reason": None}
    if cur is None:
        return {**out, "reason": "The tenant Ads mirror is unavailable."}
    if not all(prop["sent_payload"].get(f) for f in ("connection_id", "profile_id")):
        return {**out, "reason": "The historical connection and Ads profile were not recorded."}
    ad_type = prop["sent_payload"].get("ad_type")
    if ad_type not in ALL_AD_TYPES:
        return {**out, "reason": "The sent change has no supported Ads type."}
    table = _ads_table(ad_type, "advertised_products")
    cols = _columns(cur, table)
    needed = {"date", "campaign_id", "cost"} | (set() if spend_only else {"sales", "orders"})
    if not needed <= cols:
        return {**out, "reason": "Ads report columns are missing: " + ", ".join(sorted(needed - cols)) + "."}
    where, args = _result_scope(prop, cols, start, end)
    metric = lambda field: f'TRY_CAST("{field}" AS DOUBLE)'
    fields = ["cost"] if spend_only else ["cost", "sales", "orders"]
    invalid = " OR ".join(f"({metric(f)} IS NULL OR NOT isfinite({metric(f)}))" for f in fields)
    count, observed, cost, bad = cur.execute(
        f'SELECT COUNT(*), COUNT(DISTINCT {_DATE}), SUM({metric("cost")}), '
        f'COUNT(*) FILTER (WHERE {invalid}) FROM {table} WHERE {where}', args).fetchone()
    out["days_with_data"] = observed
    if not count:
        return {**out, "reason": "No Ads rows exist for this change in this window."}
    if bad:
        return {**out, "reason": "Ads rows contain missing or invalid metrics. No result can be calculated."}
    out.update(ad_cost=round(cost, 2), state="ready" if observed == days else "partial")
    reasons = [] if observed == days else [f"Only {observed} of {days} days have Ads data in this window."]
    if not spend_only:
        sku, asin = _text(cols, "advertised_sku"), _text(cols, "asin", "advertised_asin")
        query = (f'SELECT {sku}, {asin}, SUM({metric("cost")}), SUM({metric("sales")}), '
                 f'SUM({metric("orders")}), COUNT(*) FROM {table} WHERE {where} GROUP BY 1, 2 '
                 'ORDER BY 1 NULLS FIRST, 2 NULLS FIRST LIMIT ? OFFSET ?')
        offset, sales, linked_sales, linked_cost, cogs, linked = 0, 0.0, 0.0, 0.0, 0.0, 0
        unlinked = set()
        while True:
            rows = cur.execute(query, [*args, 256, offset]).fetchall()
            if not rows:
                break
            profit = _result_cogs(tenant_key, st, [(r[0], r[1]) for r in rows])
            by_asin = {p["asin"]: key for key, p in profit.items() if p.get("asin")}
            for sku, asin, spend, revenue, orders, row_count in rows:
                sales += revenue
                sku = str(sku or "").strip() or by_asin.get(str(asin or "").strip(), "")
                info = profit.get(sku)
                if not sku:
                    out["rows_without_sku"] += row_count
                elif not info or not info["linked"]:
                    unlinked.add(sku)
                else:
                    linked += 1
                    linked_sales += revenue
                    linked_cost += spend
                    cogs += orders * info["cogs_per_unit"]
            offset += len(rows)
        out.update(ad_sales=round(sales, 2), acos=round(cost / sales * 100, 2) if sales > 0 else None,
                   cogs=round(cogs, 2) if linked else None, unlinked_skus=len(unlinked),
                   ad_profit_after_cogs=round(linked_sales - linked_cost - cogs, 2) if linked else None)
        if sales <= 0:
            reasons.append("ACOS is unavailable because ad sales are zero or negative.")
        if unlinked or out["rows_without_sku"] or not linked:
            reasons.append("Profit excludes rows without linked COGS. Link the missing SKUs in Command Center.")
        if out["ad_profit_after_cogs"] is None or out["acos"] is None or unlinked or out["rows_without_sku"]:
            out["state"] = "partial"
    out["reason"] = " ".join(reasons) or None
    return out


def _undo_id(proposal_id):
    return "undo_" + hashlib.sha1(str(proposal_id).encode("utf-8")).hexdigest()[:16]


def _undo_payload(prop):
    payload = copy.deepcopy(prop["sent_payload"])
    payload.pop("item_id", None)
    for field in ("schedule_id", "timezone", "weekday", "hour"):
        payload.pop(field, None)
    operation = payload.get("operation")
    if operation in ("set_bid", "set_daily_budget"):
        field = "bid" if operation == "set_bid" else "daily_budget"
        previous = _num(payload.get("previous_" + field))
        if previous is None or previous <= 0:
            raise ValueError(f"The prior {field.replace('_', ' ')} was not saved. Undo is unavailable.")
        payload["previous_" + field], payload[field] = payload.get(field), previous
        change = f"Restore {'bid' if field == 'bid' else 'daily budget'} to {_money(previous)}"
    elif operation == "pause_ads":
        if payload.get("previous_state") != "enabled":
            raise ValueError("The enabled prior state was not proved for every ad. Undo is unavailable.")
        payload.update(operation="enable_ads", state="enabled", previous_state="paused")
        change = "Enable the paused ads"
    else:
        raise ValueError("Undo is available for bid, daily budget and pause changes only.")
    payload["undo_of"] = prop["id"]
    return payload, change


def results(tenant_key, proposal_id, *, st=None, now=None, source_allowed=None):
    """Compare 7 and 14 full days after a sent change with equal windows before it."""
    st, now = _rt(tenant_key, st), now or _now()
    if _blocked_ids(tenant_key, st, [proposal_id], source_allowed):
        return withheld(1)
    prop, sent = _sent_change(tenant_key, st, proposal_id)
    try:
        if prop.get("undo_of"):
            raise ValueError("This item is already an Undo. Propose a new change instead.")
        _undo_payload(prop)
        undo = {"available": True, "reason": None}
    except ValueError as exc:
        undo = {"available": False, "reason": str(exc)}
    existing = _result_proposal(tenant_key, st, _undo_id(proposal_id))
    undo["item"] = _item(existing) if existing else None
    out = {"proposal_id": prop["id"], "sent_at": prop["outcome_at"], "basis": BASELINE_BASIS,
           "acos_basis": "Ad cost divided by ad sales times 100, for all rows in the change's scope.",
           "scope": "The sent campaign, ad group and SKU. Target is matched when the report carries it.",
           "window_basis": "The send day is excluded. Each after window starts the following day.",
           "windows": [], "undo": undo, "budget_spend": None}
    due = any(now.date() >= sent + dt.timedelta(days=n) for n in (7, 14))
    budget = prop["sent_payload"].get("operation") == "set_daily_budget"
    with _reader(tenant_key, st) if due or budget else contextlib.nullcontext(None) as cur:
        for days in (7, 14):
            available = sent + dt.timedelta(days=days)
            window = {"days": days, "available_on": available.isoformat(), "state": "waiting",
                      "reason": f"The {days} day result arrives on {available.isoformat()}.",
                      "before": None, "after": None}
            if now.date() >= available:
                before = _result_window(tenant_key, st, cur, prop, sent - dt.timedelta(days=days),
                                        sent - dt.timedelta(days=1))
                after = _result_window(tenant_key, st, cur, prop, sent + dt.timedelta(days=1), available)
                window.update(before=before, after=after,
                              state="ready" if before["state"] == after["state"] == "ready" else "partial",
                              reason=" ".join(f"{label}: {value['reason']}" for label, value in
                                              (("Before", before), ("After", after)) if value["reason"]) or None)
            out["windows"].append(window)
        if budget:
            end = now.date()
            if existing and existing.get("status") == "sent":
                end = min(end, dt.date.fromisoformat(existing["outcome_at"][:10]))
            out["budget_spend"] = _result_window(tenant_key, st, cur, prop, sent, end, spend_only=True)
            out["budget_spend"]["basis"] = ("Daily campaign spend includes the send and Undo days. "
                                             "Intraday spend cannot be separated. Undo does not reverse past spend.")
    return out


def propose_undo(tenant_key, user, proposal_id, *, st=None, now=None):
    """Create one proposed reversal that needs its own ordinary batch approval."""
    st, now = _rt(tenant_key, st), now or _now()
    who = _editor(st, user)
    prop, _sent = _sent_change(tenant_key, st, proposal_id)
    if prop.get("undo_of"):
        raise ValueError("This item is already an Undo. Propose a new change instead.")
    payload, change = _undo_payload(prop)
    pid = _undo_id(proposal_id)
    day = now.date().isoformat()
    proposal = _proposal(day, prop.get("data_date"), {**prop, "campaign": prop.get("campaign") or prop["campaign_id"]},
                         "bid" if prop["kind"] == "scheduled_change" else prop["kind"], "undo", change, payload,
                         "Restore the saved value from now on. Past spend is not reversed.",
                         "Undo needs a new approval before Amazon Ads receives it.", prop.get("owner"),
                         (now.date() + dt.timedelta(days=DUE_DAYS)).isoformat())
    proposal.update(id=pid, undo_of=prop["id"], proposed_by=who, proposed_at=_stamp(now))
    saved = {}

    def _apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        days = doc.setdefault("days", {})
        for record in days.values():
            existing = (record.get("items") or {}).get(pid)
            if existing:
                saved.clear()
                saved.update(existing)
                return doc
        record = days.setdefault(day, {"built_at": _stamp(now), "data_date": prop.get("data_date"),
                                       "items": {}, "held": [], "spend": {}})
        record.setdefault("items", {})[pid] = proposal
        doc["latest"] = max(days)
        saved.clear()
        saved.update(proposal)
        return doc
    st.update(KEY_DAYS, _apply)
    return _item(saved)


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

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


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


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


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


def _editor(st, user, tenant_key=None):
    """The deciding account's name. PermissionError for a viewer, an inactive or an unknown account."""
    name = user if isinstance(user, str) else user.get("username", "") if isinstance(user, dict) else ""
    name = str(name or "").strip().lower()
    rec = None
    if name:
        try:
            rec = account_get(name, st=st, fresh=True)
        except Exception:                                              # noqa: BLE001
            rec = None
    if not isinstance(rec, dict) or rec.get("active") is False:
        raise PermissionError(READ_ONLY)
    role = str(rec.get("role") or "user").strip().lower()
    if role == "viewer" or rec.get("can_edit") is False or rec.get("canEdit") is False:
        raise PermissionError(READ_ONLY)
    want = str(tenant_key or getattr(st, "key", "") or "").strip().lower()
    if want and str(rec.get("tenant") or "royal-imports").strip().lower() != want:
        raise PermissionError(READ_ONLY)
    return name


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


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


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


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

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


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

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


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

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


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


def _send(st, tenant_key, client, prop, approval_id, *, now=None):
    """One named write for one approved proposal, its outcome stored on its row. Never raises."""
    payload = _write_payload(prop)
    result = None
    if not all(isinstance(payload.get(f), str) and payload[f].strip() for f in ("connection_id", "profile_id")):
        status, cause = "refused", "The Ads connection and profile were not recorded. No write was sent."
    elif client is None:
        status, cause = "refused", NOT_INSTALLED
    else:
        try:
            result = _json_safe(client.send_named_write(tenant_key, prop["kind"], payload,
                                                        approval_id=approval_id, rt=st))
        except Exception as exc:                                       # noqa: BLE001
            status, cause = "refused", _cause(exc)
        else:
            status, cause = "sent", None
    at = _stamp(now or _now())
    try:
        _record_outcome(st, prop["id"], approval_id, prop["kind"], status, cause, result,
                        payload if status == "sent" else None, at)
    except Exception as exc:                                           # noqa: BLE001
        _log.warning("amazon_operator: the outcome of %s could not be stored (%s): %s",
                     prop["id"], type(exc).__name__, exc)
    row = {"id": prop["id"], "status": status, "kind": prop["kind"]}
    if cause:
        row["cause"] = cause
    return row


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


def sent_write(tenant_key, item_id, *, st=None):
    """Return the original stored send and receipt for the client's exact Undo validation."""
    st = _schedule_store(tenant_key, st)
    rec = _row_get(st, KEY_SCHEDULE_RUNS, item_id) if str(item_id).startswith("run_") else _result_proposal(tenant_key, st, item_id)
    return copy.deepcopy(rec) if isinstance(rec, dict) and rec.get("status") == "sent" else None


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


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

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


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


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


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

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


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


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


def _review_of(raw):
    """The removal snapshot a person reviews before approval, or None for an item that needs no review.

    Returns and refunds sends `reviewed` {item id: hash} with `removalPreview`. Aged stock sends `removal_review`
    with its fingerprint. `reviewed` is passed back to the source App exactly as it was read.
    """
    preview, rv = raw.get("removalPreview"), raw.get("removal_review")
    if isinstance(raw.get("reviewed"), dict) and raw["reviewed"] and isinstance(preview, dict):
        arithmetic = preview.get("arithmetic") if isinstance(preview.get("arithmetic"), dict) else None
        return _json_safe({"reviewed": raw["reviewed"], "fate": preview.get("fate"), "units": preview.get("units"),
                           "sku": preview.get("sku"), "unitCost": preview.get("unitCost"),
                           "currency": preview.get("currency"), "arithmetic": arithmetic,
                           "shipTo": preview.get("shipTo") if isinstance(preview.get("shipTo"), dict) else None,
                           "validateOnly": raw.get("validateOnly") is not False, "canSubmit": False})
    if isinstance(rv, dict) and isinstance(rv.get("fingerprint"), str) and rv["fingerprint"].strip():
        return _json_safe({"reviewed": rv["fingerprint"], "fate": rv.get("disposition"), "units": rv.get("quantity"),
                           "sku": rv.get("sku"), "sellable": rv.get("sellable"), "marketplace": rv.get("marketplace"),
                           "arithmetic": None,
                           "shipTo": rv.get("ship_to") if isinstance(rv.get("ship_to"), dict) else None,
                           "validateOnly": raw.get("validateOnly", rv.get("validateOnly", rv.get("validate_only"))) is not False,
                           "canSubmit": True})
    return None


def _legacy_ids(st):
    """{old Returns item id: new id} once the registry's Returns split is done, else None."""
    try:
        marker = st.get(RETURNS_SPLIT_MARKER)
    except Exception:                                                  # noqa: BLE001
        return None
    if not isinstance(marker, dict) or marker.get("state") != "done" or not isinstance(marker.get("itemIds"), dict):
        return None
    return {str(k): str(v) for k, v in marker["itemIds"].items() if str(k).strip() and str(v).strip()}


def _rekey_legacy(doc, mapping, at):
    """Move retired Returns and repeat buyers inbox rows onto Returns and refunds. Pure and idempotent.

    A mapped open row takes its new id, or is dropped when the new App already listed it. An unmapped open
    row turns stale, so it can be dismissed. A decided row keeps its id, decision and history.
    """
    doc = doc if isinstance(doc, dict) else {}
    items = doc.get("items") if isinstance(doc.get("items"), dict) else {}
    label = APP_LABELS.get(RETURNS_SOURCE.rsplit(".", 1)[-1])
    for iid, rec in list(items.items()):
        if not isinstance(rec, dict) or (rec.get("source_module") not in LEGACY_RETURNS
                                         and rec.get("source_kind") not in LEGACY_RETURNS):
            continue
        new_item = (mapping or {}).get(str(rec.get("item_id") or ""))
        if rec.get("status") not in INBOX_OPEN + ("stale",):
            if new_item:
                items[iid] = {**rec, "source_kind": _short(RETURNS_SOURCE), "source_module": RETURNS_SOURCE,
                              "item_id": new_item, "app": label, "legacy_item_id": rec.get("item_id")}
            continue
        if not new_item:
            if rec.get("status") != "stale":
                items[iid] = {**rec, "status": "stale", "cause": STALE, "last_seen": at}
            continue
        new_iid = _inbox_id(_short(RETURNS_SOURCE), new_item)
        items.pop(iid)
        if new_iid not in items:
            items[new_iid] = {**rec, "id": new_iid, "source_kind": _short(RETURNS_SOURCE),
                              "source_module": RETURNS_SOURCE, "item_id": new_item, "app": label,
                              "legacy_id": iid, "legacy_item_id": rec.get("item_id"), "last_seen": at}
    doc["items"] = items
    return doc


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


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


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


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


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


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


def _source_fn(rec, attr):
    """(callable or None, plain cause or None) for the source App's attr."""
    name, app = rec.get("source_module") or "", rec.get("app") or "Its App"
    if name not in PROPOSAL_SOURCES:
        return None, f"{app} is not an inbox source, so it could not take this decision."
    mod, _missing = _load_source(name)
    fn = getattr(mod, attr, None) if mod is not None else None
    return (fn, None) if callable(fn) else (None, f"{app} is not installed, so it could not take this decision.")


def _accepted(fn, offered):
    """The keywords in offered that fn declares. Nothing is retried, so an unknown keyword is never sent."""
    try:
        params = inspect.signature(fn).parameters
    except (TypeError, ValueError):
        return {}
    if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):
        return dict(offered)
    return {k: v for k, v in offered.items() if k in params}


def _refusal(app, exc):
    detail = _plain(exc).rstrip(".")
    return f"{app} could not take this decision: {detail}." if detail else f"{app} could not take this decision."


def _hand_back(tenant_key, rec, decision, reason, *, user=None, review=None):
    """Call the source App's on_decision once with the decider and the reviewed snapshot. (cause, result)."""
    fn, cause = _source_fn(rec, "on_decision")
    if fn is None:
        return cause, None
    offered = {"user": user}
    if review is not None and decision == "approved":
        offered.update(reviewed=copy.deepcopy(review["reviewed"]), validate_only=review["validateOnly"])
        if not review["validateOnly"] and "validate_only" not in _accepted(fn, offered):
            return "Submission is unavailable for this removal.", None
    try:
        result = fn(tenant_key, rec["item_id"], decision, reason, **_accepted(fn, offered))
    except Exception as exc:                                           # noqa: BLE001
        return _refusal(rec.get("app") or "Its App", exc), None
    return None, result


def _validated(result):
    """True when a removal approval only checked its file and sent no order, so the item stays open."""
    claim = result.get("removalApproval") if isinstance(result, dict) else None
    return isinstance(claim, dict) and claim.get("state") == "Validated"


def _checked_reviews(ids, inbox, status, reviews):
    """Bind each removal's fingerprint and chosen mode before any decision is recorded."""
    if status != "approved":
        return {}
    given = reviews if isinstance(reviews, dict) else {}
    out = {}
    for iid in ids:
        rec = inbox[iid]
        review = rec.get("review") if isinstance(rec.get("review"), dict) else None
        if review is None or rec.get("status") not in INBOX_OPEN:
            continue
        if iid not in given or given[iid] in (None, "", {}):
            raise ValueError(NEED_REVIEW)
        supplied = given[iid]
        chosen = supplied if isinstance(supplied, dict) and "reviewed" in supplied else {
            "reviewed": supplied, "validateOnly": review.get("validateOnly", True)}
        if type(chosen.get("validateOnly")) is not bool:
            raise ValueError(NEED_REVIEW)
        if _json_safe(chosen.get("reviewed")) != review.get("reviewed"):
            raise ValueError(REVIEW_CHANGED)
        out[iid] = {"reviewed": copy.deepcopy(review["reviewed"]), "validateOnly": chosen["validateOnly"]}
    return out


def _decide_apps(st, tenant_key, ids, inbox, status, note, who, at, *, reviews=None):
    """Claim inbox items and hand each source one batch or each item one decision with its reviewed snapshot."""
    reviewed = _checked_reviews(ids, inbox, status, reviews)
    rows, eligible = {}, []
    for iid in ids:
        current = inbox[iid].get("status")
        if current == "stale" and status == "approved":
            rows[iid] = {"id": iid, "status": "skipped", "current": "stale",
                         "cause": f"{STALE} It cannot be approved."}
        elif current not in INBOX_OPEN + ("stale",):
            rows[iid] = {"id": iid, "status": "skipped", "current": current, "cause": _skip_cause(current, status)}
        else:
            eligible.append(iid)
    if not eligible:
        return rows, None
    decision_id = ("apd_" if status == "approved" else "dsm_") + uuid.uuid4().hex[:16]
    record = {"id": decision_id, "decision": status, "source": APP_KIND, "by": who, "at": at,
              "item_ids": eligible, "note": note,
              "sources": {iid: {"module": inbox[iid].get("source_module"), "item_id": inbox[iid].get("item_id")}
                          for iid in eligible}}
    if reviewed:
        record["reviews"] = {iid: reviewed[iid]["reviewed"] for iid in eligible if iid in reviewed}
        record["review_modes"] = {iid: reviewed[iid]["validateOnly"] for iid in eligible if iid in reviewed}
    _put_decision(st, record)
    claimed = {}

    def _claim_apps(doc):
        doc = doc if isinstance(doc, dict) else {}
        claimed.clear()
        for iid in eligible:
            rec = (doc.get("items") or {}).get(iid)
            if isinstance(rec, dict) and rec.get("status") in INBOX_OPEN + ("stale",):
                if status == "approved":
                    if rec.get("status") == "stale":
                        continue
                    current_review = (rec.get("review") or {}).get("reviewed")
                    if current_review != reviewed.get(iid, {}).get("reviewed"):
                        raise ValueError(REVIEW_CHANGED)
                claimed[iid] = rec["status"]
                rec.update(status=status, decision_id=decision_id, decided_by=who, decided_at=at, note=note,
                           cause=None if rec["status"] in INBOX_OPEN else rec.get("cause"))
        return doc
    st.update(KEY_INBOX, _claim_apps)
    reason = note or (APPROVED_NOTE if status == "approved" else "")
    done, batches, single = [], {}, []
    for iid in eligible:
        if iid not in claimed:
            rows[iid] = {"id": iid, "status": "skipped", "current": "decided", "cause": _skip_cause("decided", status)}
        elif claimed[iid] == "stale":
            # A stale item is gone from its App, so dismissing it closes it here only.
            done.append(iid)
            rows[iid] = {"id": iid, "status": status, "app": inbox[iid].get("app")}
        elif _source_fn(inbox[iid], "on_batch_decision")[0] is not None:
            batches.setdefault(inbox[iid]["source_module"], []).append(iid)
        else:
            single.append(iid)
    for name, members in batches.items():
        rec = inbox[members[0]]
        fn = _source_fn(rec, "on_batch_decision")[0]
        try:
            fn(tenant_key, [inbox[iid]["item_id"] for iid in members], status, reason, approval_id=decision_id)
            cause = None
        except Exception as exc:                                       # noqa: BLE001
            cause = _refusal(rec.get("app") or "Its App", exc)
        for iid in members:
            if cause:
                _reopen(st, iid, cause)
                rows[iid] = {"id": iid, "status": "refused", "cause": cause, "app": inbox[iid].get("app")}
            else:
                done.append(iid)
                rows[iid] = {"id": iid, "status": status, "app": inbox[iid].get("app")}
    for iid in single:
        rec = inbox[iid]
        cause, result = _hand_back(tenant_key, rec, status, reason, user=who,
                                   review=reviewed.get(iid))
        if cause:
            _reopen(st, iid, cause)
            rows[iid] = {"id": iid, "status": "refused", "cause": cause, "app": rec.get("app")}
        elif iid in reviewed and _validated(result):
            _reopen(st, iid, VALIDATED)
            rows[iid] = {"id": iid, "status": "validated", "cause": VALIDATED, "app": rec.get("app")}
        else:
            done.append(iid)
            rows[iid] = {"id": iid, "status": status, "app": rec.get("app")}
    if sorted(done) != sorted(eligible):
        record["item_ids"] = [iid for iid in eligible if iid in done]
        _put_decision(st, record)
    return rows, decision_id


def app_approval(tenant_key, approval_id, *, st=None):
    """C3 reader for Restock's inbound plan and its cancel: the Operator approval bound to the saved batch.

    Returns {tenant_key, decision, approved_by, item_ids, writes, original_plan?} or None. The batch must hold
    only Restock items this approval decided, and each write is a payload Restock saved before its send.
    """
    key = str(tenant_key or "").strip().lower()
    aid = str(approval_id or "")
    if not key or not aid.startswith("apd_"):
        return None
    st = _schedule_store(key, st)
    rec = (_doc(st, KEY_DECISIONS).get("decisions") or {}).get(aid)
    if (not isinstance(rec, dict) or rec.get("decision") != "approved" or rec.get("source") != APP_KIND
            or not str(rec.get("by") or "").strip()):
        return None
    sources = rec.get("sources") if isinstance(rec.get("sources"), dict) else {}
    approved = {str(src.get("item_id")) for iid, src in sources.items()
                if iid in (rec.get("item_ids") or ()) and isinstance(src, dict) and src.get("module") == RESTOCK_SOURCE}
    mod, _missing = _load_source(RESTOCK_SOURCE)
    binding = getattr(mod, "inbound_plan_binding", None) if mod is not None else None
    if not approved or not callable(binding):
        return None
    try:
        batch = binding(key, aid)
    except Exception:                                                  # noqa: BLE001
        return None
    if (not isinstance(batch, dict) or batch.get("tenantKey") != key or batch.get("approvalId") != aid
            or not set(map(str, batch.get("itemIds") or ())) or not set(map(str, batch["itemIds"])) <= approved):
        return None
    submitted = [str(i) for i in batch.get("submittedItemIds") or ()]
    if not submitted or not set(submitted) <= set(map(str, batch["itemIds"])):
        return None
    writes = [{"kind": "inbound_plan", "payload": copy.deepcopy(a["namedWriteIntent"])}
              for a in batch.get("attempts") or () if isinstance(a, dict) and isinstance(a.get("namedWriteIntent"), dict)]
    writes += [{"kind": "inbound_plan_cancel", "payload": copy.deepcopy(a["payload"])}
               for a in batch.get("cancelAttempts") or ()
               if isinstance(a, dict) and a.get("event") == "request" and isinstance(a.get("payload"), dict)]
    out = {"tenant_key": key, "decision": "approved", "approved_by": rec["by"], "item_ids": submitted,
           "writes": writes}
    plan = batch.get("inboundPlanId")
    created = any(isinstance(a, dict) and isinstance(a.get("result") or a.get("response"), dict)
                  and (a.get("result") or a.get("response")).get("inboundPlanId") == plan
                  for a in batch.get("attempts") or ())
    if isinstance(plan, str) and plan and created:
        out["original_plan"] = {"kind": "inbound_plan", "sent": True, "tenant_key": key, "inboundPlanId": plan,
                                "approval_id": aid, "item_ids": list(submitted)}
    return out


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


def _dashboard_period(start, end):
    first, last = dt.date.fromisoformat(str(start)), dt.date.fromisoformat(str(end))
    if first > last:
        raise ValueError("The Dashboard start must be on or before its end.")
    return first, last


def _weekly_counts(tenant_key, start, end, st, *, independent=False):
    """Aggregate stored events in SQL and return bounded weekly batches without a row cap."""
    first, last = _dashboard_period(start, end)
    counts = {key: {} for key in ("approved", "refused", "sent")}
    documents = (KEY_DAYS, KEY_INBOX) if independent else (KEY_DECISIONS, KEY_OUTCOMES)
    with _screen_store(tenant_key, st, documents) as (execute, pg, _names):
        each = "jsonb_each" if pg else "json_each"
        array = "jsonb_array_elements_text" if pg else "json_each"
        p = "%s" if pg else "?"
        docs = f"SELECT key AS name, value FROM {{tbl}} WHERE key IN ({p}, {p})" if pg else (
            f"SELECT * FROM docs WHERE name IN ({p}, {p})")
        if independent:
            source = _stored_sql(pg) + """, proposals AS (SELECT r FROM ad UNION ALL SELECT r FROM apps),
              events AS (
                SELECT 'approved' AS status, r ->> 'id' AS id, r ->> 'decided_at' AS event_at FROM proposals
                  WHERE (r ->> 'status') IN ('approved', 'sent', 'refused') AND (r ->> 'decision_id') IS NOT NULL
                UNION ALL
                SELECT r ->> 'status', r ->> 'id', r ->> 'outcome_at' FROM ad
                  WHERE r ->> 'status' IN ('sent', 'refused')) """
        else:
            identity = "i.value" if pg else "CAST(i.value AS TEXT)"
            source = f"""WITH documents AS ({docs}), events AS (
              SELECT 'approved' AS status, {identity} AS id, d.value ->> 'at' AS event_at FROM documents,
                LATERAL {each}(COALESCE(value -> 'decisions', '{{}}')) d,
                LATERAL {array}(COALESCE(d.value -> 'item_ids', '[]')) i
                WHERE d.value ->> 'decision' = 'approved'
              UNION ALL
              SELECT o.value ->> 'status', o.key, o.value ->> 'at' FROM documents,
                LATERAL {each}(COALESCE(value -> 'items', '{{}}')) o
                WHERE o.value ->> 'status' IN ('sent', 'refused')) """
        result = execute(source + f"""SELECT status, CAST(date_trunc('week', CAST(left(event_at, 10) AS DATE)) AS DATE),
          count(DISTINCT id) FROM events WHERE left(event_at, 10) BETWEEN {p} AND {p}
          GROUP BY 1, 2 ORDER BY 2, 1""", [first.isoformat(), last.isoformat()])
        while batch := result.fetchmany(128):
            for status, week, count in batch:
                counts[status][str(week)] = int(count)
    week = first - dt.timedelta(days=first.weekday())
    series = {key: [] for key in counts}
    while week <= last:
        for key in counts:
            series[key].append({"date": week.isoformat(), "x": week.isoformat(),
                                "value": counts[key].get(week.isoformat(), 0)})
        if (last - week).days < 7:
            break
        week += dt.timedelta(days=7)
    return series


def _figure_numbers_valid(figure):
    """Accept finite JSON numbers and nullable series points, never boolean number aliases."""
    def finite(value):
        try:
            return type(value) in (int, float) and math.isfinite(value)
        except OverflowError:
            return False

    return (isinstance(figure, dict) and finite(figure.get("value"))
            and isinstance(figure.get("series"), list)
            and all(isinstance(point, dict) and "value" in point
                    and (point["value"] is None or finite(point["value"])) for point in figure["series"]))


def validate_dashboard_figure(tenant_key, start, end, figure, *, st=None):
    """Tie one weekly figure to stored proposal rows, independent of the event-log aggregation."""
    if not _figure_numbers_valid(figure):
        return {"ok": False, "detail": "Weekly figure needs finite numbers and numeric or null series points."}
    st = _rt(tenant_key, st)
    figure_id = str(figure.get("id", ""))
    if figure_id not in ("proposals_approved", "proposals_refused", "proposals_sent"):
        return {"ok": False, "detail": "Unknown weekly figure."}
    key = figure_id.removeprefix("proposals_")
    expected = _weekly_counts(tenant_key, start, end, st, independent=True)[key]
    ok = figure.get("series") == expected and figure.get("value") == sum(row["value"] for row in expected)
    return {"ok": ok, "detail": "Stored proposals tie." if ok else "Stored proposals do not tie."}


def dashboard(tenant_key, start, end, *, st=None):
    """Serve C6 figures after independent validation without building proposals or reading another App."""
    _dashboard_period(start, end)
    st = _rt(tenant_key, st)
    from modules import amazon_operator_overview
    report = amazon_operator_overview.overview(tenant_key, start, end, st=st, limit=1)
    tie = amazon_operator_overview.validate(tenant_key, start, end, st=st, report=report)
    figures = []
    for key, label, unit in (("acos", "ACoS", "percent"), ("tacos", "TACoS", "percent"),
                             ("spend", "Spend", "money"), ("ad_sales", "Ad sales", "money"),
                             ("organic_sales", "Organic sales", "money")):
        available = tie["ok"] and report["totals"][key] is not None
        figures.append({"id": key, "label": label, "unit": unit,
                        "value": report["totals"][key] if available else None,
                        "series": [{"date": row["date"], "x": row["date"], "value": row[key]} for row in report["daily"]]
                                  if available else [],
                        "source_table": "amzn_economics" if key in ("tacos", "organic_sales") else
                                        "amzn_ads_sp_campaigns,amzn_ads_sb_campaigns,amzn_ads_sd_campaigns",
                        "validated": bool(available),
                        "reason": None if available else report["reason"] or (
                            tie["detail"] if not tie["ok"] else "No sales in this period.")})
    try:
        weekly = _weekly_counts(tenant_key, start, end, st)
        weekly_figures = []
        for key, label in (("approved", "Approved"), ("refused", "Refused"), ("sent", "Sent")):
            figure = {"id": f"proposals_{key}", "label": label, "unit": "count", "series": weekly[key],
                      "value": sum(row["value"] for row in weekly[key]),
                      "source_table": KEY_DECISIONS if key == "approved" else KEY_OUTCOMES}
            checked = validate_dashboard_figure(tenant_key, start, end, figure, st=st)
            figure.update(validated=checked["ok"], reason=None if checked["ok"] else checked["detail"])
            if not checked["ok"]:
                figure.update(value=None, series=[])
            weekly_figures.append(figure)
        figures.extend(weekly_figures)
    except Exception:                                                  # noqa: BLE001
        _log.exception("Operator weekly figures could not be validated")
        figures.extend({"id": f"proposals_{key}", "label": label, "unit": "count", "value": None,
                        "series": [], "source_table": KEY_DECISIONS if key == "approved" else KEY_OUTCOMES,
                        "validated": False, "reason": "Weekly proposals are unavailable."}
                       for key, label in (("approved", "Approved"), ("refused", "Refused"), ("sent", "Sent")))
    return {"figures": figures}


def validate_figure(tenant, figure, *, start, end, st):
    """Validate a C6 figure against independent source evidence and its complete served payload."""
    figure_id = figure.get("id") if isinstance(figure, dict) else None
    result = {"ok": False, "id": figure_id, "reason": "Unknown Operator figure."}
    overview_fields = {"acos": ("ACoS", "percent"), "tacos": ("TACoS", "percent"),
                       "spend": ("Spend", "money"), "ad_sales": ("Ad sales", "money"),
                       "organic_sales": ("Organic sales", "money")}
    weekly_fields = {"proposals_approved": "Approved", "proposals_refused": "Refused", "proposals_sent": "Sent"}
    if not isinstance(figure_id, str) or figure_id not in (*overview_fields, *weekly_fields):
        return result
    if not _figure_numbers_valid(figure):
        result["reason"] = "Operator figure needs finite numbers and numeric or null series points."
        return result
    try:
        st = _rt(tenant, st)
        if figure_id in weekly_fields:
            checked = validate_dashboard_figure(tenant, start, end, figure, st=st)
            source = KEY_DECISIONS if figure_id == "proposals_approved" else KEY_OUTCOMES
            ok = (checked["ok"] is True and figure.get("label") == weekly_fields[figure_id]
                  and figure.get("unit") == "count" and figure.get("source_table") == source)
            reason = checked["detail"] if not checked["ok"] else "Weekly figure payload does not tie."
        else:
            from modules import amazon_operator_overview
            report = amazon_operator_overview.overview(tenant, start, end, st=st, limit=1)
            checked = amazon_operator_overview.validate(tenant, start, end, st=st, report=report)
            label, unit = overview_fields[figure_id]
            source = ("amzn_economics" if figure_id in ("tacos", "organic_sales") else
                      "amzn_ads_sp_campaigns,amzn_ads_sb_campaigns,amzn_ads_sd_campaigns")
            expected = [{"date": row["date"], "x": row["date"], "value": row[figure_id]} for row in report["daily"]]
            value = report["totals"][figure_id]
            ok = (checked["ok"] is True and value is not None and figure.get("value") == value
                  and figure.get("series") == expected and figure.get("source_table") == source
                  and figure.get("label") == label and figure.get("unit") == unit)
            reason = checked["detail"] if not checked["ok"] else "Overview figure payload does not tie."
        result.update(ok=bool(ok and figure.get("validated") is True),
                      reason="Figure ties to independently checked source rows." if ok and figure.get("validated") is True else reason)
    except Exception as exc:                                           # noqa: BLE001
        from core.request_timing import raise_if_resource_error
        raise_if_resource_error(exc)
        result["reason"] = "Operator figure could not be independently validated."
    return result


SCHEDULE_WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")


def _schedule_cells(report):
    """Group retained daily slots by weekday without filling an unreported occurrence with zero."""
    from modules import amazon_operator_hourly as hourly
    buckets = {(weekday, hour): [] for weekday in range(7) for hour in range(24)}
    for row in report["daily_rows"]:
        buckets[(dt.date.fromisoformat(row["date"]).weekday(), row["hour"])].append(row)
    cells = []
    for (weekday, hour), slots in buckets.items():
        active = [row for row in slots if row["expected_occurrences"]]
        cell = {"weekday": weekday, "day": SCHEDULE_WEEKDAYS[weekday], "hour": hour,
                "dates": [row["date"] for row in slots], "observed": any(row["observed"] for row in active),
                "occurrences": sum(row["occurrences"] for row in active),
                "expected_occurrences": sum(row["expected_occurrences"] for row in active),
                "metric_occurrences": {key: sum(row["metric_occurrences"][key] for row in active)
                                       for key in hourly.METRICS}}
        reasons = list(dict.fromkeys(row["reason"] for row in slots if row.get("reason")))
        for metric in hourly.METRICS:
            complete = active and all(row[metric] is not None and math.isfinite(row[metric])
                and row["metric_occurrences"][metric] >= row["expected_occurrences"] for row in active)
            value = sum(row[metric] for row in active) if complete else None
            cell[metric] = value if value is not None and math.isfinite(value) else None
        cell["acos"] = hourly._acos(cell["spend"], cell["sales"])
        cell["reason"] = ("No selected dates for this weekday." if not slots else
                          " ".join(reasons) or ("Some metrics are unavailable." if any(
                              cell[key] is None for key in hourly.METRICS) else None))
        cells.append(cell)
    return cells


def schedule_grid(tenant_key, campaign_id, start, end, *, st=None, ad_type="sp", connection_id=None, profile_id=None):
    """Serve the weekday axis of the existing scoped SP hourly report without another source path."""
    from modules import amazon_operator_hourly as hourly
    st = _rt(tenant_key, st)
    report = hourly.by_hour(tenant_key, campaign_id, start, end, st=st, ad_type=ad_type,
                            connection_id=connection_id, profile_id=profile_id)
    report["grid"] = _schedule_cells(report)
    report["validation"] = validate_schedule_grid(tenant_key, campaign_id, start, end, st=st, report=report,
        ad_type=ad_type, connection_id=connection_id, profile_id=profile_id)
    if report["state"] == "ready" and not report["validation"]["ok"]:
        report.update(state="partial", reason=report["validation"]["detail"])
    return report


def validate_schedule_grid(tenant_key, campaign_id, start, end, *, st=None, report=None, ad_type="sp",
                           connection_id=None, profile_id=None):
    """Tie every retained day to the daily report before checking the weekday grid payload."""
    from modules import amazon_operator_hourly as hourly
    if report is None:
        return schedule_grid(tenant_key, campaign_id, start, end, st=st, ad_type=ad_type,
            connection_id=connection_id, profile_id=profile_id)["validation"]
    checked = hourly.validate(tenant_key, campaign_id, start, end, st=st, report=report, ad_type=ad_type,
                              connection_id=connection_id, profile_id=profile_id)
    if report.get("grid") != _schedule_cells(report):
        checked["ok"] = False
        checked["detail"] += " Weekday figures do not tie to independently checked daily slots."
    return checked


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


# --------------------------------------------------------------------------- approved schedules, one store row per record

def _schedule_store(tenant_key, st=None):
    st = _rt(tenant_key, st)
    if str(getattr(st, "key", tenant_key)).lower() != str(tenant_key).lower():
        raise PermissionError("The schedule store belongs to another tenant.")
    _screen_backend(st, tenant_key)
    return st


def _row_key(namespace, identity):
    if namespace not in ROW_NAMESPACES or not isinstance(identity, str) or not identity or "/" in identity:
        raise ValueError("Invalid schedule record identity.")
    return namespace + "/" + identity


def _row_get(st, namespace, identity):
    value = st.get(_row_key(namespace, str(identity)), fresh=True)
    return value if isinstance(value, dict) and value else None


def _row_update(st, namespace, identity, body):
    result = st.update(_row_key(namespace, identity), body, flush="sync")
    if result is None or result is False:
        raise RuntimeError("The schedule record was not durably saved.")
    return _row_get(st, namespace, identity)


def _row_page(tenant_key, st, namespace, *, cursor=None, limit=50):
    """Page individual authored rows in SQL, keeping every schedule and claim reachable."""
    if namespace not in ROW_NAMESPACES:
        raise ValueError("Unknown schedule namespace.")
    try:
        size = min(200, int(limit))
    except (ValueError, TypeError):
        raise ValueError("Use a whole page size.") from None
    if size < 1:
        raise ValueError("Use a positive page size.")
    after = str(cursor or "")
    prefix = namespace + "/"
    backend = _screen_backend(st, tenant_key)
    if backend is not None:
        from core import store_pg
        prefix = getattr(st, "store_key", lambda key: key)(prefix)
        with store_pg._pool().connection() as con:
            rows = con.execute(store_pg._q("SELECT key, value FROM {tbl} WHERE starts_with(key, %s) "
                               "AND key > %s ORDER BY key LIMIT %s", "store_kv", backend.tenant_slug),
                               [prefix, prefix + after, size + 1]).fetchall()
    else:
        names = getattr(st, "list_keys", None)
        if not callable(names):
            raise RuntimeError("The isolated schedule store needs list_keys.")
        keys = sorted(key for key in names(prefix) if key.startswith(prefix) and key > prefix + after)
        rows = [(key, st.get(key)) for key in keys[:size + 1]]
    values = [value if isinstance(value, dict) else json.loads(value) for _key, value in rows[:size]]
    return {"items": values, "cursor": rows[size - 1][0][len(prefix):] if len(rows) > size else None, "limit": size}


def schedule_records(tenant_key, *, st=None, cursor=None, limit=50, runs=False):
    st = _schedule_store(tenant_key, st)
    return _row_page(tenant_key, st, KEY_SCHEDULE_RUNS if runs else KEY_SCHEDULES, cursor=cursor, limit=limit)


def schedule_switch(tenant_key, *, st=None):
    value = _schedule_store(tenant_key, st).get(KEY_SETTINGS, fresh=True)
    return isinstance(value, dict) and value.get("schedules_enabled") is True


def set_schedule_switch(tenant_key, user, enabled, *, st=None):
    st = _schedule_store(tenant_key, st)
    _editor(st, user, tenant_key)
    if type(enabled) is not bool:
        raise ValueError("Choose on or off.")
    def apply(doc):
        doc = doc if isinstance(doc, dict) else {}
        doc["schedules_enabled"] = enabled
        return doc
    result = st.update(KEY_SETTINGS, apply, flush="sync")
    if result is None or result is False:
        raise RuntimeError("The schedule switch was not saved.")
    return {"enabled": schedule_switch(tenant_key, st=st)}


def _schedule_binding(record):
    fields = ("connection_id", "profile_id", "campaign_id", "ad_type")
    if record.get("ad_type") not in AD_TYPES or not all(isinstance(record.get(f), str) and record[f].strip() for f in fields):
        raise ValueError("Choose a campaign with a verified connection and Ads profile.")
    return {f: record[f] for f in fields}


def _schedule_scope(record):
    binding = _schedule_binding(record)
    return ('CAST(_connection_id AS VARCHAR) = ? AND CAST(profile_id AS VARCHAR) = ? '
            'AND CAST(campaign_id AS VARCHAR) = ?'), [binding[f] for f in ("connection_id", "profile_id", "campaign_id")]


def _schedule_timezone(tenant_key, st, record):
    from zoneinfo import ZoneInfo
    where, args = _schedule_scope(record)
    with _reader(tenant_key, st) as cur:
        table = "amzn_ads_sp_hourly"
        if cur is None or record["ad_type"] != "sp" or not {"timezone", "_connection_id", "profile_id", "campaign_id"} <= _columns(cur, table):
            raise ValueError("The Ads profile timezone is unavailable. Sync hourly data first.")
        rows = cur.execute(f"SELECT DISTINCT timezone FROM {table} WHERE {where} LIMIT 2", args).fetchall()
    if len(rows) != 1 or not rows[0][0]:
        raise ValueError("The Ads profile timezone is ambiguous or unavailable.")
    timezone = str(rows[0][0])
    ZoneInfo(timezone)
    return timezone


def _schedule_entity_page(tenant_key, st, record, action, *, cursor=None, limit=50):
    where, args = _schedule_scope(record)
    if action not in ("set_bid", "pause_ads"):
        raise ValueError("Choose a bid change or pause.")
    entity = "target_id" if action == "set_bid" else "ad_id"
    table = _ads_table(record["ad_type"], "targeting" if action == "set_bid" else "advertised_products")
    size = max(1, min(200, int(limit)))
    offset = int(cursor or 0)
    if offset < 0:
        raise ValueError("Invalid entity page.")
    with _reader(tenant_key, st) as cur:
        required = {"_connection_id", "profile_id", "campaign_id", "ad_group_id", entity, "date"}
        if cur is None or not required <= _columns(cur, table):
            raise ValueError("Trusted campaign entities are unavailable. Sync Amazon Ads first.")
        rows = cur.execute(f'SELECT DISTINCT CAST(ad_group_id AS VARCHAR), CAST("{entity}" AS VARCHAR) '
                           f'FROM {table} WHERE {where} AND ad_group_id IS NOT NULL AND "{entity}" IS NOT NULL '
                           f'AND CAST("{entity}" AS VARCHAR) <> \'\' ORDER BY 1, 2 LIMIT ? OFFSET ?',
                           [*args, size + 1, offset]).fetchall()
    return {"items": [{"ad_group_id": group, entity: identity} for group, identity in rows[:size]],
            "cursor": str(offset + size) if len(rows) > size else None, "limit": size}


def schedule_targets(tenant_key, record, action, *, st=None, cursor=None, limit=50):
    st = _schedule_store(tenant_key, st)
    return _schedule_entity_page(tenant_key, st, record, action, cursor=cursor, limit=limit)


def _schedule_evidence(tenant_key, st, record, rule):
    """Prove membership and prior values from the exact connection's latest entity observations."""
    where, args = _schedule_scope(record)
    bid = rule["action"] == "set_bid"
    table = _ads_table(record["ad_type"], "targeting" if bid else "advertised_products")
    entity, field = ("target_id", "bid") if bid else ("ad_id", "state")
    ids = [rule["target_id"]] if bid else rule["ad_ids"]
    previous = []
    with _reader(tenant_key, st) as cur:
        if cur is None or not {"_connection_id", "profile_id", "campaign_id", "ad_group_id", entity, "date"} <= _columns(cur, table):
            raise ValueError("Trusted campaign entities are unavailable.")
        for identity in ids:
            scope = where + f' AND CAST(ad_group_id AS VARCHAR) = ? AND CAST("{entity}" AS VARCHAR) = ?'
            values = [*args, rule["ad_group_id"], identity]
            value = f'CAST("{field}" AS VARCHAR)' if field in _columns(cur, table) else "NULL"
            rows = cur.execute(f"SELECT DISTINCT {value} FROM {table} WHERE {scope} AND "
                               f'TRY_CAST("date" AS DATE) = (SELECT MAX(TRY_CAST("date" AS DATE)) FROM {table} WHERE {scope}) LIMIT 2',
                               [*values, *values]).fetchall()
            if not rows:
                raise ValueError("The scheduled entity does not belong to this campaign, connection and profile.")
            previous.append(rows[0][0] if len(rows) == 1 else None)
    if bid:
        return {"previous_bid": _num(previous[0]), "source": table}
    known = {str(value or "").lower() for value in previous}
    return {"previous_state": next(iter(known)) if len(known) == 1 and known <= {"enabled", "paused"} else None,
            "source": table}


def _clean_schedule(tenant_key, st, body):
    from zoneinfo import ZoneInfo
    record = _schedule_binding(body)
    record["timezone"] = _schedule_timezone(tenant_key, st, record)
    ZoneInfo(record["timezone"])
    record["weekday_convention"] = "monday_zero"
    rules, seen = [], set()
    if not isinstance(body.get("rules"), list) or not body["rules"]:
        raise ValueError("Choose weekdays, hours and an action.")
    for raw in body["rules"]:
        if not isinstance(raw, dict) or type(raw.get("weekday")) is not int or type(raw.get("hour")) is not int:
            raise ValueError("Use Monday-zero weekdays and whole hours.")
        weekday, hour, action = raw["weekday"], raw["hour"], raw.get("action")
        if weekday not in range(7) or hour not in range(24) or (weekday, hour) in seen:
            raise ValueError("Each weekday and hour needs one rule.")
        seen.add((weekday, hour))
        if action not in ("set_bid", "pause_ads") or not str(raw.get("ad_group_id") or "").strip():
            raise ValueError("Choose a bid change or pause and a trusted ad group.")
        rule = {"weekday": weekday, "hour": hour, "action": action, "ad_group_id": str(raw["ad_group_id"])}
        if action == "set_bid":
            value = _num(raw.get("value"))
            if isinstance(raw.get("value"), bool) or value is None or value <= 0 or not raw.get("target_id"):
                raise ValueError("Choose a trusted target and a positive bid.")
            rule.update(value=value, target_id=str(raw["target_id"]))
        else:
            ids = raw.get("ad_ids")
            if not isinstance(ids, list) or not ids or any(not isinstance(i, str) or not i.strip() for i in ids):
                raise ValueError("Choose the exact ads to pause.")
            rule.update(value="paused", ad_ids=sorted(set(ids)))
        _schedule_evidence(tenant_key, st, record, rule)
        rules.append(rule)
    record["rules"] = sorted(rules, key=lambda r: (r["weekday"], r["hour"]))
    return record


def _schedule_digest(record):
    fields = ("campaign_id", "ad_type", "connection_id", "profile_id", "timezone", "weekday_convention", "rules")
    return hashlib.sha256(json.dumps({k: record.get(k) for k in fields}, sort_keys=True).encode()).hexdigest()


def save_schedule(tenant_key, user, body, *, schedule_id=None, st=None, now=None):
    st, now = _schedule_store(tenant_key, st), now or _now()
    who = _editor(st, user, tenant_key)
    cleaned = _clean_schedule(tenant_key, st, body)
    identity = schedule_id or "sch_" + uuid.uuid4().hex
    def apply(prior):
        if schedule_id and not prior:
            raise KeyError(schedule_id)
        return {**cleaned, "id": identity, "enabled": False, "approved_by": None, "approved_at": None,
                "approval_digest": None, "updated_by": who, "updated_at": _stamp(now),
                "created_at": (prior or {}).get("created_at") or _stamp(now)}
    return _row_update(st, KEY_SCHEDULES, identity, apply)


def approve_schedules(tenant_key, user, identities, *, st, now=None):
    who, now = _editor(st, user, tenant_key), now or _now()
    rows = []
    for identity in identities:
        def apply(record):
            if not record:
                raise KeyError(identity)
            cleaned = _clean_schedule(tenant_key, st, record)
            if _schedule_digest(cleaned) != _schedule_digest(record):
                raise ValueError("Campaign binding changed. Save and approve the schedule again.")
            return {**record, "enabled": True, "approved_by": who, "approved_at": _stamp(now),
                    "approval_digest": _schedule_digest(record)}
        rows.append(_row_update(st, KEY_SCHEDULES, identity, apply))
    return {"rows": rows, "approved": len(rows), "sent": 0}


def set_schedule_enabled(tenant_key, user, identity, enabled, *, st=None):
    st = _schedule_store(tenant_key, st)
    _editor(st, user, tenant_key)
    if type(enabled) is not bool:
        raise ValueError("Choose on or off.")
    def apply(record):
        if not record:
            raise KeyError(identity)
        if enabled and (not record.get("approved_by") or record.get("approval_digest") != _schedule_digest(record)):
            raise ValueError("Approve this schedule before switching it on.")
        return {**record, "enabled": enabled}
    return _row_update(st, KEY_SCHEDULES, identity, apply)


def schedule_approval(tenant_key, schedule_id, *, st=None):
    """Read a fresh exact approval, refusing off switches, edits and untrusted entity bindings."""
    st = _schedule_store(tenant_key, st)
    if not schedule_switch(tenant_key, st=st):
        return None
    record = _row_get(st, KEY_SCHEDULES, schedule_id)
    if not record or record.get("enabled") is not True or not record.get("approved_by") or not record.get("approved_at"):
        return None
    if record.get("approval_digest") != _schedule_digest(record):
        return None
    try:
        at = dt.datetime.fromisoformat(record["approved_at"].replace("Z", "+00:00"))
        if at.utcoffset() is None or _schedule_timezone(tenant_key, st, record) != record["timezone"]:
            return None
        for rule in record["rules"]:
            _schedule_evidence(tenant_key, st, record, rule)
    except (ValueError, KeyError, TypeError):
        return None
    return record


def claim_schedule_run(tenant_key, schedule_id, rule, *, st, now):
    """Commit a local date/rule/hour claim before any named write, including repeated DST hours."""
    from zoneinfo import ZoneInfo
    record = schedule_approval(tenant_key, schedule_id, st=st)
    if not record or rule not in record["rules"]:
        return None
    local = now.astimezone(ZoneInfo(record["timezone"]))
    if rule["weekday"] != local.weekday() or rule["hour"] != local.hour:
        return None
    identity = "run_" + hashlib.sha256(json.dumps([schedule_id, local.date().isoformat(), rule["weekday"], rule["hour"]]).encode()).hexdigest()
    evidence = _schedule_evidence(tenant_key, st, record, rule)
    payload = {**_schedule_binding(record), **evidence, "operation": rule["action"], "ad_group_id": rule["ad_group_id"],
               "schedule_id": schedule_id, "item_id": identity, "timezone": record["timezone"],
               "weekday": rule["weekday"], "hour": rule["hour"]}
    if rule["action"] == "set_bid":
        payload.update(target_id=rule["target_id"], bid=rule["value"])
    else:
        payload.update(ad_ids=rule["ad_ids"], state=rule["value"])
    claimed = []
    def apply(prior):
        claimed.clear()
        if prior:
            return prior
        claimed.append(True)
        return {"id": identity, "kind": "scheduled_change", "schedule_id": schedule_id,
                **_schedule_binding(record), "status": "unknown", "cause": "Claimed. Send outcome is not confirmed.",
                "approved_by": record["approved_by"], "approved_at": record["approved_at"],
                "claimed_at": _stamp(now), "local_date": local.date().isoformat(), "timezone": record["timezone"],
                "weekday": local.weekday(), "hour": local.hour, "rule": rule, "sent_payload": payload,
                "previous_value": evidence.get("previous_bid" if rule["action"] == "set_bid" else "previous_state"),
                "new_value": rule["value"], "source": evidence["source"], "result": None}
    saved = _row_update(st, KEY_SCHEDULE_RUNS, identity, apply)
    return saved if claimed else None


def finish_schedule_run(tenant_key, identity, *, st, status, result=None, cause=None, now=None):
    if status not in ("sent", "refused", "unknown"):
        raise ValueError("Invalid schedule outcome.")
    def apply(record):
        if not record:
            raise KeyError(identity)
        return {**record, "status": status, "result": _json_safe(result), "cause": cause,
                "outcome_at": _stamp(now or _now()), "sent_at": (result or {}).get("sent_at") if isinstance(result, dict) else None}
    return _row_update(_schedule_store(tenant_key, st), KEY_SCHEDULE_RUNS, identity, apply)


def _change_sql(pg):
    """Join immutable writes to exact item receipts before selecting a bounded log page."""
    p, each, array = ("%s", "jsonb_each", "jsonb_array_elements") if pg else ("?", "json_each", "json_each")
    table, key = ("{tbl}", "key") if pg else ("docs", "name")
    return f"""WITH documents AS (SELECT {key} AS name, value FROM {table}
        WHERE {key} IN ({p},{p},{p},{p}) OR starts_with({key},{p})),
      props AS (SELECT i.value AS r FROM documents,
        LATERAL {each}(COALESCE(value -> 'days', '{{}}')) d,
        LATERAL {each}(COALESCE(d.value -> 'items', '{{}}')) i),
      decisions AS (SELECT d.value AS r FROM documents,
        LATERAL {each}(COALESCE(value -> 'decisions', '{{}}')) d),
      outcomes AS (SELECT o.key AS id, o.value AS r FROM documents,
        LATERAL {each}(COALESCE(value -> 'items', '{{}}')) o),
      claims AS (SELECT g.value AS r FROM documents,
        LATERAL {each}(COALESCE(value -> 'groups', '{{}}')) g WHERE g.value ->> 'decision_id' IS NOT NULL),
      candidates AS (
        SELECT w.value ->> 'item_id' AS id, w.value -> 'payload' AS payload, w.value ->> 'kind' AS kind,
          d.r ->> 'id' AS approval_id, d.r ->> 'by' AS approver, d.r ->> 'at' AS approved_at,
          CASE WHEN d.r ->> 'source' = 'wasted_spend' THEN 'Wasted spend' ELSE 'Inbox' END AS source,
          NULL AS saved_status, NULL AS saved_at, NULL AS saved_result, NULL AS saved_cause, 1 AS priority
        FROM decisions d, LATERAL {array}(COALESCE(d.r -> 'writes', '[]')) w
        WHERE d.r ->> 'decision' = 'approved' AND COALESCE(d.r ->> 'source','') <> 'app'
        UNION ALL
        SELECT w.value ->> 'item_id', w.value -> 'payload', w.value ->> 'kind',
          c.r ->> 'decision_id', c.r ->> 'decided_by', c.r ->> 'decided_at', 'Wasted spend',
          c.r -> 'outcomes' -> (w.value ->> 'item_id') ->> 'status',
          c.r -> 'outcomes' -> (w.value ->> 'item_id') ->> 'at',
          c.r -> 'outcomes' -> (w.value ->> 'item_id') -> 'result',
          c.r -> 'outcomes' -> (w.value ->> 'item_id') ->> 'cause', 2
        FROM claims c, LATERAL {array}(COALESCE(c.r -> 'writes', '[]')) w
        UNION ALL
        SELECT r ->> 'id', COALESCE(r -> 'sent_payload', r -> 'payload'), r ->> 'kind',
          r ->> 'decision_id', r ->> 'decided_by', r ->> 'decided_at', 'Inbox',
          r ->> 'status', r ->> 'outcome_at', r -> 'result', r ->> 'cause', 3 FROM props
        WHERE r ->> 'status' IN ('sent','refused','approved','unknown') AND COALESCE(r ->> 'kind','') <> 'app'
        UNION ALL
        SELECT value ->> 'id', value -> 'sent_payload', value ->> 'kind', value ->> 'schedule_id',
          value ->> 'approved_by', value ->> 'approved_at', 'Schedule', value ->> 'status',
          COALESCE(value ->> 'outcome_at', value ->> 'claimed_at'), value -> 'result', value ->> 'cause', 0
        FROM documents WHERE value ->> 'kind' = 'scheduled_change'),
      ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY priority) AS position FROM candidates),
      joined AS (SELECT w.*, pr.r AS proposal, o.r AS outcome,
          COALESCE(o.r ->> 'status', pr.r ->> 'status', w.saved_status, c.r -> 'outcomes' -> w.id ->> 'status', 'unknown') AS receipt_status,
          COALESCE(o.r -> 'result', pr.r -> 'result', w.saved_result, c.r -> 'outcomes' -> w.id -> 'result') AS receipt,
          COALESCE(o.r ->> 'at', pr.r ->> 'outcome_at', w.saved_at, c.r -> 'outcomes' -> w.id ->> 'at', w.approved_at) AS occurred_at,
          COALESCE(o.r ->> 'cause', pr.r ->> 'cause', w.saved_cause, c.r -> 'outcomes' -> w.id ->> 'cause') AS cause
        FROM ranked w LEFT JOIN props pr ON (pr.r ->> 'id') = w.id
          AND ((pr.r ->> 'decision_id') = w.approval_id OR w.approval_id IS NULL)
        LEFT JOIN outcomes o ON o.id = w.id AND (o.r ->> 'decision_id') = w.approval_id
        LEFT JOIN claims c ON (c.r ->> 'decision_id') = w.approval_id
        WHERE w.position = 1 AND w.id IS NOT NULL),
      log AS (SELECT *, CASE WHEN (payload ->> 'undo_of') IS NOT NULL OR (proposal ->> 'undo_of') IS NOT NULL
          THEN 'Undo' ELSE source END AS change_source,
          payload ->> 'connection_id' AS connection_id, payload ->> 'profile_id' AS profile_id,
          payload ->> 'ad_type' AS ad_type, payload ->> 'campaign_id' AS campaign_id FROM joined)
      """


def _page_size(limit, cursor):
    try:
        size, offset = min(200, int(limit)), int(cursor or 0)
    except (TypeError, ValueError):
        raise ValueError("Use a whole page size and cursor.") from None
    if size < 1 or offset < 0:
        raise ValueError("Use a positive page size and a valid cursor.")
    return size, offset


def _change_values(payload):
    operation = payload.get("operation")
    field = {"set_bid": "bid", "set_daily_budget": "daily_budget", "pause_ads": "state", "enable_ads": "state",
             "add_negative_keyword": "keyword_text"}.get(operation)
    old = payload.get("previous_" + field) if field else None
    if operation == "set_daily_budget" and old is None:
        old = payload.get("previous_budget")
    return old, payload.get(field) if field else None


def change_log(tenant_key, *, st=None, cursor=None, limit=50, source=None, connection_id=None,
               profile_id=None, ad_type=None, campaign_id=None):
    """Read every recorded change and uncertain claim without inventing a send or account binding."""
    st = _schedule_store(tenant_key, st)
    size, offset = _page_size(limit, cursor)
    if source and source not in ("Inbox", "Undo", "Schedule", "Wasted spend"):
        raise ValueError("Choose a change source.")
    scope = dict(connection_id=connection_id, profile_id=profile_id, ad_type=ad_type, campaign_id=campaign_id)
    if any(scope.values()):
        _schedule_binding(scope)
    with _screen_store(tenant_key, st, (KEY_DAYS, KEY_DECISIONS, KEY_OUTCOMES, "amazon_operator_wasted"),
                       namespaces=(KEY_SCHEDULE_RUNS,)) as (execute, pg, _names):
        p, sql, args, tests = "%s" if pg else "?", _change_sql(pg), [], []
        for field, value in (("change_source", source), *scope.items()):
            if value:
                tests.append(f"{field} = {p}")
                args.append(value)
        where = " WHERE " + " AND ".join(tests) if tests else ""
        total = execute(sql + "SELECT COUNT(*) FROM log" + where, args).fetchone()[0]
        rows = execute(sql + "SELECT id, payload, kind, approval_id, approver, approved_at, change_source, "
                       "receipt_status, receipt, occurred_at, cause, proposal ->> 'campaign' FROM log" + where
                       + f" ORDER BY occurred_at DESC NULLS LAST, id LIMIT {p} OFFSET {p}", [*args, size, offset]).fetchall()
    def parsed(value):
        return value if isinstance(value, dict) else json.loads(value) if value else None
    items = []
    for identity, raw, kind, approval_id, who, approved_at, label, status, receipt, at, cause, campaign in rows:
        payload = parsed(raw) or {}
        old, new = _change_values(payload)
        if status == "sent" and parsed(receipt) is None:
            status, cause = "unknown", "The send receipt was not recorded."
        if status == "approved":
            status, cause = "unknown", "Approval is recorded. The send outcome is not confirmed."
        items.append({"id": identity, "kind": kind, "operation": payload.get("operation"), "old_value": old,
                      "new_value": new, "source": label, "evidence_table": payload.get("source"),
                      "approver": who, "approved_at": approved_at, "approval_id": approval_id, "at": at,
                      "status": status, "cause": cause, "currency": payload.get("currency"),
                      "campaign": campaign or payload.get("campaign_id"), "undo_of": payload.get("undo_of"),
                      "sku": payload.get("sku"), "asin": payload.get("asin"),
                      **{f: payload.get(f) for f in scope},
                      "binding_recorded": all(payload.get(f) for f in ("connection_id", "profile_id")),
                      **{key: value for key, value in _proposal_values({"payload": payload}).items()
                         if key in ("value_change", "value_unit", "values_reason")}})
    return {"items": items, "total": total, "cursor": str(offset + size) if offset + size < total else None, "limit": size}


def pacing_campaigns(tenant_key, *, st=None, cursor=None, limit=50):
    """Page every campaign's exact account and currency scope across the saved campaign history."""
    st, (size, offset) = _schedule_store(tenant_key, st), _page_size(limit, cursor)
    parts = []
    with _reader(tenant_key, st) as cur:
        if cur is None:
            return {"items": [], "cursor": None, "total": 0, "state": "unavailable"}
        for kind in AD_TYPES:
            table = _ads_table(kind, "campaigns")
            cols = _columns(cur, table)
            if {"campaign_id", "profile_id", "_connection_id"} <= cols:
                parts.append(f"SELECT '{kind}' AS ad_type, {_text(cols, '_connection_id')} AS connection_id, "
                             f"{_text(cols, 'profile_id')} AS profile_id, {_text(cols, 'campaign_id')} AS campaign_id, "
                             f"{_text(cols, 'campaign_name')} AS campaign, {_text(cols, 'currency')} AS currency FROM {table}")
        if not parts:
            return {"items": [], "cursor": None, "total": 0, "state": "unavailable"}
        sql = "WITH campaigns AS (" + " UNION ALL ".join(parts) + "), scopes AS (SELECT ad_type, connection_id, profile_id, " \
              "campaign_id, MAX(campaign) AS campaign, currency FROM campaigns WHERE connection_id IS NOT NULL AND " \
              "connection_id <> '' AND profile_id IS NOT NULL AND profile_id <> '' GROUP BY ALL) "
        total = cur.execute(sql + "SELECT COUNT(*) FROM scopes").fetchone()[0]
        rows = cur.execute(sql + "SELECT * FROM scopes ORDER BY ad_type, connection_id, profile_id, campaign_id, currency "
                           "LIMIT ? OFFSET ?", [size, offset]).fetchall()
    keys = ("ad_type", "connection_id", "profile_id", "campaign_id", "campaign", "currency")
    return {"items": [dict(zip(keys, row)) for row in rows], "total": total, "state": "ready",
            "cursor": str(offset + size) if offset + size < total else None, "limit": size}


def _pacing_metadata(cur, binding, currency):
    from zoneinfo import ZoneInfo
    identities = set()
    for table in (_ads_table(binding["ad_type"], "campaigns"), "amzn_ads_sp_hourly"):
        cols = _columns(cur, table)
        if {"_connection_id", "profile_id", "timezone"} <= cols:
            rows = cur.execute(f"SELECT DISTINCT timezone FROM {table} WHERE CAST(_connection_id AS VARCHAR) = ? "
                               "AND CAST(profile_id AS VARCHAR) = ? LIMIT 2",
                               [binding["connection_id"], binding["profile_id"]]).fetchall()
            identities.update(str(row[0]) for row in rows if row[0])
    if len(identities) != 1 or not currency:
        raise ValueError("The Ads profile timezone or currency is unavailable or ambiguous.")
    timezone = identities.pop()
    ZoneInfo(timezone)
    return timezone


def pacing_months(tenant_key, record, *, st=None, cursor=None, limit=12, now=None):
    """Page observed months plus the profile's current local month."""
    from zoneinfo import ZoneInfo
    binding = _schedule_binding(record)
    st, (size, offset) = _schedule_store(tenant_key, st), _page_size(limit, cursor)
    where, args = _schedule_scope(binding)
    with _reader(tenant_key, st) as cur:
        if cur is None:
            raise ValueError("The tenant Ads mirror is unavailable.")
        timezone = _pacing_metadata(cur, binding, record.get("currency"))
        current = (now or _now()).astimezone(ZoneInfo(timezone)).strftime("%Y-%m")
        table = _ads_table(binding["ad_type"], "campaigns")
        sql = f"WITH months AS (SELECT DISTINCT left({_DATE},7) AS month FROM {table} WHERE {where} UNION SELECT ?) "
        rows = cur.execute(sql + "SELECT month FROM months WHERE month IS NOT NULL ORDER BY month DESC LIMIT ? OFFSET ?",
                           [*args, current, size + 1, offset]).fetchall()
    return {"items": [r[0] for r in rows[:size]], "current_month": current, "timezone": timezone,
            "cursor": str(offset + size) if len(rows) > size else None, "limit": size}


def budget_pacing(tenant_key, record, month=None, *, st=None, now=None):
    """Compare dated daily budgets and spend without carrying current settings into historical gaps."""
    from zoneinfo import ZoneInfo
    binding = _schedule_binding(record)
    st, currency = _schedule_store(tenant_key, st), str(record.get("currency") or "")
    where, args = _schedule_scope(binding)
    with _reader(tenant_key, st) as cur:
        if cur is None:
            raise ValueError("The tenant Ads mirror is unavailable.")
        timezone = _pacing_metadata(cur, binding, currency)
        month = month or (now or _now()).astimezone(ZoneInfo(timezone)).strftime("%Y-%m")
        try:
            first = dt.date.fromisoformat(month + "-01")
            after = (first.replace(day=28) + dt.timedelta(days=4)).replace(day=1)
        except (TypeError, ValueError, OverflowError):
            raise ValueError("Choose a month in YYYY-MM format.") from None
        table = _ads_table(binding["ad_type"], "campaigns")
        cols = _columns(cur, table)
        if not {"currency", "date", "cost", "campaign_budget_amount"} <= cols:
            raise ValueError("Daily campaign budget and spend history is unavailable.")
        metric = 'TRY_CAST(cost AS DOUBLE)'
        budget = 'TRY_CAST(campaign_budget_amount AS DOUBLE)'
        daily = cur.execute(f"SELECT {_DATE}, COUNT(*), COUNT({metric}), COUNT(DISTINCT {budget}), "
                            f"MIN({budget}), SUM({metric}), COUNT({budget}), "
                            f"COUNT(*) FILTER (WHERE NOT isfinite({metric})), "
                            f"COUNT(*) FILTER (WHERE NOT isfinite({budget})) "
                            f"FROM {table} WHERE {where} AND currency = ? AND {_DATE} >= ? AND {_DATE} < ? "
                            "GROUP BY 1 ORDER BY 1", [*args, currency, first.isoformat(), after.isoformat()]).fetchall()
    by_day = {row[0]: row for row in daily}
    days = []
    for offset in range((after - first).days):
        day = (first + dt.timedelta(days=offset)).isoformat()
        row = by_day.get(day)
        spend = row[5] if row and row[1] == row[2] and not row[7] else None
        amount = row[4] if row and row[1] == row[6] and row[3] == 1 and not row[8] else None
        days.append({"date": day, "budget": amount, "spend": spend})
    total = round(sum(row["spend"] for row in days if row["spend"] is not None), 2) if any(row["spend"] is not None for row in days) else None
    budgets = [row["budget"] for row in days]
    report = {**binding, "currency": currency, "timezone": timezone, "month": month,
              "start": first.isoformat(), "end": (after - dt.timedelta(days=1)).isoformat(),
              "source_table": table, "days": days, "recorded_spend": total,
              "monthly_spend": total if all(row["spend"] is not None for row in days) else None,
              "monthly_budget": round(sum(budgets), 2) if all(value is not None for value in budgets) else None,
              "spend_days": sum(row["spend"] is not None for row in days),
              "budget_days": sum(value is not None for value in budgets)}
    report["validation"] = validate_pacing(tenant_key, record, report, st=st)
    return report


def validate_pacing(tenant_key, record, report, *, st=None):
    """Reconcile the displayed month and daily figures with a separate exact-scope campaign report aggregate."""
    binding = _schedule_binding(record)
    where, args = _schedule_scope(binding)
    try:
        first = dt.date.fromisoformat(report["month"] + "-01")
        after = (first.replace(day=28) + dt.timedelta(days=4)).replace(day=1)
        currency = record["currency"]
        with _reader(tenant_key, _schedule_store(tenant_key, st)) as cur:
            table = _ads_table(binding["ad_type"], "campaigns")
            count, valid, cost = cur.execute(f"SELECT COUNT(*), COUNT(TRY_CAST(cost AS DOUBLE)), SUM(TRY_CAST(cost AS DOUBLE)) "
                f"FROM {table} WHERE {where} AND currency = ? AND {_DATE} >= ? AND {_DATE} < ?",
                [*args, currency, first.isoformat(), after.isoformat()]).fetchone()
        expected = round(cost, 2) if count and count == valid and _num(cost) is not None else None
        values = [row["spend"] for row in report["days"] if row["spend"] is not None]
        observed = round(sum(values), 2) if values else None
        ok = (expected is not None and observed == expected == report["recorded_spend"]
              and all(report.get(f) == value for f, value in binding.items()) and report["currency"] == currency
              and report["start"] == first.isoformat() and report["end"] == (after - dt.timedelta(days=1)).isoformat()
              and [row["date"] for row in report["days"]] == [(first + dt.timedelta(days=n)).isoformat() for n in range((after-first).days)]
              and report["monthly_spend"] == (observed if len(values) == (after-first).days else None))
        return {"ok": ok, "source_total": expected, "source_table": table,
                "reason": None if ok else "Monthly pacing does not tie to the selected Ads spend report."}
    except (KeyError, TypeError, ValueError):
        return {"ok": False, "source_total": None, "reason": "Monthly pacing could not be validated."}


def _remove_schedule_rows(tenant_key, st):
    for namespace in ROW_NAMESPACES:
        while True:
            page = _row_page(tenant_key, st, namespace, limit=200)
            if not page["items"]:
                break
            for row in page["items"]:
                st.delete_document(_row_key(namespace, row["id"]))


def remove(tenant_key, *, st=None):
    """Delete App documents and schedule rows while retaining connector observations (rule 13)."""
    st = _rt(tenant_key, st)
    _remove_schedule_rows(tenant_key, st)
    for key in KEYS:
        deleter = getattr(st, "delete_document", None)
        if callable(deleter):
            deleter(key)
        else:
            st.update(key, lambda _doc: {})
    return [*KEYS, *ROW_NAMESPACES]