Spaces:
Paused

File size: 132,411 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
data_analysis.py β€” smolagents manager + `data_worker` sub-agent for the
Data Analysis tab (the same orchestration shape as rag_agent.py and
deep_research_agent.py).

NOTE β€” matplotlib backend safety: the `data_worker` sandbox may execute
raw model-written matplotlib code (the curated `save_chart` tool forces
Agg itself, but the model can bypass it with hand-written plt.savefig).
The app's splash screen owns a tkinter Tk root on the MAIN thread; if
pyplot auto-selected TkAgg in the worker thread, the Tk objects created
and garbage-collected there would abort the whole process with
`Tcl_AsyncDelete: async handler deleted by the wrong thread` (exit
0x80000003). The MPLBACKEND env var forces the non-GUI Agg backend
process-wide β€” set it here too so the guard holds even when the app is
entered through a path that skips run_webview.py / app.py.

Architecture (manager / sub-agent):    * MANAGER (`data_worker` is the ONLY thing it can call) β€” a CodeAgent
    that ANALYZES the user's data question (totals, breakdowns, charts,
    payroll, cleaning…), decomposes it into focused sub-tasks and
    delegates each one to the `data_worker` sub-agent via plain Python
    expressions (`data_worker(task='...')`, which the executor resolves
    to the managed agent), then SYNTHESIZES the full Markdown report from
    the worker's findings. It never touches the data itself. It is a
    CodeAgent rather than a ToolCallingAgent because this tab's verified
    models (small GGUFs) are reliable on the app's forgiving code grammar
    β€” see _build_manager_agent's docstring for the end-to-end evidence.
  * SUB-AGENT (`data_worker`) β€” a plain CodeAgent (Python execution is its
    whole point β€” ToolCallingAgent has no Python executor) holding
    ONLY the curated data tools (`list_columns`, `aggregate`,
    `summarize_numeric`, `save_chart`, `complete_missing_data`,
    `install_package`). Given ONE
    focused sub-task per call (it has no memory of other calls), it loads
    the data file, runs the tools / pandas / matplotlib, and returns its
    findings (the tool outputs transcribed VERBATIM β€” a transcription
    validator enforces this) for the manager to write the final report
    from.

This replaces the older single-agent design (one CodeAgent holding every
tool and doing the whole EDA itself). Splitting the work mirrors the
proven RAG / Deep Research pattern: each worker call has a FOCUSED task
with far less context than the whole EDA instruction block, and the
manager's context accumulates the workers' findings instead of one huge
monolithic run. The curated tools' file-path contract and the exact-
column-name rule are unchanged β€” they live on the worker, which is the
only agent that touches the data.

The full Markdown report is returned as the manager's final answer (never
auto-saved to disk β€” the user exports it to Word on demand via the
πŸ’Ύ Save Report button). The worker can install any missing Python packages
itself via the `install_package` tool, and can COMPLETE blank (empty)
columns (e.g. αž€αžΆαžαŸ‹αž–αž“αŸ’αž’ / tax or αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD) / net salary) when
their values are derivable from the other columns viathe `complete_missing_data` tool.
"""

import os

# Matplotlib backend safety β€” see the module docstring: the worker sandbox
# may run raw model-written pyplot code, and the tkinter splash must never
# make matplotlib auto-select TkAgg in the worker thread (Tcl_AsyncDelete
# would abort the process). Force the non-GUI Agg backend app-wide.
os.environ.setdefault("MPLBACKEND", "Agg")

import datetime
import html
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import types
from pathlib import Path
from typing import Optional

from smolagents import tool

from agents.agent_factory import build_smol_agent
from agents import agent_memory
from agents import agent_streaming
from backend import model_registry as mr
from backend import models
from backend.hardware import DEVICE
from backend.knowledge_base import get_file_path
from ui import i18n

_data_agent          = None
_data_worker         = None
_data_agent_model_id = None
_data_agent_max_steps = None
_data_agent_worker_max_steps = None
_data_agent_execution_timeout = None
_data_agent_n_ctx    = None
_data_agent_files    = ()
_data_agent_lock      = threading.Lock()

# How many conversation turns the Data Analysis MANAGER is allowed to
# remember (see agent_memory.cap_agent_memory()). Kept smaller than the
# other tabs' default of 6 because each turn's task prompt here is already
# long (the full analysis instructions in build_data_task() below), so
# memory grows the prompt much faster per turn than a one-line chat
# question would.
DATA_AGENT_MEMORY_TURNS = 3

# Tracks which uploaded file paths the manager's current memory "belongs
# to". A new/changed set of files means a different dataset, so old
# memory (which may reference the previous file's columns/stats) needs to
# be dropped even though the model itself hasn't changed β€” see
# agent_memory.reset_if_context_changed().
_last_data_context = {"key": None}


_SAFE_PACKAGE_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]+(==[0-9.]+[a-zA-Z0-9]*)?$")


@tool
def install_package(package_name: str) -> str:
    """
    Install a Python package into the current environment using pip.
    Use this whenever a data-analysis step needs a library that is not
    yet installed (e.g. "openpyxl" for reading .xlsx files, "seaborn",
    "scikit-learn", "statsmodels", "plotly", "xlsxwriter").

    Args:
        package_name: The pip package name to install, e.g. "seaborn" or
            "scikit-learn==1.4.0". Pass a single package per call.
    """
    pkg = str(package_name or "").strip()
    if not pkg or not _SAFE_PACKAGE_NAME_RE.match(pkg) or pkg.startswith("-") or "/" in pkg or "\\" in pkg:
        return (
            f"❌ Rejected package name '{package_name}': invalid format. "
            "Only standard PyPI package names (e.g. 'openpyxl', 'seaborn==0.13.0') are allowed."
        )

    try:
        from backend.hardware import _pip_base_args
        flags = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
        cmd = _pip_base_args() + ["--quiet", "--disable-pip-version-check", pkg]
        result = subprocess.run(
            cmd,
            capture_output=True, text=True, timeout=1200,
            creationflags=flags,
        )
        if result.returncode == 0:
            return f"βœ… Installed '{pkg}' successfully."
        return f"❌ Failed to install '{pkg}':\n{result.stderr[-2000:]}"
    except subprocess.TimeoutExpired:
        return f"❌ Installing '{pkg}' timed out after 1200s."
    except Exception as e:
        return f"❌ Error installing '{pkg}': {e}"


install_package.input_aliases = {
    "package_name": ("package", "name", "pkg", "lib"),
}


def _normalize_tool_path(file_path: str) -> str:
    """Normalize a model-transcribed file path back to the real Windows path.
    Small models (E2B observed end-to-end) sometimes rewrite the uploaded
    file's `G:\\user_data\\...` path as a POSIX-style `/G/localailab_svelet/...`
    or `/G:/user_data/...` (leading slash + drive letter + forward slashes) β€”
    which Path.is_file() then rejects with 'file not found' and the worker
    burns its step budget retrying the same broken path. Convert a
    `/X:/...` or `/X/...` drive-letter prefix back to `X:\\...`. Returns the
    original when there is nothing to normalize."""
    raw = (file_path or "").strip()
    m = re.match(r"^/([A-Za-z]):?/(.*)$", raw, re.DOTALL)
    if m:
        cand = f"{m.group(1)}:\\{m.group(2)}".replace("/", "\\")
        return cand
    return raw


def _load_dataframe(file_path: str):
    """Read a CSV or Excel file into a pandas DataFrame (lazy imports so a
    failed load degrades to an informative tool message, never a crash).

    CSVs are read with DELIMITER SNIFFING (sep=None, python engine) so
    comma-, tab- and semicolon-separated uploads all work out of the box
    (Excel "CSV" exports are frequently tab- or semicolon-delimited, and
    real payroll sheets like the user's sample paste are tab-separated),
    and the UTF-8 BOM is auto-stripped (Excel-saved CSVs carry it, which
    would otherwise corrupt the first column name into '\ufeffEmployee ID')."""
    import pandas as pd

    p = Path(_normalize_tool_path(file_path))
    if not p.is_file():
        raise FileNotFoundError(f"file not found: {file_path}")
    if p.suffix.lower() in (".xlsx", ".xls"):
        try:
            return pd.read_excel(p)
        except Exception as e:
            raise RuntimeError(
                f"could not read '{p.name}' (Excel). If 'openpyxl' is missing, call "
                f"install_package('openpyxl') first, then retry. Original error: {e}"
            )
    return pd.read_csv(p, sep=None, engine="python", encoding="utf-8-sig")


def _missing_columns(df, wanted) -> str:
    """Return the exact available column list when any `wanted` column is
    absent β€” the mechanical version of the task prompt's KeyError-recovery
    rule (never guess/translate a column name). Empty string = all present."""
    cols = list(df.columns)
    missing = [c for c in wanted if c not in cols]
    if not missing:
        return ""
    return f"column(s) not found: {missing}. Available columns: {cols}"


def _run_with_timeout(fn, args=(), kwargs=None, timeout_seconds: float = 60.0):
    """Execute a function in a thread with a hard timeout to prevent slow file IO
    or complex dataframe operations from hanging indefinitely."""
    if kwargs is None:
        kwargs = {}
    res = [None]
    err = [None]

    def _worker():
        try:
            res[0] = fn(*args, **kwargs)
        except Exception as e:
            err[0] = e

    t = threading.Thread(target=_worker, daemon=True)
    t.start()
    t.join(timeout_seconds)
    if t.is_alive():
        return f"❌ Operation timed out after {int(timeout_seconds)}s."
    if err[0] is not None:
        raise err[0]
    return res[0]


@tool
def list_columns(file_path: str) -> str:
    """Get the EXACT column names, data types and a sample of the uploaded
    data file.

    ALWAYS call this first after loading your data, and copy the column
    names it returns VERBATIM into your code β€” they may be in Khmer or any
    language and are never translated, renamed or guessed.

    Args:
        file_path: Absolute path to the uploaded data file (.csv or .xlsx).
    """
    def _impl():
        df = _load_dataframe(file_path)
        lines = ["Columns (exact names, use verbatim):"]
        for c in df.columns:
            lines.append(f"  - {c}  ({df[c].dtype})")
        lines.append("\nFirst 3 rows:\n" + df.head(3).to_string())
        return "\n".join(lines)

    try:
        return _run_with_timeout(_impl, timeout_seconds=60.0)
    except Exception as e:
        return f"❌ list_columns failed: {e}"


list_columns.input_aliases = {
    "file_path": ("filepath", "file", "path", "filename", "data_path", "source"),
}


@tool
def aggregate(file_path: str, group_col: str, value_col: str, agg: str = "sum") -> str:
    """Aggregate a numeric column grouped by a categorical column and return a
    Markdown table with the computed values.

    Prefer this over writing groupby code yourself β€” it verifies that BOTH
    column names exist exactly as you passed them, so a wrong (translated or
    guessed) name returns the real column list instead of a KeyError.

    Args:
        file_path: Absolute path to the loaded data file (.csv or .xlsx).
        group_col: The EXACT name of the grouping column (e.g. 'αž•αž›αž·αžαž•αž›'),
            or '' / empty to get the OVERALL aggregate with no grouping.
        value_col: The EXACT name of the numeric column to aggregate
            (e.g. 'αžŸαžšαž»αž” (USD)').
        agg: Aggregation function β€” 'sum', 'mean', 'count', 'min' or 'max'.
    """
    def _impl():
        df = _load_dataframe(file_path)
        if agg not in ("sum", "mean", "count", "min", "max"):
            return f"❌ Unsupported agg '{agg}'. Use one of: sum, mean, count, min, max."
        missing = _missing_columns(df, [value_col] + ([group_col] if group_col.strip() else []))
        if missing:
            return f"❌ aggregate failed: {missing}"
        if agg != "count":
            df = df.copy()
            df[value_col] = df[value_col].map(_to_number)
        if not group_col.strip():
            value = float(df[value_col].agg(agg))
            return (
                f"| {value_col} ({agg}) |\n|---|\n| {value:.4g} |\n\n"
                f"**{agg.title()} {value_col} = {value:.4g}**"
            )
        grouped = df.groupby(group_col)[value_col].agg(agg).reset_index()
        rows = "\n".join(
            f"| {row[group_col]} | {row[value_col]:.4g} |"
            for _, row in grouped.iterrows()
        )
        total = f"**{agg.title()} {value_col} = {grouped[value_col].sum():.4g}**"
        return f"| {group_col} | {value_col} ({agg}) |\n|---|---|\n{rows}\n\n{total}"

    try:
        return _run_with_timeout(_impl, timeout_seconds=60.0)
    except Exception as e:
        return f"❌ aggregate failed: {e}"


aggregate.input_aliases = {
    "file_path": ("filepath", "file", "path", "filename", "data_path", "source"),
    "group_col": ("group_by", "groupby", "by", "category", "category_col", "column"),
    "value_col": ("target_col", "metric_col", "num_col", "val_col", "value", "column_name"),
    "agg": ("aggregation", "agg_func", "function", "method", "op"),
}


@tool
def summarize_numeric(file_path: str, value_col: str) -> str:
    """Summary statistics for one numeric column: count, mean, std, min,
    quartiles and max.

    Prefer this over writing describe code yourself β€” the column name is
    verified exactly as you pass it.

    Args:
        file_path: Absolute path to the loaded data file (.csv or .xlsx).
        value_col: The EXACT name of the numeric column to summarise
            (e.g. 'αž”αžšαž·αž˜αžΆαžŽ').
    """
    def _impl():
        import numpy as np
        import pandas as pd

        df = _load_dataframe(file_path)
        missing = _missing_columns(df, [value_col])
        if missing:
            return f"❌ summarize_numeric failed: {missing}"
        s = df[value_col]
        if not pd.api.types.is_numeric_dtype(s):
            coerced = s.map(_to_number)
            if coerced.notna().any() and coerced.notna().all():
                s = coerced
            else:
                return f"❌ Column '{value_col}' is not numeric (dtype {s.dtype})."
        clean = s.dropna()
        q1, q2, q3 = clean.quantile([0.25, 0.5, 0.75])
        out = {
            "count": int(clean.count()),
            "mean": round(float(clean.mean()), 4),
            "std": round(float(clean.std()), 4),
            "min": round(float(clean.min()), 4),
            "25%": round(float(q1), 4),
            "50% (median)": round(float(q2), 4),
            "75%": round(float(q3), 4),
            "max": round(float(clean.max()), 4),
            "sum": round(float(clean.sum()), 4),
        }
        return "\n".join(f"  - {k}: {v}" for k, v in out.items())

    try:
        return _run_with_timeout(_impl, timeout_seconds=60.0)
    except Exception as e:
        return f"❌ summarize_numeric failed: {e}"


summarize_numeric.input_aliases = {
    "file_path": ("filepath", "file", "path", "filename", "data_path", "source"),
    "value_col": ("target_col", "metric_col", "num_col", "val_col", "value", "column", "column_name"),
}


# ── Professional chart rendering ────────────────────────────────────────
# save_chart applies a clean, consistent look instead of matplotlib's bare
# defaults (no grid, default colors, 100 DPI): white canvas, light dashed
# grid, clean spines, a coherent palette, compact tick formatting, bar value
# labels and a high 150 DPI so charts stay crisp on HiDPI screens. It also
# registers a Khmer-capable font β€” DejaVu Sans has NO Khmer glyphs, so Khmer
# column names / titles used to render as empty boxes (the "Glyph ... missing
# from font(s) DejaVu Sans" warnings). The font probe is cached: the
# font-manager scan is once per process, and machines without any Khmer font
# degrade to DejaVu's boxed behaviour β€” never a crash.

_KHMER_FONT_CACHE = None  # None = not probed yet; then a family name or None

_KHMER_FONT_FAMILIES = (
    "Noto Sans Khmer", "Khmer OS", "Leelawadee UI",
    "DaunPenh", "MoolBoran", "Khmer UI",
)


def _khmer_font_family():
    """Find a Khmer-capable font family for matplotlib so Khmer axis labels /
    titles render instead of missing-glyph boxes. Returns the family name to
    put FIRST in font.family, or None when no Khmer font exists on this
    machine (charts then degrade to DejaVu's boxed behaviour). Never raises.
    Cached after the first probe."""
    global _KHMER_FONT_CACHE
    if _KHMER_FONT_CACHE is not None:
        return _KHMER_FONT_CACHE
    family = None
    try:
        from matplotlib import font_manager

        # Already registered (matplotlib found a system/user Khmer font itself).
        known = {f.name for f in font_manager.fontManager.ttflist}
        for fam in _KHMER_FONT_FAMILIES:
            if fam in known:
                family = fam
                break
        if family is None:
            # Register a font file from the well-known Windows locations.
            local = os.environ.get("LOCALAPPDATA", "")
            windir = os.environ.get("WINDIR", r"C:\Windows")
            candidates = [
                os.path.join(local, "Microsoft", "Windows", "Fonts", "NotoSansKhmer-Regular.ttf"),
                os.path.join(local, "Microsoft", "Windows", "Fonts", "NotoSansKhmerUI-Regular.ttf"),
                os.path.join(windir, "Fonts", "LeelawadeeUI.ttf"),
                os.path.join(windir, "Fonts", "khmerui.ttf"),
                os.path.join(windir, "Fonts", "daunpenh.ttf"),
                os.path.join(windir, "Fonts", "moolbor.ttf"),
                os.path.join(windir, "Fonts", "KhmerOS.ttf"),
            ]
            for p in candidates:
                if not (p and os.path.isfile(p)):
                    continue
                try:
                    font_manager.fontManager.addfont(p)
                    family = font_manager.FontProperties(fname=p).get_name()
                    break
                except Exception:
                    continue
    except Exception:
        family = None
    _KHMER_FONT_CACHE = family
    return family


# A professional categorical palette (terracotta accent first, then a muted
# blue/gold/violet set) β€” charts read like the app, not like a default
# matplotlib rainbow.
_CHART_PALETTE = ("#d97757", "#4e79a7", "#59a14f", "#edc948", "#b07aa1", "#f28e2b")


def _apply_chart_style(khmer_family):
    """The shared professional look every save_chart plot gets: white canvas,
    light dashed grid, clean spines, muted axis text, the coherent palette.
    `khmer_family` (or None) goes first in font.family so Khmer renders; the
    font list keeps DejaVu Sans as the always-present fallback."""
    import matplotlib as mpl

    families = [khmer_family] if khmer_family else []
    families.append("DejaVu Sans")
    mpl.rcParams.update({
        "font.family": families,
        "font.size": 11,
        "figure.facecolor": "white",
        "axes.facecolor": "white",
        "axes.edgecolor": "#d8d2c6",
        "axes.grid": True,
        "grid.color": "#e9e3d8",
        "grid.linewidth": 0.8,
        "grid.linestyle": "--",
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.spines.left": True,
        "axes.spines.bottom": True,
        "axes.titleweight": "bold",
        "axes.titlesize": 14,
        "axes.titlecolor": "#333333",
        "axes.labelcolor": "#4a4a4a",
        "axes.labelsize": 11.5,
        "xtick.color": "#666666",
        "ytick.color": "#666666",
        "xtick.labelsize": 10.5,
        "ytick.labelsize": 10.5,
        "legend.frameon": False,
        "legend.fontsize": 10.5,
    })


def _fmt_num(v):
    """Compact professional number formatting for chart ticks/labels: comma
    thousands (1,250,000), 1.2M for millions, whole numbers without a
    trailing .0. Never raises on non-numeric input."""
    try:
        v = float(v)
    except (TypeError, ValueError):
        return str(v)
    if abs(v) >= 1_000_000:
        return (f"{v / 1_000_000:.1f}M").replace(".0M", "M")
    if abs(v) >= 1_000:
        return f"{v:,.0f}"
    if v == int(v):
        return str(int(v))
    return f"{v:,.2f}".rstrip("0").rstrip(".")


_active_data_report_dir: Optional[Path] = None


def get_active_report_dir() -> Optional[Path]:
    """Return the active timestamped report folder for the current Data Analysis run,
    or None if no run has set one."""
    global _active_data_report_dir
    return _active_data_report_dir


def set_active_report_dir(p: Optional[Path]) -> None:
    """Set or clear the active timestamped report folder."""
    global _active_data_report_dir
    _active_data_report_dir = Path(p) if p else None


def _maybe_rotate_xticks(ax, series, max_ticks=8):
    """Rotate crowded category labels (many x values) so they don't overlap."""
    if len(series) > max_ticks:
        ax.tick_params(axis="x", rotation=45)


@tool
def save_chart(file_path: str, chart_type: str, x_col: str, y_col: str = "", title: str = "") -> str:
    """Create a chart from the data, save it as a PNG and return its filename.

    Use this for ALL charts β€” it produces a deterministic, valid image every
    time, so you never need to write matplotlib code yourself. The filename it
    returns is what you reference in your report.

    Args:
        file_path: Absolute path to the loaded data file (.csv or .xlsx).
        chart_type: 'line', 'bar', 'pie', 'hist' or 'scatter'.
        x_col: For line/bar β€” the EXACT X axis column (e.g. 'αž€αžΆαž›αž”αžšαž·αž…αŸ’αž†αŸαž‘');
            for pie β€” the EXACT category column to group by; for hist β€” the
            EXACT numeric column to plot; for scatter β€” the EXACT X column.
        y_col: The EXACT numeric column for the Y axis (line/bar/scatter) or
            the EXACT numeric values for the pie slices. Ignored for hist.
        title: Optional chart title.
    """
    def _impl():
        import matplotlib
        matplotlib.use("Agg")
        import matplotlib.pyplot as plt
        from matplotlib.ticker import FuncFormatter

        # Professional style + Khmer-capable font (cached probe; charts on
        # machines without a Khmer font degrade gracefully, never crash).
        _apply_chart_style(_khmer_font_family())
        fmt = FuncFormatter(lambda v, _pos: _fmt_num(v))

        df = _load_dataframe(file_path)
        wanted = [x_col] + ([y_col] if y_col else [])
        missing = _missing_columns(df, wanted)
        if missing:
            return f"❌ save_chart failed: {missing}"
        if chart_type not in ("line", "bar", "pie", "hist", "scatter"):
            return f"❌ Unsupported chart_type '{chart_type}'. Use: line, bar, pie, hist, scatter."

        fig, ax = plt.subplots(figsize=(9, 5.2), dpi=150)
        if chart_type == "line":
            series = df.groupby(x_col)[y_col].sum().sort_index()
            ax.plot(series.index.astype(str), series.values, marker="o",
                    linewidth=2.5, markersize=5, color=_CHART_PALETTE[0])
            ax.set_xlabel(str(x_col))
            ax.set_ylabel(str(y_col))
            ax.yaxis.set_major_formatter(fmt)
            _maybe_rotate_xticks(ax, series)
        elif chart_type == "bar":
            series = df.groupby(x_col)[y_col].sum().sort_values(ascending=False)
            bars = ax.bar(series.index.astype(str), series.values,
                          color=_CHART_PALETTE[0], width=0.65)
            ax.set_xlabel(str(x_col))
            ax.set_ylabel(str(y_col))
            ax.yaxis.set_major_formatter(fmt)
            ax.bar_label(bars, fmt=_fmt_num, fontsize=9, padding=2)
            ax.margins(y=0.12)
            _maybe_rotate_xticks(ax, series)
        elif chart_type == "pie":
            series = df.groupby(x_col)[y_col].sum()
            colors = [_CHART_PALETTE[i % len(_CHART_PALETTE)] for i in range(len(series))]
            ax.pie(series.values, labels=series.index.astype(str), autopct="%1.1f%%",
                   startangle=90, counterclock=False, colors=colors,
                   wedgeprops={"edgecolor": "white", "linewidth": 1.5})
            ax.set_ylabel("")
        elif chart_type == "hist":
            ax.hist(df[x_col].dropna(), bins=min(20, int(df[x_col].nunique()) or 1),
                    color=_CHART_PALETTE[1], edgecolor="white", linewidth=0.8)
            ax.set_xlabel(str(x_col))
            ax.set_ylabel("Count")
            ax.xaxis.set_major_formatter(fmt)
        elif chart_type == "scatter":
            ax.scatter(df[x_col], df[y_col], color=_CHART_PALETTE[0],
                       alpha=0.75, s=42, edgecolor="white", linewidth=0.6)
            ax.set_xlabel(str(x_col))
            ax.set_ylabel(str(y_col))
            ax.xaxis.set_major_formatter(fmt)
            ax.yaxis.set_major_formatter(fmt)
        ax.set_title(title or f"{y_col or x_col} by {x_col}",
                     fontsize=14, fontweight="bold", pad=12)
        fig.tight_layout()

        out_dir = get_active_report_dir() or Path(mr.DATA_OUTPUT_DIR)
        out_dir.mkdir(parents=True, exist_ok=True)
        stem = title.replace(" ", "_")[:40] if title else f"{chart_type}_{x_col}_{y_col or x_col}"
        stem = "".join(c for c in stem if c.isalnum() or c in ("-", "_")).strip("_") or chart_type
        name = f"{stem}.png"
        # High DPI (150) keeps the chart crisp on HiDPI screens; the white
        # facecolor guarantees the image is legible in dark mode too.
        fig.savefig(out_dir / name, dpi=150, bbox_inches="tight", facecolor="white")
        # Keep DATA_OUTPUT_DIR in sync as fallback
        fallback_dir = Path(mr.DATA_OUTPUT_DIR)
        fallback_dir.mkdir(parents=True, exist_ok=True)
        if out_dir.resolve() != fallback_dir.resolve():
            try:
                shutil.copy2(out_dir / name, fallback_dir / name)
            except OSError:
                pass
        plt.close(fig)
        return f"βœ… Chart saved as: {name}"

    try:
        return _run_with_timeout(_impl, timeout_seconds=60.0)
    except Exception as e:
        return f"❌ save_chart failed: {e}"


save_chart.input_aliases = {
    "file_path": ("filepath", "file", "path", "filename", "data_path", "source"),
    "chart_type": ("type", "kind", "plot_type"),
    "x_col": ("x", "x_axis", "category_col", "column_x"),
    "y_col": ("y", "y_axis", "value_col", "metric_col", "column_y"),
    "title": ("chart_title", "name", "heading"),
}


# ──────────────────────────────────────────────────────────────────
# Missing-data completion ("complete the missing data")
# ──────────────────────────────────────────────────────────────────
# A GENERAL missing-data completion tool for ANY dataset / file type
# (.csv β€” comma/tab/semicolon β€” and .xlsx): when a file leaves cells or
# columns blank, the worker can COMPLETE them from the rest of the data β€”
# an explicit rule (rules={'αž€αžΆαžαŸ‹αž–αž“αŸ’αž’': '...'}), a relation auto-derived
# from the column names (payroll: net = base + bonus βˆ’ tax; generic:
# quantity Γ— unit price = total β€” the latter validated against the
# column's known values), or the standard statistical treatment (mean /
# mode of the observed values for partially-blank columns). The tool
# NEVER invents numbers: only cells whose value is computed from real
# source values (or honestly estimated from observed ones, clearly
# labeled) are filled, and blank columns that cannot be completed are
# reported honestly instead of guessed.

_KHMER_DIGITS = str.maketrans("០៑្៣ៀαŸ₯៦៧៨៩", "0123456789")


def _to_number(v):
    """Coerce one cell to a float β€” tolerating the two formatting
    corruptions real uploads carry: thousands separators ('1,100.00') and
    Khmer digits ('្្'). Returns None for anything non-numeric (blank
    cells included)."""
    import math

    if v is None:
        return None
    if isinstance(v, float) and math.isnan(v):
        return None
    s = str(v).strip().translate(_KHMER_DIGITS).replace(",", "").replace(" ", "")
    if not s:
        return None
    try:
        return float(s)
    except ValueError:
        return None


def _blank_mask(series):
    """True per row when the cell is blank: NaN/None OR an empty/whitespace
    string. pandas reads an entirely-blank CSV column as NaN floats, but a
    partially-blank column can come through as object dtype with ''."""
    import pandas as pd

    blank = pd.isna(series)
    blank |= series.astype("object").astype(str).str.strip().isin(["", "nan", "None"])
    return blank


def _fmt_cell(v) -> str:
    """Display one cell: '' for blank, a tidy number (990 β†’ '990', 995.55
    β†’ '995.55') for numeric values, else the raw string."""
    import pandas as pd

    n = _to_number(v)
    if n is None:
        return "" if _blank_mask(pd.Series([v])).iloc[0] else str(v)
    s = f"{round(n, 2):.2f}".rstrip("0").rstrip(".")
    return s if s else "0"


def _norm_col_name(name: str) -> str:
    """Column-name fingerprint for payroll-role detection: lowercase,
    separators/punctuation stripped, but ALL MARK CHARACTERS KEPT (Mn
    nonspacing β€” the coeng U+17D2 β€” AND Mc spacing marks β€” the Khmer vowel
    signs U+17B6..U+17C6 like αŸ„) β€” so 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD)' and 'Net
    Salary' both fingerprint cleanly and match by substring. Stripping the
    marks (e.g. only isalnum(), which drops both mark classes) corrupts the
    Khmer tokens so 'αžŸαž»αž‘αŸ’αž’' / 'αž‚αŸ„αž›' never match their own fingerprints β€”
    the silent roles={} bug this fixes (observed: unicodedata.combining()
    alone still dropped the Mc vowel signs, leaving 'αž‚αž›' for 'αž‚αŸ„αž›')."""
    import unicodedata

    return "".join(
        ch for ch in str(name).lower()
        if ch.isalpha() or unicodedata.category(ch) in ("Mn", "Mc", "Me")
    )


def _classify_columns(df) -> dict:
    """Map the dataframe's columns to ROLES by name (Khmer + English): the
    payroll roles (base / bonus / tax / net / gross) plus the generic
    derived-column roles (qty, unit_price, total) β€” so the completion tool
    understands ANY dataset, not just payroll sheets. Detection is
    substring-based on the fingerprint, so partially translated headers
    still match. Role branches are ordered so a payroll column is never
    misread as a generic one (e.g. αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ β†’ net, not total; the
    hours / position / ID columns match nothing)."""
    roles = {}
    for col in df.columns:
        n = _norm_col_name(col)
        if "αžŸαž»αž‘αŸ’αž’" in n or "net" in n:
            roles.setdefault("net", col)
        elif "αž€αžΆαžαŸ‹αž–αž“αŸ’αž’" in n or "tax" in n or "deduct" in n:
            roles.setdefault("tax", col)
        elif "αž‚αŸ„αž›" in n or "base" in n:
            roles.setdefault("base", col)
        elif "αž”αž“αŸ’αžαŸ‚αž˜" in n or "bonus" in n or "allowance" in n or "overtime" in n:
            roles.setdefault("bonus", col)
        elif "gross" in n or ("αžŸαžšαž»αž”" in n and "αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚" in n):
            roles.setdefault("gross", col)
        elif "αž”αžšαž·αž˜αžΆαžŽ" in n or "quantity" in n or "qty" in n or "units" in n:
            roles.setdefault("qty", col)
        elif "αžαž˜αŸ’αž›αŸƒ" in n or "unit price" in n or "price" in n or "rate" in n:
            roles.setdefault("unit_price", col)
        elif "αžŸαžšαž»αž”" in n or "total" in n or "revenue" in n or "sum" in n or "αž…αŸ†αžŽαžΌαž›" in n:
            roles.setdefault("total", col)
    return roles


def _has_values(df, col) -> bool:
    """True when the column has at least one non-blank cell β€” a formula
    whose source column is entirely blank could never compute anything."""
    return bool((~_blank_mask(df[col])).any())


def _payroll_role_aliases(df) -> dict:
    """Canonical payroll-role aliases β†’ the EXACT column name, keyed by
    fingerprint: 'tax' β†’ 'αž€αžΆαžαŸ‹αž–αž“αŸ’αž’', 'net salary'/'net' β†’ 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’
    (USD)', 'base salary' β†’ 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αž‚αŸ„αž› (USD)', … Built from the
    detected roles so a model writing completion rules with TRANSLATED
    names still works β€” the observed E2B failure: the worker passed
    rules={'tax': '…'} against a αž€αžΆαžαŸ‹αž–αž“αŸ’αž’ column and the tool refused with
    'Rule column tax not found' instead of completing the payroll."""
    roles = _classify_columns(df)
    aliases = {}
    for role, col in roles.items():
        aliases[_norm_col_name(role)] = col
    for token, role in (("base salary", "base"), ("gross salary", "gross"),
                        ("net salary", "net"), ("take home", "net"),
                        ("allowance", "bonus"), ("deduction", "tax"),
                        ("tax deduction", "tax")):
        if roles.get(role):
            aliases[_norm_col_name(token)] = roles[role]
    return aliases


def _resolve_rule_column(df, aliases, key) -> Optional[str]:
    """Map a completion-rule target name to the EXACT column name: exact
    match first, then a payroll-role alias ('tax' β†’ 'αž€αžΆαžαŸ‹αž–αž“αŸ’αž’'), then a
    fingerprint match (case / space / paren-insensitive). None when nothing
    matches β€” the caller reports the real column list."""
    if key in df.columns:
        return key
    fp = _norm_col_name(key)
    if not fp:
        return None
    if fp in aliases:
        return aliases[fp]
    for col in df.columns:
        if _norm_col_name(col) == fp or fp in _norm_col_name(col):
            return col
    return None


def _substitute_formula_aliases(df, aliases, formula) -> str:
    """Rewrite a completion-rule formula so every payroll-role alias is
    replaced by the EXACT column name (the model's '… - tax' becomes
    '… - αž€αžΆαžαŸ‹αž–αž“αŸ’αž’') before evaluation. Exact column names are protected by
    substituting longest-first (an exact name never gets partially
    rewritten by a shorter alias inside it)."""
    subs = {str(col): str(col) for col in df.columns}
    for alias, col in aliases.items():
        subs[alias] = col
    expr = str(formula)
    for name in sorted(subs, key=len, reverse=True):
        expr = expr.replace(name, subs[name])
    return expr


def _auto_payroll_rules(df) -> list:
    """Auto-derived completion rules from the detected payroll column
    roles: a list of (target_column, formula, description) tried in order.
    Only targets columns that still have blank cells, and only when every
    source column the formula needs actually HAS values (so the user's
    both-columns-blank payroll sheet is honestly reported as underivable
    rather than filled with NaN or guessed numbers)."""
    roles = _classify_columns(df)
    blank = {c for c in df.columns if _blank_mask(df[c]).any()}
    rules = []

    def sources_have_values(*names) -> bool:
        return all(roles.get(n) and _has_values(df, roles[n]) for n in names)

    if roles.get("net") in blank and sources_have_values("base", "bonus", "tax"):
        rules.append((roles["net"],
                      f"{roles['base']} + {roles['bonus']} - {roles['tax']}",
                      "net = base + bonus βˆ’ tax"))
    if roles.get("tax") in blank and sources_have_values("base", "bonus", "net"):
        rules.append((roles["tax"],
                      f"{roles['base']} + {roles['bonus']} - {roles['net']}",
                      "tax = base + bonus βˆ’ net"))
    if roles.get("net") in blank and sources_have_values("gross", "tax"):
        rules.append((roles["net"],
                      f"{roles['gross']} - {roles['tax']}",
                      "net = gross βˆ’ tax"))
    if roles.get("gross") in blank and sources_have_values("base", "bonus"):
        rules.append((roles["gross"],
                      f"{roles['base']} + {roles['bonus']}",
                      "gross = base + bonus"))
    if roles.get("tax") in blank and sources_have_values("gross", "net"):
        rules.append((roles["tax"],
                      f"{roles['gross']} - {roles['net']}",
                      "tax = gross βˆ’ net"))
    return rules


def _validate_formula_against_known(df, col, result, tolerance: float = 0.01) -> bool:
    """The general-tool SAFETY GATE: does a proposed derivation reproduce
    the column's KNOWN (non-blank) values? A formula is only allowed to
    fill the blank cells when it matches reality on EVERY observed row
    (within a small absolute+relative tolerance for money rounding). A
    wrong guess β€” e.g. 'sum of the other numeric columns' against a
    quantityΓ—price Total β€” fails against the known totals and is never
    applied, so blanks can never be filled with fabricated numbers."""
    known = ~_blank_mask(df[col])
    result_num = result.map(_to_number)
    known_num = df[col].map(_to_number)
    ok = known & result_num.notna() & known_num.notna()
    if not ok.any():
        return False  # nothing observed to validate against
    diff = (result_num[ok] - known_num[ok]).abs()
    scale = known_num[ok].abs()
    return bool((diff <= tolerance + tolerance * scale).all())


def _auto_generic_rules(df, roles=None) -> list:
    """Auto-derived completion rules for ANY dataset, beyond payroll:
    generic derived totals recognized from the column names β€” quantity Γ—
    unit price = total (the classic e-commerce/invoice relation), or sum of
    the other numeric columns as a fallback β€” each applied ONLY when it
    reproduces the column's known values (see
    _validate_formula_against_known), so a misidentified relation can
    never fill blanks with invented numbers. Returns (target, formula,
    description) tuples, tried in order."""
    import pandas as pd

    roles = roles if roles is not None else _classify_columns(df)
    blank = {c for c in df.columns if _blank_mask(df[c]).any()}
    rules = []
    total_col = roles.get("total")
    if total_col in blank:
        qty_col, price_col = roles.get("qty"), roles.get("unit_price")
        if qty_col and price_col and _has_values(df, qty_col) and _has_values(df, price_col):
            formula = f"{qty_col} * {price_col}"
            result, err = _apply_formula(df, formula)
            if not err and _validate_formula_against_known(df, total_col, result):
                rules.append((total_col, formula, "total = quantity Γ— unit price"))
        # Fallback: total = sum of the OTHER numeric columns β€” only when it
        # matches the known totals (so it can never misfire on a
        # multiplicative total like qtyΓ—price).
        numeric = [
            c for c in df.columns
            if c != total_col and (
                pd.api.types.is_numeric_dtype(df[c])
                or df[c].map(_to_number).notna().all()
            )
        ]
        if len(numeric) >= 2:
            formula = " + ".join(numeric)
            result, err = _apply_formula(df, formula)
            if not err and _validate_formula_against_known(df, total_col, result):
                rules.append((total_col, formula,
                              "total = sum of the other numeric columns"))
    return rules


def _impute_columns(df, blank_cols, changed, lines, filled) -> None:
    """Statistical estimation for partially-blank columns β€” the standard
    missing-data treatment that works on ANY dataset: numeric columns are
    completed with the MEAN of the observed values, categorical columns
    with the MOST COMMON value (mode). Fully-blank columns (no observed
    values) are never imputed β€” there is no basis, and the tool reports
    them honestly instead. Imputed cells are clearly labeled as estimates."""
    import pandas as pd

    for col in blank_cols:
        if col in filled:
            continue
        observed = df[col][~_blank_mask(df[col])]
        if len(observed) == 0:
            continue  # fully blank β€” no basis to estimate
        mask = _blank_mask(df[col])
        n = int(mask.sum())
        if n == 0:
            continue
        coerced = observed.map(_to_number)
        if coerced.notna().all():
            mean = float(coerced.mean())
            df.loc[mask, col] = round(mean, 2)
            changed |= mask
            filled[col] = "statistical estimate"
            lines.append(
                f"ℹ️ Column '{col}': estimated {n} blank cell(s) as the mean "
                f"({mean:.4g}) of the {len(observed)} observed values."
            )
        else:
            mode_val = observed.mode()
            if len(mode_val) == 0:
                continue
            mode_val = mode_val.iloc[0]
            df.loc[mask, col] = mode_val
            changed |= mask
            filled[col] = "statistical estimate"
            lines.append(
                f"ℹ️ Column '{col}': estimated {n} blank cell(s) as the most "
                f"common value ('{mode_val}') of the {len(observed)} observed "
                f"values."
            )


def _apply_formula(df, formula):
    """Evaluate a per-row formula written with the EXACT column names over
    the dataframe (referenced source cells coerced to numbers β€” commas and
    Khmer digits tolerated). Returns (Series, None) on success or
    (None, error_msg); the error carries the real cause so the model can
    fix the formula instead of guessing."""
    import pandas as pd

    expr = str(formula).replace("Γ—", "*").replace("βˆ’", "-").replace("Γ·", "/")
    locals_ = {}
    # Longest-first replacement so a column whose name is a PREFIX of
    # another (e.g. 'αžˆαŸ’αž˜αŸ„αŸ‡' vs 'αžˆαŸ’αž˜αŸ„αŸ‡αž αžΆαž„') can't corrupt the longer one.
    for i, col in enumerate(sorted(df.columns, key=lambda c: -len(str(c)))):
        token = f"col_{i}"
        expr = expr.replace(str(col), token)
        locals_[token] = df[col].map(_to_number)
    try:
        result = pd.eval(expr, local_dict=locals_)
    except Exception as e:
        return None, f"could not evaluate the formula '{formula}': {e}"
    if isinstance(result, pd.Series) and len(result) == len(df):
        return result.map(_to_number), None
    return None, f"the formula '{formula}' did not produce one value per row"


def _fill_blanks(df, col, result) -> int:
    """Fill the blank cells of `col` with the computed values where the
    formula produced a real number (rounding money to 2 decimals). Returns
    the number of cells filled."""
    mask = _blank_mask(df[col]) & result.notna()
    n = int(mask.sum())
    if n:
        df.loc[mask, col] = result[mask].round(2)
    return n


def _completion_table(df, changed_rows) -> str:
    """Markdown table of the rows where at least one blank cell was filled,
    showing the WHOLE row so the completed values read in context. Capped at
    25 rows β€” the findings text the manager reads must stay compact."""
    if not changed_rows.any():
        return ""
    sub = df.loc[changed_rows].head(25)
    cols = list(sub.columns)
    lines = ["| " + " | ".join(str(c) for c in cols) + " |",
             "|" + "---|" * len(cols)]
    for _, row in sub.iterrows():
        lines.append("| " + " | ".join(_fmt_cell(v) for v in row) + " |")
    total = int(changed_rows.sum())
    if total > 25:
        lines.append(f"… showing the first 25 of {total} completed rows")
    return "\n".join(lines)


@tool
def complete_missing_data(file_path: str, rules: Optional[dict] = None,
                          impute: bool = True) -> str:
    """Detect BLANK (missing/empty) cells and COMPLETE them from the rest
    of the data β€” the general missing-data completion tool that works on
    ANY dataset and file type (.csv β€” comma/tab/semicolon β€” and .xlsx),
    not just payroll sheets.

    Three strategies are applied in order, and each only fills cells it
    can honestly compute β€” nothing is ever invented:
      1. EXPLICIT RULES: rules={'<column>': '<formula with the exact
         column names>'} β€” applied in dict order, so a later rule can use
         values an earlier one just filled (tax before net). English /
         Khmer payroll aliases work too ('tax' β†’ αž€αžΆαžαŸ‹αž–αž“αŸ’αž’).
      2. AUTO-DERIVED COLUMNS from the column names: payroll relations
         (net = base + bonus βˆ’ tax, tax = base + bonus βˆ’ net, gross = base
         + bonus, …) AND generic derived totals (quantity Γ— unit price =
         total, or the sum of the numeric components) β€” the generic ones
         are applied ONLY when they reproduce the column's KNOWN values
         (validated against observed rows), so a wrong guess can never
         fill blanks.
      3. STATISTICAL ESTIMATION (impute=True): partially-blank columns
         with observed values are completed with the MEAN (numeric) or
         the MOST COMMON value (categorical) of those observed values β€”
         the standard missing-data treatment, clearly labeled as
         estimates.

    Example for a payroll sheet:
      rules={'αž€αžΆαžαŸ‹αž–αž“αŸ’αž’': '(αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αž‚αŸ„αž› (USD) + αž”αŸ’αžšαžΆαž€αŸ‹αž”αž“αŸ’αžαŸ‚αž˜) * 0.10',
             'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD)': 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αž‚αŸ„αž› (USD) + αž”αŸ’αžšαžΆαž€αŸ‹αž”αž“αŸ’αžαŸ‚αž˜ - αž€αžΆαžαŸ‹αž–αž“αŸ’αž’'}

    Fully-blank columns with no observed values and no derivable rule are
    reported honestly (never guessed). Numbers tolerate thousands
    separators ('1,100.00') and Khmer digits (្្).

    Args:
        file_path: Absolute path to the uploaded data file (.csv or .xlsx).
        rules: Optional dict {column: formula} of explicit completion
            rules.
        impute: Whether to statistically estimate partially-blank columns
            (default True).
    """
    try:
        import pandas as pd

        df = _load_dataframe(file_path)
        blank_cols = [c for c in df.columns if _blank_mask(df[c]).any()]
        if not blank_cols:
            return "βœ… No missing values found β€” every column is already complete."
        # Strategy 1: explicit rules (in dict order, chained β€” a later rule
        # can use values an earlier one just filled). Rule keys AND
        # formulas go through the payroll-role alias resolver: a model
        # writing rules={'tax': …} against a αž€αžΆαžαŸ‹αž–αž“αŸ’αž’ column (the observed
        # E2B failure) is mechanically cured instead of refused.
        aliases = _payroll_role_aliases(df)
        plan = []
        for raw_col, formula in (rules or {}).items():
            col = _resolve_rule_column(df, aliases, raw_col)
            if col is None:
                return (f"❌ Rule column '{raw_col}' not found. Available columns: "
                        f"{list(df.columns)}")
            plan.append((col, _substitute_formula_aliases(df, aliases, formula),
                         f"explicit rule"))
        # Strategy 2: auto-derived relations β€” payroll identities first,
        # then the generic validated totals for any other dataset.
        plan.extend(_auto_payroll_rules(df))
        plan.extend(_auto_generic_rules(df))
        filled_total = 0
        completed = {}  # column -> formula actually used
        changed = pd.Series(False, index=df.index)
        lines = []
        for col, formula, desc in plan:
            result, err = _apply_formula(df, formula)
            if err:
                lines.append(f"⚠️ Column '{col}': {err}")
                continue
            before = _blank_mask(df[col])
            n = _fill_blanks(df, col, result)
            if n:
                filled_total += n
                changed |= before & ~_blank_mask(df[col])
                completed[col] = formula
                lines.append(f"βœ… Column '{col}': filled {n} cell(s) β€” {desc}: {formula}")
        # Strategy 3: statistical estimation of whatever is still partially
        # blank (mean / mode of the observed values) β€” never for
        # fully-blank columns.
        if impute:
            _impute_columns(df, blank_cols, changed, lines, completed)
        out = []
        if completed:
            out.append(f"βœ… complete_missing_data: completed {len(completed)} column(s), "
                       f"{filled_total} cell(s) filled.")
        remaining = [c for c in blank_cols if _blank_mask(df[c]).any()]
        if remaining:
            out.append(
                f"⚠️ {len(remaining)} blank column(s) could not be completed: "
                + ", ".join(f"'{c}'" for c in remaining)
                + " β€” no derivable formula and no observed values to estimate "
                "from (they are entirely blank). If you know the rule, pass it "
                "explicitly, e.g. rules={'αž€αžΆαžαŸ‹αž–αž“αŸ’αž’': '(αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αž‚αŸ„αž› (USD) + "
                "αž”αŸ’αžšαžΆαž€αŸ‹αž”αž“αŸ’αžαŸ‚αž˜) * 0.10', 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD)': 'αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αž‚αŸ„αž› "
                "(USD) + αž”αŸ’αžšαžΆαž€αŸ‹αž”αž“αŸ’αžαŸ‚αž˜ - αž€αžΆαžαŸ‹αž–αž“αŸ’αž’'}."
            )
        out.extend(lines)
        table = _completion_table(df, changed)
        if table:
            out.append("\nCompleted rows (values filled / estimated above):\n" + table)
        return "\n".join(out)
    except Exception as e:
        return f"❌ complete_missing_data failed: {e}"


# ──────────────────────────────────────────────────────────────────
# Sub-agent identity (required by smolagents' managed_agents machinery).
# ──────────────────────────────────────────────────────────────────
DATA_WORKER_NAME = "data_worker"
DATA_WORKER_DESCRIPTION = (
    "Runs ONE focused data-analysis sub-task against the user's uploaded "
    "data files (load the file, list columns, aggregate/summarize columns, "
    "create charts) and returns a concise findings report with the actual "
    "numbers and chart filenames. Call with task='<the focused sub-task>' "
    "(e.g. data_worker(task='Compute the total of column αžŸαžšαž»αž” (USD)')). It "
    "has NO memory of any other call, so every task must be fully "
    "self-contained β€” name the data file(s) and the exact columns to use."
)

# The `data_worker` sub-agent's step budget for ONE focused sub-task (the
# manager's budget is DATA_AGENT_MAX_STEPS). Scaled down for very large
# models like every other sub-agent (see get_max_steps_for_model).
DATA_WORKER_DEFAULT_MAX_STEPS = 10

# How often (in manager steps) the manager stops to re-plan β€” smolagents'
# own `planning_interval` mechanism, the same one RAG / Deep Research use
# to make a research loop "deep" instead of a single-pass agentic chat.
DATA_MANAGER_PLANNING_INTERVAL = 3

# Default per-step Python-execution timeout (seconds) applied when the Data
# tab's "Exec timeout" control is on AUTO. smolagents' own default is 30s,
# which is too tight for the worker's real steps: loading an .xlsx,
# grouping, and rendering a chart can legitimately exceed 30s per step on
# modest hardware (observed end-to-end: "Code execution exceeded the
# maximum execution time of 30 seconds" on a heavy bundled EDA step). The
# footer reports the ACTUAL applied value, so an auto run shows this number.
DATA_EXECUTION_TIMEOUT_DEFAULT = 120

# final_answer_checks validator threshold for the manager's report: a
# final answer shorter than this isn't a real data-analysis report.
MIN_FINAL_REPORT_CHARS = 150

# ──────────────────────────────────────────────────────────────────
# Manager system instructions (applied once at construction, if this
# smolagents version supports `instructions=`; the per-call task in
# build_data_task() repeats the core rules β€” belt and braces, the same
# pattern as rag_agent's STRICT_SYSTEM_INSTRUCTIONS / build_strict_task).
# ──────────────────────────────────────────────────────────────────
DATA_MANAGER_INSTRUCTIONS = (
    "You are a data-analysis research manager. You answer the user's data "
    "question by DELEGATING the actual work β€” you never load the data or "
    "run Python yourself.\n\n"
    "You do NOT have any data tools. The ONLY agent that exists is "
    "`data_worker`, which runs the computations for you. There is no "
    "list_columns, aggregate, summarize_numeric, save_chart, "
    "complete_missing_data, or install_package tool on you β€” never call "
    "anything else.\n"
    "Call it from your code block as a plain Python expression, exactly "
    "like a tool: worker_result = data_worker(task='...')\n"
    "print(worker_result)\n"
    "The value it returns is the worker's findings text β€” read it and "
    "include the real numbers from it in your report.\n\n"
    "Work like this:\n"
    "1. ANALYZE the user's question: what numbers, breakdowns, charts or "
    "computations are actually being asked for?\n"
    "2. DECOMPOSE it into 1-3 sub-tasks and BUNDLE related computations into "
    "as few data_worker calls as possible. Each data_worker call is an "
    "expensive fresh worker run, so ONE task can (and should) ask the worker "
    "to do several related things together β€” e.g. 'list the columns, compute "
    "the total of column X and column Y, break them down by column Z and by "
    "column W, and create a bar chart of X by Z' is a single call, not four. "
    "Only split when a sub-task genuinely depends on a previous result.\n"
    "3. DELEGATE: call `data_worker` once per sub-task with a fully "
    "self-contained task string: name the data file(s) and the EXACT column "
    "names to use (e.g. data_worker(task='Compute the total of column "
    "αžŸαžšαž»αž” (USD) from the file ...xlsx')). Never invent column names β€” the "
    "worker will list the exact ones; if you are unsure of a column name, "
    "delegate a 'list the columns' sub-task first.\n"
    "4. RE-CHECK your plan periodically against what the worker actually "
    "returned (read its findings from the printed result of each "
    "data_worker call): if a finding changes what you still need, adjust "
    "instead of blindly finishing the original plan. If a sub-task comes "
    "back thin or empty, delegate again with a different angle β€” never "
    "repeat an identical task.\n"
    "5. SYNTHESIZE: once you have enough findings, write a well-structured "
    "Markdown report using ONLY the numbers and results the `data_worker` "
    "actually returned. Include every concrete value (totals, per-group "
    "breakdowns, statistics) verbatim from the findings β€” never estimate, "
    "guess, or recompute them yourself, and never write placeholders. "
    "Reference each chart by its exact PNG filename the worker reported.\n"
    "6. You MUST call `data_worker` at least once β€” a final answer written "
    "without any data_worker call will be REJECTED and sent back to you, so "
    "do not describe what you would do; actually delegate the work.\n"
    "7. If the system rejects your final answer for formatting or for a "
    "missing data_worker call, do NOT start any new worker calls. Keep the "
    "same findings, rewrite only the final report so it satisfies the "
    "checker, and call `final_answer(...)` again.\n\n"
    "TERMINATION REQUIREMENT: you MUST submit your final answer by calling "
    "the special `final_answer(report_text)` tool β€” this is the ONLY way to "
    "actually end the task. Simply printing or writing the report as plain "
    "text does NOT end the run: without calling `final_answer(...)`, you "
    "will be given another step and may end up starting unnecessary new "
    "worker calls even though your report was already complete.\n\n"
    "The user's actual question is in the Task below β€” answer THAT, not "
    "these instructions. Never repeat, summarize, or reply to the "
    "instructions themselves."
)

# ──────────────────────────────────────────────────────────────────
# Sub-agent system instructions: the exact-column-name rule, tool usage,
# sandbox rules, and the findings-report format the worker must return.
# The data file paths are appended at build time (see
# _build_worker_agent) so the worker always knows what to read without
# relying on the manager remembering to pass them.
# ──────────────────────────────────────────────────────────────────
DATA_WORKER_INSTRUCTIONS = (
    "You are a focused data-analysis worker running inside a local Python "
    "sandbox with pandas, matplotlib, and common data-science libraries. "
    "The research manager gives you ONE focused sub-task β€” answer only "
    "that task, fully self-contained. You have NO memory of any other call.\n\n"
    "β˜… COLUMN NAMES β€” ALWAYS USE THE EXACT NAMES FROM THE DATA\n"
    "   - Column names are EXACTLY as they appear in the file and may be in "
    "Khmer or any other language, with spaces/slashes/parentheses (e.g. "
    "'αž”αžšαž·αž˜αžΆαžŽ', 'αžαž˜αŸ’αž›αŸƒ/αž―αž€αžαžΆ (USD)', 'αžŸαžšαž»αž” (USD)', 'αž€αžΆαž›αž”αžšαž·αž…αŸ’αž†αŸαž‘'). NEVER "
    "translate, rename, guess, or invent column names β€” and never assume "
    "English equivalents like 'Quantity', 'Unit Price', 'Date', or "
    "'Product'.\n"
    "   - After loading, ALWAYS run print(df.columns.tolist()) and copy the "
    "column names it prints VERBATIM into your code. Access columns with "
    "bracket syntax, e.g. df['αž”αžšαž·αž˜αžΆαžŽ'], never df.quantity.\n"
    "   - If any step raises a KeyError on a column name, STOP guessing β€” "
    "re-print df.columns.tolist(), take the real name, and retry. Do NOT "
    "keep using a name the data does not have.\n\n"
    "WORKFLOW:\n"
    "1. Load the named file with pandas (pd.read_csv for .csv, pd.read_excel "
    "for .xlsx/.xls β€” if a required package like 'openpyxl' is missing, call "
    "the install_package tool with its pip name first, then retry the import).\n"
    "2. PREFER THE BUILT-IN TOOLS for the operations they cover (they never "
    "guess column names and never hit the sandbox's file limits):\n"
    "   * list_columns(file_path) β€” exact column names + dtypes + first rows.\n"
    "   * aggregate(file_path, group_col, value_col, agg) β€” sum/mean/count/"
    "min/max grouped by a column; pass group_col='' for the OVERALL "
    "(grand-total) aggregate of the whole column.\n"
    "   * summarize_numeric(file_path, value_col) β€” count/mean/std/quartiles/"
    "min/max/sum for one numeric column.\n"
    "   * save_chart(file_path, chart_type, x_col, y_col, title) β€” line / "
    "bar / pie / hist / scatter saved directly into the charts folder; it "
    "returns the PNG filename.\n"
    "   * complete_missing_data(file_path, rules=None, impute=True) β€” detect "
    "and COMPLETE blank (empty) cells in ANY dataset (.csv/.xlsx): explicit "
    "rules={{'<column>': '<formula with the exact column names>'}} (e.g. a "
    "payroll sheet with αž€αžΆαžαŸ‹αž–αž“αŸ’αž’ / tax and αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD) / net "
    "salary left blank), auto-derived relations from the column names "
    "(payroll: net = base + bonus βˆ’ tax, …; generic: quantity Γ— unit price "
    "= total, validated against known rows), and statistical estimation of "
    "partially-blank columns (mean for numeric, most common value for "
    "categorical). It NEVER invents numbers β€” every filled cell is computed "
    "from real values or clearly labeled as an estimate β€” and reports "
    "honestly which blank cells it could not complete.\n"
    "   These tools take the FILE PATH as their first argument and return "
    "results as text or a βœ… chart confirmation. Hand-written pandas/"
    "matplotlib is still allowed for anything the tools don't cover.\n"
    "3. Save EVERY chart as a PNG with a descriptive filename (use "
    "save_chart, or plt.savefig(...) followed ALWAYS by plt.close(); never "
    "call plt.show()).\n"
    "4. Do NOT try to write a report or data file β€” the sandbox blocks raw "
    "open()/write(), and there is no file-save tool. (plt.savefig() is "
    "whitelisted separately and works fine.)\n\n"
    "RETURN β€” TRANSCRIBE, DO NOT NARRATE: your final_answer MUST contain "
    "the EXACT tool outputs you received, copied VERBATIM β€” the column "
    "list from list_columns, the numbers and Markdown tables from "
    "aggregate / summarize_numeric, the exact 'βœ… Chart saved as: "
    "<filename>.png' line from save_chart. The manager writes the final "
    "report from YOUR final_answer, so everything you do not pass to "
    "final_answer is lost. NEVER paraphrase, summarize, round, or invent "
    "values β€” and never write prose describing what you did (a narrative "
    "with no tool output is rejected). If the sub-task cannot be done "
    "(missing file, unknown column, impossible computation), copy the "
    "actual tool error message into final_answer instead of guessing.\n\n"
    "{files_block}"
)

DATA_WORKER_FILES_HEADER = (
    "DATA FILES (the uploaded data files β€” pass one of these absolute paths "
    "to the tools' file_path argument):\n"
)

# Replaces smolagents' default managed-agent task template, which demands a
# three-part narrative final answer ("Task outcome (short version)…") β€” a
# structure that invites small GGUF workers to write prose with INVENTED
# numbers instead of transcribing their real tool outputs (the root-cause
# failure observed end-to-end: the worker ran aggregate() correctly but
# "reported" totals of 15,234 / 123,456 instead of the real 22 / 3,206).
# The override keeps the {{name}} / {{task}} placeholders populate_template
# requires, but demands verbatim tool outputs instead of a narrative.
DATA_WORKER_MANAGED_TASK_TEMPLATE = (
    "You're a focused data-analysis worker named '{{name}}'.\n"
    "You have been submitted this task by your manager.\n"
    "---\n"
    "Task:\n"
    "{{task}}\n"
    "---\n"
    "Answer ONLY that task by calling the data tools, then submit your "
    "findings with the final_answer(...) tool β€” everything you do not pass "
    "to final_answer is LOST, so the manager only sees what you put there.\n\n"
    "Your final_answer MUST contain the EXACT tool outputs you received, "
    "copied VERBATIM:\n"
    "- the full column list returned by list_columns,\n"
    "- the numbers and Markdown tables returned by aggregate / "
    "summarize_numeric,\n"
    "- the exact 'βœ… Chart saved as: <filename>.png' line returned by "
    "save_chart.\n"
    "Copy them verbatim β€” never paraphrase, summarize, round, or invent "
    "values, and never write prose describing what you did."
)

# Markers that a REAL data-tool output always carries. A worker final answer
# that called a data tool but contains NONE of these is a narrative with no
# actual findings (the fabrication failure) and is rejected with feedback.
_WORKER_FINDINGS_MARKERS = (
    "Columns (exact names", "**Sum", "count:", "mean:", "saved as:",
    "βœ…", "❌", "|",
)

# The worker's final answer IS the observation the manager reads (with
# provide_run_summary=False, the observation = the final answer verbatim).
# A 4-8K-char verbatim dump per delegation quickly fills the manager's
# 16K-token window mid-run (the "Requested tokens exceed context window"
# crash observed end-to-end), so the transcription validator also caps the
# findings size: keep the numbers verbatim, drop the fluff.
_WORKER_MAX_FINDINGS_CHARS = 3000


def _step_evidence_text(step) -> str:
    """Flatten ONE memory step into searchable text.

    A CodeAgent records EVERY step's tool_calls as ['python_interpreter'] β€”
    the actual tool (data_worker on the manager, aggregate/list_columns/… on
    the worker) is invoked INSIDE the executed code, so it only ever appears
    in `step.code_action` (the code text) or `step.observations` (the
    tool's output). Introspecting `tool_calls` alone (as this module did
    initially) can NEVER see a delegation or a data-tool call on the
    CodeAgent path β€” the root-cause bug behind the end-to-end failure where
    the manager delegated 4+ times yet every final answer was rejected as
    "WITHOUT calling data_worker". This helper unions all three evidence
    sources; version-robust (getattr / dict guards)."""
    parts = []
    for attr in ("code_action", "observations"):
        try:
            v = getattr(step, attr, None)
            if v is None and isinstance(step, dict):
                v = step.get(attr)
            if v:
                parts.append(str(v))
        except Exception:
            pass
    try:
        for tc in (getattr(step, "tool_calls", None) or []):
            name = getattr(tc, "name", None)
            if name is None and isinstance(tc, dict):
                name = tc.get("name")
            if name:
                parts.append(str(name))
    except Exception:
        pass
    return "\n".join(p for p in parts if p)


_DATA_TOOLS = ("list_columns", "aggregate", "summarize_numeric",
               "save_chart", "complete_missing_data", "install_package")


def _steps_reference_data_tools(steps) -> bool:
    """True when any memory step shows a real data-tool call: the tool-call
    name in `tool_calls` (ToolCallingAgent path) OR a call expression like
    `aggregate(` in the executed code / observation text (the CodeAgent
    path β€” see _step_evidence_text)."""
    for step in steps:
        evidence = _step_evidence_text(step)
        if not evidence:
            continue
        if any(f"{name}(" in evidence for name in _DATA_TOOLS):
            return True
    return False


def _validate_worker_findings(final_answer, memory=None, agent=None) -> bool:
    """`final_answer_checks` validator for the `data_worker` sub-agent.

    smolagents invokes it as check(final_answer, memory, agent=self) and
    feeds a raised Exception back to the model as the reason its answer was
    rejected. Catches the transcription failure: the worker ran the tools
    (real outputs in its own memory) but its final_answer is pure narration
    with invented numbers. Only enforced when the worker ACTUALLY called a
    data tool β€” a tool-less run has nothing to transcribe. Introspection
    failures never block (defensive)."""
    text = str(final_answer or "")
    called_tool = False
    try:
        steps = list(getattr(memory, "steps", None) or []) \
            or list(getattr(getattr(agent, "memory", None), "steps", None) or [])
        called_tool = _steps_reference_data_tools(steps)
    except Exception:
        # Never let memory introspection block a run.
        return True
    if not called_tool:
        return True
    # Size cap: the manager reads this whole text into its OWN context, so a
    # bloated dump is not just noise β€” it is what overflows the window
    # mid-run. Keep the numbers verbatim, drop the fluff.
    if len(text) > _WORKER_MAX_FINDINGS_CHARS:
        raise ValueError(
            f"Your findings are {len(text)} characters β€” too long (max "
            f"{_WORKER_MAX_FINDINGS_CHARS}). The manager reads your entire "
            "final_answer into its own context, so return a COMPACT findings "
            "block: the exact numbers and Markdown tables from "
            "aggregate/summarize_numeric, the column list once, and the exact "
            "'βœ… Chart saved as: <file>.png' lines. Drop the full first-3-rows "
            "dump, repeated table dumps, and any prose."
        )
    if not any(m in text for m in _WORKER_FINDINGS_MARKERS):
        raise ValueError(
            "Your final answer contains no actual tool output even though "
            "you called the data tools. Copy the EXACT results of those "
            "tool calls into final_answer(...) VERBATIM β€” the column list, "
            "the numbers, the Markdown tables, the 'βœ… Chart saved as: "
            "<filename>.png' lines. Do not describe what you did and never "
            "invent values; the manager writes the report from your exact "
            "tool outputs."
        )
    return True


# A leaked NATIVE tool-call envelope β€” `<tool_call>data_worker(task='...')</tool_call>`
# (GLM-4.7-Flash / Qwen native format) or `<|tool_call|>` variants β€” that a
# tool-calling model writes INSIDE a final_answer("""…""") string instead of
# executing data_worker as a Python expression (the observed end-to-end
# failure: GLM-4.7-Flash's manager emitted its intended delegation as an
# envelope, the validator rejected it, and the model repeated the same leak
# every step until the run died). The opening marker is matched so both
# `<tool_call>` and `<|tool_call|>` (with or without the closing pipe/brace)
# are recognized; the body is captured up to the matching close or end.
_NATIVE_TOOL_CALL_RE = re.compile(r"<\|?tool_call\|?[>|](.*?)(?:<\|?\s*/\s*\|?tool_call\|?>|$)",
                                 re.DOTALL | re.IGNORECASE)


def _task_from_envelope(content: str) -> Optional[str]:
    """Parse ONE native-envelope body for a `data_worker` task string.
    Handles the three shapes seen in the wild: the plain call form
    `data_worker(task='...')` (GLM-4.7-Flash observed), the JSON form
    `{"name": "data_worker", "arguments": {"task": "..."}}` (Qwen), and
    the `call:data_worker{task: "..."}` form (Gemma). Returns None when the
    body is not a data_worker call or no task can be extracted."""
    content = (content or "").strip()
    if not content:
        return None
    # GLM-4.7-Flash (the llama-server native tool-call format) appends a
    # stray `</arg_value>` XML fragment after the call's close paren, before
    # the `</tool_call>` close tag (observed end-to-end). Strip trailing
    # tag-ish garbage so the JSON / call: / plain forms below still parse.
    content = re.sub(r"(?:</?[a-zA-Z_][a-zA-Z0-9_]*>\s*)+$", "", content).rstrip()
    if not content:
        return None

    # JSON shape: {"name": "data_worker", "arguments": {"task": "..."}}
    if content.lstrip().startswith("{"):
        try:
            import json

            data = json.loads(content)
            if str(data.get("name", "")).strip() == DATA_WORKER_NAME:
                args = data.get("arguments") or {}
                t = args.get("task")
                if isinstance(t, str) and t.strip():
                    return t.strip()
        except Exception:
            pass

    # call:data_worker{task: "..."} shape
    m = re.search(r"call\s*:\s*data_worker\s*\{.*?task\s*:\s*(['\"])(.*?)\1",
                  content, re.DOTALL)
    if m and m.group(2).strip():
        return m.group(2).strip()

    # Plain / kwargs form: data_worker(task='...') β€” capture the whole arg
    # list (the task may contain commas and nested quotes), then the task=
    # value or the first string literal.
    m = re.search(r"data_worker\s*\((.*)\)\s*$", content, re.DOTALL)
    if m:
        args = m.group(1).strip()
        tm = re.search(r"task\s*=\s*(['\"])(.*?)\1", args, re.DOTALL)
        if tm and tm.group(2).strip():
            return tm.group(2).strip()
        sm = re.search(r"(['\"])(.*?)\1", args, re.DOTALL)
        if sm and sm.group(2).strip():
            return sm.group(2).strip()
    return None


def _extract_data_worker_task(text: str) -> Optional[str]:
    """Extract the `data_worker` task string from a leaked NATIVE tool-call
    envelope in the final-answer text. Returns None when the text carries no
    data_worker envelope (a normal report is never touched)."""
    if not text or not isinstance(text, str):
        return None
    for m in _NATIVE_TOOL_CALL_RE.finditer(text):
        task = _task_from_envelope(m.group(1))
        if task:
            return task
    return None


# How much of the rescued worker findings the rejection message carries back
# to the model β€” enough to write the grounded report, without flooding its
# context with a max-length transcript.
_RESCUE_FINDINGS_CHAR_CAP = 2200


def _rescue_leaked_data_worker_call(text, agent) -> Optional[str]:
    """When the manager's final answer is a leaked NATIVE tool-call envelope
    for `data_worker` β€” the model wrote `<tool_call>data_worker(task='...')</tool_call>`
    INSIDE the final_answer string instead of executing it as a Python
    expression (GLM/Qwen native format), so no delegation actually ran β€”
    EXECUTE the delegation on its behalf and return a rejection message that
    carries the findings, so the model can write the real report next step.
    Returns None when there is nothing to rescue (no envelope, no worker β€”
    the caller falls through to the plain "never delegated" rejection).

    The worker runs at most ONCE per run: a repeat leak reuses the first
    rescue's findings instead of re-running the expensive worker, and the
    flag is set so the follow-up report passes the delegation check. The
    findings are also appended to the executor's printed output so the
    grounding check can enforce the REAL numbers on that follow-up report
    (mirrors what a real `print(worker_result)` delegation would leave).
    Never raises."""
    if agent is None:
        return None
    task = _extract_data_worker_task(text)
    if not task:
        return None
    findings = getattr(agent, "_data_worker_rescued_findings", None)
    if findings is None:
        worker = None
        try:
            worker = (getattr(agent, "managed_agents", None) or {}).get(DATA_WORKER_NAME)
        except Exception:
            worker = None
        if worker is None:
            return None
        try:
            findings = worker(task=task)
        except Exception as e:
            findings = f"❌ data_worker failed: {e}"
        findings = str(findings or "")
        agent._data_worker_rescued_findings = findings
        agent._data_worker_delegated = True
        try:
            state = getattr(getattr(agent, "python_executor", None), "state", None)
            if state is not None:
                printed = str(state.get("_print_outputs", "") or "")
                state["_print_outputs"] = printed + "\n" + findings
        except Exception:
            pass
    if len(findings) <= _RESCUE_FINDINGS_CHAR_CAP:
        shown = findings
    else:
        shown = findings[:_RESCUE_FINDINGS_CHAR_CAP] + "\n… (truncated)"
    return (
        "You wrote your `data_worker` delegation as a native tool-call envelope "
        "(<tool_call>data_worker(...)</tool_call>) INSIDE the final_answer "
        "string instead of executing it, so no delegation actually ran. I ran "
        "it for you. The worker's findings are:\n\n"
        f"{shown}\n\n"
        "Now write your FINAL Markdown report: headings and prose plus the real "
        "numbers above copied VERBATIM (totals, breakdowns, statistics) and "
        "each chart filename, then call final_answer(report_text) again. Do NOT "
        "write another <tool_call> envelope β€” the report must be clean text for "
        "the user."
    )


def _validate_final_report(final_answer, memory=None, agent=None) -> bool:
    """`final_answer_checks` validator for the Data Analysis manager.
    smolagents invokes it as check(final_answer, memory, agent=self) and
    surfaces a raised Exception back to the model as the reason its answer
    was rejected, giving it another step to fix it (same pattern as
    rag_agent._validate_final_report). Two checks, both cheap and honest:

      1. The report isn't too short to be a real analysis.
      2. The run actually DELEGATED to `data_worker` at least once β€” a
         final answer written without a single data_worker call contains
         no real numbers (the small-model failure the orchestration exists
         to fix: a plan-narrative "final answer" that describes the work
         instead of doing it). Introspection failures never block the run
         (defensive: a future smolagents that renames the memory shape
         must not start rejecting every answer).

    The worker's findings are the source of truth for the numbers, so this
    deliberately does not police report content itself.

    First, a RESCUE: a final answer that is a leaked native `<tool_call>`
    envelope for data_worker (the model wrote its intended delegation as
    text instead of executing it β€” GLM/Qwen native format) is EXECUTED on
    the model's behalf and the findings fed back in the rejection message,
    so the model can write the real report next step instead of repeating
    the same leak until the run dies (the observed GLM-4.7-Flash failure).
    Runs before every other check so even a short envelope is rescued."""
    text = str(final_answer or "").strip()
    rescued = _rescue_leaked_data_worker_call(text, agent)
    if rescued:
        raise ValueError(rescued)
    # A final answer that LEAKS planning/code text is not a report β€” the
    # observed end-to-end failure had the manager emit a Gemma-native
    # `<|tool_call>` envelope inside `final_answer("""…""")` β€” the model
    # narrated its next delegation instead of executing it, so the run
    # "succeeded" with a report that contained no real numbers. The
    # delegation check below passes for such an answer (an earlier step
    # DID delegate, e.g. list_columns), so this catches what delegation
    # alone cannot: user-facing reports never mention the internal agent
    # name, never assign its result, and never carry a tool-call envelope
    # (both the pipe-less `<tool_call>` GLM form and the `<|tool_call|>`
    # Gemma/Qwen form). Runs before the min-length check so even a short
    # leaked envelope gets the right guidance.
    if _MANAGED_AGENT_RETURN_MARKER in text \
            or re.search(r"worker_result\s*=\s*data_worker\(", text) \
            or re.search(r"<\|?tool_call\|?[>|]", text):
        raise ValueError(
            "Your final answer contains leaked planning or code text instead "
            "of the Markdown report: it must be a clean report FOR THE USER "
            "about the data (headings, prose, the real numbers, chart "
            "filenames) β€” never the internal `data_worker` call syntax, "
            "never a <|tool_call> envelope, never your plan. Rewrite it as a "
            "proper Markdown report built ONLY from the findings the worker "
            "returned, then call final_answer(report_text) again."
        )
    if len(text) < MIN_FINAL_REPORT_CHARS:
        raise ValueError(
            f"Your final answer is only {len(text)} character(s) β€” too "
            f"short to be a real data-analysis report (need at least "
            f"{MIN_FINAL_REPORT_CHARS}). Write a complete Markdown report "
            "(a short introduction, clearly-headed sections covering each "
            "sub-task the data_worker ran, the actual numbers it returned, "
            "and a brief conclusion), then call final_answer(report_text) "
            "again with the FULL report text as the argument."
        )
    # Delegation evidence on the CodeAgent path lives in the EXECUTED CODE
    # (`data_worker(task='...')` inside code_action) and the observation
    # (the worker's findings), NOT in tool_calls (which is always
    # ['python_interpreter']) β€” see _step_evidence_text. A persistent flag
    # set by the manager's step callback (see _manager_step_callback)
    # records the delegation even when this validator runs before the
    # delegating step has been appended to memory (smolagents validates the
    # final answer BEFORE memory.steps.append(action_step)).
    delegated = bool(getattr(agent, "_data_worker_delegated", False))
    if not delegated:
        try:
            steps = list(getattr(memory, "steps", None) or []) \
                or list(getattr(getattr(agent, "memory", None), "steps", None) or [])
            for step in steps:
                # REAL delegation evidence lives in the step's OBSERVATION
                # (the worker's actual return), never in code_action β€” a
                # model can quote `data_worker(...)` inside a string without
                # the call ever running (the observed plan-narration
                # failure).
                if _observations_prove_delegation(_step_observations_text(step)):
                    delegated = True
                    break
        except Exception:
            # Introspection must never block a run β€” treat unreadable memory
            # as "delegated" so the min-length check alone governs.
            delegated = True
    if not delegated:
        # Same-block fallback: when the manager delegates AND final-answers in
        # ONE code block, the delegating step isn't in memory yet at
        # validation time β€” but the executor's accumulated printed output
        # already holds the worker's findings (the manager printed
        # worker_result). That text proves the worker actually ran.
        try:
            state = getattr(getattr(agent, "python_executor", None), "state", None) or {}
            printed = str(state.get("_print_outputs", "") or "")
            if _observations_prove_delegation(printed):
                delegated = True
        except Exception:
            pass
    if not delegated:
        raise ValueError(
            "Your final answer was written WITHOUT calling the `data_worker` "
            "sub-agent even once β€” every number in the report must come from "
            "a data_worker call, never from your own assumptions. Call "
            "data_worker(task='...') at least once to list the columns and "
            "compute the totals/breakdowns/charts, then call "
            "final_answer(report_text) again with the report built ONLY from "
            "those findings. Do not write the report from memory or guess."
        )
    _validate_report_grounding(text, memory, agent)
    return True


# How many distinct REAL findings numbers (β‰₯ 10) must be reproduced in the
# manager's final report before the grounding check enforces a match. Small
# datasets / qualitative questions legitimately yield fewer, so below this
# the check is skipped (no false rejections).
REPORT_GROUNDING_MIN_FINDINGS_NUMBERS = 3

# Fraction of the distinct real findings numbers the report must contain
# (rounded up), once the check is active.
REPORT_GROUNDING_MIN_FRACTION = 0.4

_NUM_TOKEN_RE = re.compile(r"\d+(?:\.\d+)?")
_DTYPE_RE = re.compile(r"(?:int|uint|float|complex)\d+")

# The grounding check must only compare the report against REAL tool-result
# numbers, never the incidental ones in the worker's column-listing head
# dump. A delegation whose task was "list the columns" returns the column
# names + first 3 rows β€” which legitimately contain invoice IDs (2026001),
# dates (2026), unit prices (899 / 18.5) and sample quantities that a
# report would never reproduce. Extracting ALL of them (as the first
# version did) made the grounding check falsely reject a valid next step,
# panicking the model into a `final_answer()` error loop (observed
# end-to-end on E4B: the check demanded 2026003/2026002/2026001/2026… and
# the run aborted after 3 consecutive errors). These markers appear on
# every real tool-result line and on NONE of the head-dump lines: aggregate
# tables are pipe-delimited (`| … | 1798 |`) with a `**Sum … = 3206**`
# bold total, summarize_numeric lines start with `count:`/`mean:`/…, and
# save_chart returns `βœ… Chart saved as: <file>.png`.
_FINDINGS_NUMBER_LINE_MARKERS = ("**Sum", "count:", "mean:", "saved as:",
                                 "βœ…", "❌", "|")


def _result_lines_only(text: str) -> str:
    """Keep only the lines of a worker-findings text that carry a real
    tool-result marker (aggregate tables / bold totals / summary stats /
    chart confirmations), dropping the incidental column-listing head dump
    (whose numbers a report would never reproduce). Empty string when no
    line qualifies β€” the grounding check then stands down (no real results
    were returned, so there is nothing to enforce)."""
    return "\n".join(
        line for line in (text or "").splitlines()
        if any(m in line for m in _FINDINGS_NUMBER_LINE_MARKERS)
    )



def _normalize_num(tok: str) -> str:
    """'22.0' β†’ '22', '3206.00' β†’ '3206', '4.4' β†’ '4.4' β€” so the report's
    formatting of a real number always matches the findings' formatting of
    the same value (aggregate returns '22', the report may write '22.0')."""
    try:
        f = float(tok)
        if f == int(f):
            return str(int(f))
        return str(f)
    except Exception:
        return tok.strip()


def _findings_numbers(memory, agent) -> set:
    """The distinct REAL numbers the worker returned, extracted from the
    findings text β€” the observations of the delegation step(s) (whose
    code_action mentions data_worker) plus the executor's accumulated
    printed output (the same-block fallback: the delegation step isn't in
    memory yet at validation time). Dtype annotations like 'int64' are
    stripped so they can't pollute the number set. Empty set on any
    introspection failure (the check is then skipped, never a blocker)."""
    parts = []
    try:
        steps = list(getattr(memory, "steps", None) or []) \
            or list(getattr(getattr(agent, "memory", None), "steps", None) or [])
        for step in steps:
            if DATA_WORKER_NAME in _step_evidence_text(step):
                obs = getattr(step, "observations", None)
                if obs:
                    parts.append(str(obs))
    except Exception:
        pass
    try:
        state = getattr(getattr(agent, "python_executor", None), "state", None) or {}
        printed = str(state.get("_print_outputs", "") or "")
        if printed:
            parts.append(printed)
    except Exception:
        pass
    text = "\n".join(parts)
    text = _DTYPE_RE.sub(" ", text)
    # Only the REAL tool-result lines count as findings numbers β€” the
    # incidental column-listing head dump (invoice IDs, dates, sample unit
    # prices) is never something a report must reproduce, and demanding it
    # falsely rejects valid steps (see _result_lines_only / the E4B false
    # rejection this fixes).
    text = _result_lines_only(text)
    # Strip thousands separators (e.g. 11,825 -> 11825) so number extraction
    # matches formatted reports.
    text = re.sub(r"(\d),(\d)", r"\1\2", text)
    return {_normalize_num(t) for t in _NUM_TOKEN_RE.findall(text)}


def _validate_report_grounding(text: str, memory, agent) -> None:
    """Grounded-numbers check on the manager's final report: the report must
    actually CONTAIN the numbers the `data_worker` returned, not numbers the
    manager invented. This is the second half of the delegation contract:
    `_validate_final_report` proves a data_worker call happened, this proves
    the report USED its findings β€” the end-to-end failure where Qwen3-4B
    delegated correctly but then wrote a report full of fabricated totals
    (1500/45000 instead of the real 22/3206) and invented seller names.

    Enforced only when the findings contain enough real numbers (β‰₯
    REPORT_GROUNDING_MIN_FINDINGS_NUMBERS distinct values β‰₯ 10) that a
    grounded report could reasonably reproduce them; a small dataset or a
    qualitative question that legitimately yields few numbers is never
    rejected. Among those real numbers the report must contain at least
    REPORT_GROUNDING_MIN_FRACTION of them β€” the fabricated report shared
    zero, the grounded E4B report shared most. Raises (feeding the rejection
    back to the model, same as the other checks) or returns None."""
    try:
        findings = _findings_numbers(memory, agent)
        big = {n for n in findings if _num_value(n) >= 10}
        if len(big) < REPORT_GROUNDING_MIN_FINDINGS_NUMBERS:
            return  # not enough real numbers to enforce grounding
        # Strip thousands separators from report text (e.g. 11,825 -> 11825)
        # so human/Khmer-formatted numbers match raw tool findings numbers.
        clean_report = re.sub(r"(\d),(\d)", r"\1\2", text)
        report_nums = {_normalize_num(t) for t in _NUM_TOKEN_RE.findall(clean_report)}
        shared = big & report_nums
        need = max(1, int(len(big) * REPORT_GROUNDING_MIN_FRACTION))
        if len(shared) >= need:
            return
        shown = ", ".join(sorted(big, key=_num_value, reverse=True)[:6])
        raise ValueError(
            f"Your final report does not contain the real numbers the "
            f"`data_worker` returned. The findings include numbers like "
            f"{shown}, but your report used different (invented) values. "
            "REWRITE the report so every total, breakdown and statistic is "
            "copied EXACTLY from the data_worker findings in your context β€” "
            "never invent, round, or estimate numbers yourself, and never "
            "make up product or seller names."
        )
    except ValueError:
        raise
    except Exception:
        return  # introspection must never block a run


def _num_value(n: str) -> float:
    try:
        return float(n)
    except Exception:
        return 0.0


def _trim_manager_memory_mid_run(agent) -> None:
    """Drop the OLDEST steps of the manager's memory when the accumulated
    memory (system prompt + task + every step with its worker observations)
    would push the next prompt past the context window β€” the mid-run safety
    net.

    Between-turn compaction (agent_memory.compact_agent_memory) runs BEFORE
    each run; a single run that delegates many times can still overflow
    DURING the run (the end-to-end "Requested tokens (N) exceed context
    window of 16384" crash on a 4+ delegation EDA). Keeps the task step and
    the most recent steps (the latest worker findings the manager still
    needs to write the report), dropping only the old middle. Never raises.
    """
    try:
        from agents import agent_memory

        model_obj = getattr(agent, "model", None)
        if not agent_memory.is_local_backed_model(model_obj):
            return
        n_ctx = agent_memory._effective_n_ctx(
            model_obj, models._llm_n_ctx or mr.get_saved_context_window()
        )
        budget = int(n_ctx * agent_memory.COMPACTION_BUDGET_RATIO) - mr.get_saved_max_new_tokens()
        if budget <= 0:
            return
        tokenizer = agent_memory._get_model_tokenizer(model_obj)
        if agent_memory.estimate_text_tokens(
                agent_memory._memory_to_text(agent, truncate=False), tokenizer) <= budget:
            return
        steps = list(getattr(agent.memory, "steps", []) or [])
        if not steps:
            return
        from smolagents.memory import TaskStep

        task_indices = [i for i, s in enumerate(steps) if isinstance(s, TaskStep)]
        # Keep the task step (the user's question + file list β€” the manager
        # must never lose what it was asked), the most recent 3 steps, AND
        # every DELEGATION step (the step whose tool_calls include
        # `data_worker`) β€” its observation carries the worker's REAL
        # findings, and the final report is built ONLY from those numbers.
        # The observed E2B failure: a trim dropping an older delegation left
        # the manager with no real numbers to transcribe, so it wrote an
        # f-string TEMPLATE report with {total_quantity} placeholders.
        keep = [steps[task_indices[0]]] if task_indices else []
        keep.extend(steps[-3:])
        for s in steps:
            calls = getattr(s, "tool_calls", None) or []
            if any(getattr(tc, "name", "") == "data_worker" for tc in calls):
                keep.append(s)
        seen, dedup = set(), []
        for s in keep:
            if id(s) not in seen:
                seen.add(id(s))
                dedup.append(s)
        if len(dedup) < len(steps):
            agent.memory.steps = dedup
            print(f"[DataAgent] Mid-run memory trim: {len(steps)} -> "
                  f"{len(dedup)} steps (budget {budget} tokens)")
    except Exception:
        pass


def _worker_loop_guard_callback(step, agent=None):
    """smolagents step callback registered on the `data_worker`'s ActionSteps:
    the app's repetition-loop guard applied to the WORKER's INTERNAL run.

    The top-level loop guard lives in agent_streaming.stream_agent_steps,
    which wraps the MANAGER's stream β€” but the worker runs inside smolagents'
    own managed-agent machinery (ManagedAgent.__call__ β†’ worker.run()), which
    bypasses that wrapper entirely. Without this callback, a worker stuck
    repeating the SAME call over and over (observed end-to-end on
    Qwen3-4B-Q8_0: ten identical `list_columns` re-runs, then a prose
    surrender) burns its whole step budget one slow generation at a time,
    returning no findings at all. This callback detects the repeated
    tool-call signature (reusing the exact same equality key + threshold as
    the top-level guard) and, on the threshold, injects the same corrective
    nudge into the worker's memory β€” the fresh context breaks the
    deterministic re-generation, the standard cure. Never raises."""
    if agent is None:
        return
    try:
        sig = agent_streaming._tool_calls_signature(step)
        if sig is None:
            # No readable tool call β€” both loop channels stand down.
            agent._worker_prev_sig = None
            agent._worker_repeat = 0
            return
        if sig == getattr(agent, "_worker_prev_sig", None):
            agent._worker_repeat = getattr(agent, "_worker_repeat", 0) + 1
        else:
            agent._worker_prev_sig = sig
            agent._worker_repeat = 1
        if getattr(agent, "_worker_repeat", 0) >= agent_streaming._LOOP_NUDGE_THRESHOLD:
            if not getattr(agent, "_worker_nudged", False):
                agent._worker_nudged = True
                # The nudge text is bilingual in i18n; the worker's internal
                # nudge is not user-visible (no stream bubble), but the model
                # reads it, so keep it in the UI language like everywhere else.
                agent_streaming._inject_loop_nudge(agent, "en")
    except Exception:
        pass


def _manager_step_callback(step, agent=None):
    """smolagents step callback (registered on the manager's ActionSteps).

    Two jobs, both running AFTER the step completes (smolagents calls it in
    `_finalize_step`, before the step is appended to memory):

      1. Record delegation evidence on the agent object. A CodeAgent step's
         `tool_calls` is always ['python_interpreter'], so the ONLY place a
         REAL delegation shows up is the step's OBSERVATION β€” the worker's
         returned findings ("Here is the final answer from your managed
         agent…" + the verbatim tool outputs). The executed code
         (code_action) is NOT evidence: the observed end-to-end failure had
         the manager emit a Gemma-native `<|tool_call>` envelope INSIDE a
         final_answer(…) string literal β€” the text `data_worker(task=…)`
         appeared in the code without the call ever running. Requiring the
         worker's actual return (managed-agent marker or findings markers)
         in the observation keeps the flag honest. Setting a persistent
         flag here β€” rather than introspecting memory in the validator β€”
         also survives the mid-run memory trim below, which drops old
         steps whose observations held the evidence.
      2. Trim the manager's memory when it would overflow the context
         window (see _trim_manager_memory_mid_run).

    Signature matches smolagents' callback convention (memory_step, agent).
    Never raises."""
    if agent is None:
        return
    try:
        if not getattr(agent, "_data_worker_delegated", False) \
                and _observations_prove_delegation(_step_observations_text(step)):
            agent._data_worker_delegated = True
    except Exception:
        pass
    _trim_manager_memory_mid_run(agent)


def _step_observations_text(step) -> str:
    """The OBSERVATION text of a step only (never code_action) β€” the place a
    REAL managed-agent delegation shows up: smolagents wraps the worker's
    return in "Here is the final answer from your managed agent '…':" plus
    the verbatim tool outputs. Code text mentioning `data_worker(` is NOT
    proof (a model can quote the call inside a string without ever
    executing it β€” the observed plan-narration failure)."""
    try:
        v = getattr(step, "observations", None)
        if v is None and isinstance(step, dict):
            v = step.get("observations")
        return str(v or "")
    except Exception:
        return ""


# The max-steps hand-off transcript cap β€” a 10-step worker's full tool
# transcript (columns + every aggregate table) stays well under this; the
# cap only guards a pathological run from flooding the manager's context.
_WORKER_OBS_TRANSCRIPT_CAP = 8000


def _collect_worker_observations(worker) -> str:
    """The `data_worker`'s run transcript β€” the verbatim tool outputs it
    COMPUTED but never delivered via final_answer. Thin wrapper over the
    shared agent_streaming.collect_agent_observations (same helper the
    Deep Research search agent uses), with the worker-specific cap. See
    agent_streaming for the full rationale: a max-steps worker's REAL
    findings live in its ActionStep observations, exactly the verbatim
    tool outputs its final_answer contract would have carried."""
    return agent_streaming.collect_agent_observations(
        worker, cap=_WORKER_OBS_TRANSCRIPT_CAP)


def _worker_max_steps_handoff(self, task):
    """The `data_worker`'s max-steps fallback (instance-patched onto the
    worker in `_build_data_worker`): prefer the run's REAL findings β€” the
    verbatim tool observations β€” over smolagents' stock last-ditch
    raw-text answer, so the manager receives the computed numbers instead
    of a leaked code fence. Thin wrapper over the shared
    agent_streaming.max_steps_findings_handoff. NEVER raises."""
    return agent_streaming.max_steps_findings_handoff(
        self, task, cap=_WORKER_OBS_TRANSCRIPT_CAP)


# smolagents wraps every managed-agent return in this marker (the
# `managed_agent.report` prompt template) β€” its presence in an observation
# proves the worker ACTUALLY ran and returned.
_MANAGED_AGENT_RETURN_MARKER = "Here is the final answer from your managed agent"

# Delegation-proof findings markers. NOTE: deliberately EXCLUDES the bare
# `"|"` pipe from _WORKER_FINDINGS_MARKERS β€” the Gemma-native
# `<|tool_call>` envelope the model leaks when it narrates a plan contains
# pipes, so `|` alone would falsely prove a delegation that never ran.
_DELEGATION_PROOF_MARKERS = ("**Sum", "count:", "mean:", "saved as:",
                             "βœ…", "❌")


def _observations_prove_delegation(text: str) -> bool:
    """True when an observation text carries the worker's REAL return: the
    smolagents managed-agent wrapper marker (any return β€” even an error
    message) OR the strong findings markers (a return that actually ran the
    data tools)."""
    return _MANAGED_AGENT_RETURN_MARKER in text or any(m in text for m in _DELEGATION_PROOF_MARKERS)


def _build_worker_agent(llm, model_id: str = "", files: Optional[list] = None,
                        max_steps: Optional[int] = None,
                        execution_timeout: Optional[int] = None):
    """Build the `data_worker` sub-agent: a plain CodeAgent holding ONLY
    the curated data tools, with the data file paths bound into its system
    instructions at build time. Registered as a managed_agents entry on the
    manager, so smolagents exposes it to the manager as a callable tool."""
    if max_steps is None:
        max_steps = mr.get_max_steps_for_model(model_id, DATA_WORKER_DEFAULT_MAX_STEPS)
    # AUTO (None) on the Data tab means the tab's own default, NOT
    # smolagents' 30s β€” heavy EDA steps routinely exceed 30s (see
    # DATA_EXECUTION_TIMEOUT_DEFAULT).
    if execution_timeout is None:
        execution_timeout = DATA_EXECUTION_TIMEOUT_DEFAULT

    files_block = ""
    if files:
        files_block = DATA_WORKER_FILES_HEADER + "\n".join(f"- {p}" for p in files) + "\n\n"
    instructions = DATA_WORKER_INSTRUCTIONS.format(files_block=files_block)

    worker = build_smol_agent(
        llm,
        tools=[install_package, list_columns, aggregate, summarize_numeric,
               save_chart, complete_missing_data],
        max_steps=max_steps,
        execution_timeout=execution_timeout,
        # The worker ALWAYS runs a plain CodeAgent (Python execution is its
        # whole point) β€” ToolCallingAgent has no Python executor, so it
        # could never run pandas/matplotlib code. The factory's default is
        # now use_tool_calling=True (tool calling is the app-wide default),
        # so this sub-agent must explicitly opt OUT or it would silently
        # become a ToolCallingAgent. additional_authorized_imports=["*"] =
        # trusted local machine β€” full stdlib + installed packages. The
        # markdown-fence code_block_tags / executor_kwargs version guards
        # live in the shared factory (agents/agent_factory.py).
        use_tool_calling=False,
        instructions=instructions,
        extra_kwargs={
            "name": DATA_WORKER_NAME,
            "description": DATA_WORKER_DESCRIPTION,
            # The worker's final_answer IS the findings β€” a run-summary
            # blob of its whole transcript would only bloat the manager's
            # observation (and bury the numbers under noise for a small
            # model). Keep the observation = the verbatim tool outputs only.
            "provide_run_summary": False,
            "additional_authorized_imports": ["*"],
        },
        # The transcription guard: a final answer with no real tool output
        # (narration with invented numbers) is rejected and sent back. The
        # repetition-loop guard runs after every worker step (see
        # _worker_loop_guard_callback) β€” the top-level guard in
        # stream_agent_steps cannot see the worker's internal run.
        optional_kwargs={
            "final_answer_checks": [_validate_worker_findings],
            "step_callbacks": [_worker_loop_guard_callback],
        },
    )
    # Override smolagents' default managed-agent task template (the 3-part
    # "Task outcome…" narrative demand that invites invented numbers) with
    # the verbatim-transcription contract. Version-guarded: an older
    # smolagents without the prompt_templates dict keeps the stock template
    # (the instructions + validator still carry the contract).
    try:
        m_task = worker.prompt_templates["managed_agent"]
        if isinstance(m_task, dict):
            # Newer smolagents stores the template dict ({'task': ..., 'report': ...}).
            if "task" in m_task:
                m_task["task"] = DATA_WORKER_MANAGED_TASK_TEMPLATE
        elif hasattr(m_task, "task"):
            # Older dataclass shape (ManagedAgentPromptTemplate.task).
            m_task.task = DATA_WORKER_MANAGED_TASK_TEMPLATE
    except Exception:
        pass
    # Max-steps hand-off (see _worker_max_steps_handoff): when the worker
    # burns its whole step budget without ever calling final_answer (the
    # Muse Glimmer Data failure β€” it computed the totals, then surrendered
    # with a leaked code fence), the manager would receive that garbage.
    # Deliver the run's verbatim tool observations instead β€” the exact
    # content the worker's final_answer contract would have carried.
    # Instance-level patch, data_worker ONLY: the Data MANAGER is a
    # CodeAgent too, but its observations are "Here is the final answer
    # from your managed agent…" wrappers, not a report, so it keeps the
    # stock behavior.
    try:
        worker._orig_handle_max_steps_reached = worker._handle_max_steps_reached
        worker._handle_max_steps_reached = types.MethodType(
            _worker_max_steps_handoff, worker
        )
    except Exception:
        pass
    print(f"[DataAgent] Building {type(worker).__name__} sub-agent "
          f"'{DATA_WORKER_NAME}' on '{model_id or '(shared)'}' …")
    return worker


def _build_manager_agent(llm, worker, model_id: str = "",
                         max_steps: Optional[int] = None,
                         execution_timeout: Optional[int] = None):
    """Build the manager agent. It holds NO data tools of its own β€” only
    the managed `data_worker` sub-agent (plus smolagents' auto-added
    final_answer tool). Its whole job is to analyze the user's data
    question, split it into focused sub-tasks, delegate them, and
    synthesize the grounded Markdown report.

    The manager is a CodeAgent (use_tool_calling=False), not a
    ToolCallingAgent like the RAG / Deep Research managers. Reason: the
    Data tab's verified models are small quantized GGUFs whose reliable
    path in this app is the forgiving CODE grammar β€” the smart parser
    (agent_streaming._patch_smolagents_code_parser) executes even
    prose-wrapped output, rewrites Qwen/Gemma native `<|tool_call|>`
    envelopes into real calls, and the executor environment includes the
    managed agents, so `data_worker(task='...')` works as a plain Python
    expression. A ToolCallingAgent manager repeatedly failed end-to-end on
    Qwen3-4B-Q8_0 by "answering the prompt" with plan narration instead
    of emitting structured calls; the code path plus the delegation
    validator below is the reliable combination."""
    if max_steps is None:
        max_steps = mr.get_max_steps_for_model(model_id, mr.DATA_AGENT_MAX_STEPS)
    # Same AUTO default as the worker (see DATA_EXECUTION_TIMEOUT_DEFAULT).
    if execution_timeout is None:
        execution_timeout = DATA_EXECUTION_TIMEOUT_DEFAULT

    manager = build_smol_agent(
        llm,
        tools=[],
        max_steps=max_steps,
        execution_timeout=execution_timeout,
        # The manager delegates via `data_worker(task='...')` Python
        # expressions (see DATA_MANAGER_INSTRUCTIONS) β€” it never runs
        # data tools itself, but the code grammar is the reliable one for
        # this tab's small models (see the docstring above).
        use_tool_calling=False,
        instructions=DATA_MANAGER_INSTRUCTIONS,
        # Deep-research strategy: re-plan every few steps instead of
        # blindly executing the initial delegation plan. final_answer_checks
        # is attached only when this smolagents version's __init__ accepts
        # it (optional_kwargs guard).
        extra_kwargs={
            "managed_agents": [worker],
            # Per-model override: models flagged planning-incompatible
            # (Muse Glimmer β€” it echo-loops the re-plan prompt) get None
            # (planning off), everyone else keeps the default interval.
            "planning_interval": mr.planning_interval_for_model(model_id, DATA_MANAGER_PLANNING_INTERVAL),
        },
        # The delegation flag + mid-run memory trim run after every manager
        # step (see _manager_step_callback) β€” CodeAgent delegation evidence
        # lives in code_action/observations, not tool_calls, so the flag is
        # the validator's source of truth. Version-guarded through
        # optional_kwargs: an older smolagents without step_callbacks skips
        # it (the validator's memory-scan fallback still works).
        optional_kwargs={
            "final_answer_checks": [_validate_final_report],
            "step_callbacks": [_manager_step_callback],
        },
    )
    print(f"[DataAgent] Building {type(manager).__name__} manager on "
          f"'{model_id or '(shared)'}' …")
    return manager


def get_data_agent(model_id: Optional[str] = None,
                   max_steps: Optional[int] = None,
                   worker_max_steps: Optional[int] = None,
                   execution_timeout: Optional[int] = None,
                   provider: Optional[str] = None,
                   n_ctx: Optional[int] = None,
                   files: Optional[list] = None):
    """Lazily build (or rebuild, if the model or the uploaded file set
    changed) the manager + `data_worker` sub-agent pair.

    `max_steps` is the MANAGER's step budget and `worker_max_steps` the
    `data_worker` sub-agent's β€” the UI's per-tab "Max Steps" / "Sub-agent
    steps" controls. Both None = AUTO (the model-scaled defaults:
    DATA_AGENT_MAX_STEPS / DATA_WORKER_DEFAULT_MAX_STEPS).

    `files` (the staged upload paths) is part of the cache key because the
    worker's system instructions carry the data file paths β€” a new/changed
    dataset must rebuild the pair so the worker reads the right files
    (mirrors RAG's `sources` cache key). Rebuilding is cheap: the LLM is
    shared/cached via models.get_llm().
    """
    global _data_agent, _data_worker, _data_agent_model_id
    global _data_agent_max_steps, _data_agent_worker_max_steps
    global _data_agent_execution_timeout, _data_agent_n_ctx
    global _data_agent_files
    target = model_id or models._llm_model_id
    files_key = tuple(sorted(str(p) for p in (files or [])))

    if (_data_agent is not None
            and target == _data_agent_model_id
            and max_steps == _data_agent_max_steps
            and worker_max_steps == _data_agent_worker_max_steps
            and execution_timeout == _data_agent_execution_timeout
            and n_ctx == _data_agent_n_ctx
            and files_key == _data_agent_files):
        return _data_agent

    with _data_agent_lock:
        if (_data_agent is not None
                and target == _data_agent_model_id
                and max_steps == _data_agent_max_steps
                and worker_max_steps == _data_agent_worker_max_steps
                and execution_timeout == _data_agent_execution_timeout
                and n_ctx == _data_agent_n_ctx
                and files_key == _data_agent_files):
            return _data_agent

        print(f"[DataAgent] Building manager + {DATA_WORKER_NAME} on '{target}' …")
        llm = models.get_llm(target, provider=provider, n_ctx=n_ctx)
        worker = _build_worker_agent(llm, target, files_key, worker_max_steps, execution_timeout)
        _data_worker = worker
        _data_agent = _build_manager_agent(llm, worker, target, max_steps, execution_timeout)
        _data_agent_model_id = target
        _data_agent_max_steps = max_steps
        _data_agent_worker_max_steps = worker_max_steps
        _data_agent_execution_timeout = execution_timeout
        _data_agent_n_ctx = n_ctx
        _data_agent_files = files_key
        # Standard smolagents behaviour: a freshly-built agent starts
        # with empty memory. This only happens on first use, or after a
        # model/dataset switch or reset via reset_agent() below β€”
        # dataset changes are ALSO handled by reset_if_context_changed()
        # in run_data_analysis(), which clears an EXISTING manager's
        # memory in place rather than rebuilding it (see
        # agent_memory.py's module docstring for why rebuilding-to-reset
        # used to reintroduce the very stale memory it was meant to drop).
        return _data_agent


def reset_agent():
    """Drop the manager + worker pair. It references the shared LLM managed
    by models.get_llm(), whose memory is released there when the underlying
    model actually changes. Rebuilding is cheap since it reuses get_llm(target).

    Also called whenever the LLM is reloaded/unloaded elsewhere (the agents
    hold their own reference to that same model and would otherwise keep an
    unloaded model alive).
    """
    global _data_agent, _data_worker, _data_agent_model_id
    global _data_agent_max_steps, _data_agent_worker_max_steps
    global _data_agent_execution_timeout, _data_agent_n_ctx
    global _data_agent_files
    _data_agent = None
    _data_worker = None
    _data_agent_model_id = None
    _data_agent_max_steps = None
    _data_agent_worker_max_steps = None
    _data_agent_execution_timeout = None
    _data_agent_n_ctx = None
    _data_agent_files = ()


def save_data_files(files) -> list:
    """Copy uploaded CSV/XLSX files into the persistent data-analysis workspace."""
    Path(mr.DATA_UPLOAD_DIR).mkdir(parents=True, exist_ok=True)
    paths = []
    if not files:
        return paths
    if not isinstance(files, list):
        files = [files]
    for f in files:
        src = get_file_path(f)
        if not src:
            continue
        dest = Path(mr.DATA_UPLOAD_DIR) / Path(src).name
        try:
            shutil.copy(src, dest)
            paths.append(str(dest))
        except Exception:
            pass
    return paths


def build_data_task(question: str, file_list_str: str, lang_key: str = "kh") -> str:
    """Build the Data Analysis MANAGER's task prompt.

    Prepends the UI-language output directive (i18n._output_lang_instruction)
    so a Khmer UI gets Khmer answers and an English UI gets English ones β€”
    the same shared contract as every other chat/agent tab. The directive
    is at the very START of the prompt, before any other instruction, so
    small models see it first.

    The manager does not touch the data itself β€” it decomposes the user's
    request into focused sub-tasks and delegates each to the `data_worker`
    sub-agent (whose own instructions carry the exact-column-name rule and
    the tool usage). This task tells the manager how to orchestrate, what
    the worker can do, and that the final report must be built ONLY from
    the worker's findings.

    The user's request is placed as the LAST line of the task (the task
    text is the user turn the manager model sees), so a small GGUF model
    anchors on the request rather than the instruction block β€” the same
    question-last hardening as the other agentic task builders.
    """
    return f"""{i18n._output_lang_instruction(lang_key)}You are a data analysis assistant and research manager.
Data file(s) provided by the user:
{file_list_str}

You do NOT run Python or touch the data yourself β€” the ONLY agent that
exists is `data_worker`, a focused worker holding the list_columns,
aggregate, summarize_numeric, save_chart, complete_missing_data and
install_package tools. Call it
from your code block as a plain Python expression and print the result:
worker_result = data_worker(task='...')
print(worker_result)
The printed value is the worker's findings β€” read it and copy its real
numbers into your report. It has NO memory of other calls, so each task
must name the data file(s) and the EXACT column names to use.

BUNDLE related computations into as FEW data_worker calls as possible:
each call is a fresh, expensive worker run, so ONE task can ask the worker
to list the columns, compute all totals, do all breakdowns AND create all
the charts together. Do not split related work into many calls.

β˜… COLUMN NAMES β€” ALWAYS USE THE EXACT NAMES FROM THE DATA
   - Column names are EXACTLY as they appear in the file and may be in Khmer
     or any other language (e.g. 'αž”αžšαž·αž˜αžΆαžŽ', 'αžαž˜αŸ’αž›αŸƒ/αž―αž€αžαžΆ (USD)', 'αžŸαžšαž»αž” (USD)',
     'αž€αžΆαž›αž”αžšαž·αž…αŸ’αž†αŸαž‘'). NEVER translate, rename, guess, or invent column names β€”
     and never assume English equivalents like 'Quantity', 'Unit Price',
     'Date', or 'Product'.
   - Instruct `data_worker` to print df.columns.tolist() after loading and
     copy the names VERBATIM; on a KeyError it must re-print
     df.columns.tolist(), take the real name, and retry.

Write a well-structured Markdown report built ONLY from the worker's
findings β€” include the ACTUAL numbers it returned (totals, breakdowns,
statistics) verbatim, reference each chart by its exact PNG filename, and
never invent or estimate values. For a default EDA, structure it as a
Dataset Overview, Statistical Summary, and an Analysis Report with Key
Metrics and Trends. If the request involves payroll/salary data, delegate
computing gross pay, deductions, tax and net pay and report those totals. If
the data has BLANK (missing/empty) cells or columns β€” e.g. αž€αžΆαžαŸ‹αž–αž“αŸ’αž’ / tax
and αž”αŸ’αžšαžΆαž€αŸ‹αžαŸ‚αžŸαž»αž‘αŸ’αž’ (USD) / net salary left empty, or a few missing values
scattered anywhere β€” delegate completing them via complete_missing_data,
which works on ANY dataset: it auto-derives relations from the column
names (payroll identities; generic totals like quantity Γ— unit price,
validated against known rows), accepts explicit
rules={{'<column>': '<formula>'}} when the user states one (e.g. a 10% tax
rate), and statistically estimates partially-blank columns (mean / most
common value, clearly labeled). It never invents numbers, so if a blank
column has no rule, no derivable relation and no observed values, report
that it stayed blank.

As your FINAL ANSWER, return the full Markdown report or the direct answer
to the user's request below. REMEMBER: you MUST call `data_worker` at least
once before final_answer β€” a final answer with no data_worker call is
rejected and sent back to you.

---
The user's request to fulfil:
{question}"""


def _pretty_chart_name(name: str) -> str:
    """The display caption for a chart card: the filename stem with
    underscores turned into spaces ('Sales_Trend.png' β†’ 'Sales Trend')."""
    stem = Path(str(name)).stem
    return stem.replace("_", " ").strip() or str(name)


def _chart_gallery_html(chart_files, lang_key: str = "kh") -> str:
    """The chart gallery block appended under a data-analysis run's final
    answer bubble. It shows EVERY chart the run produced β€” the model's
    report markdown may reference some or none of them (small models often
    write Windows paths or prose instead of `![alt](file.png)` refs), so the
    gallery always displays the real set. Images are served by the backend's
    /api/data/chart/<name> endpoint (percent-encoded, so Khmer/space
    filenames survive). Only basenames are ever used β€” a stray path in the
    list cannot leak an arbitrary file into the bubble, and the caption /
    alt text are HTML-escaped. Returns '' when there are no charts. NEVER
    raises."""
    try:
        from urllib.parse import quote

        names = []
        for p in chart_files or []:
            name = Path(str(p)).name
            if name and name.lower().endswith(".png") and name not in names:
                names.append(name)
        if not names:
            return ""
        title = ("πŸ“Š αž€αŸ’αžšαžΆαž αŸ’αžœαž·αž€αžŠαŸ‚αž›αž”αžΆαž“αž”αž„αŸ’αž€αžΎαž" if lang_key == "kh"
                 else "πŸ“Š Generated charts")
        cards = "\n".join(
            f'<figure class="chart-card">'
            f'<img src="/api/data/chart/{quote(name)}" '
            f'alt="{html.escape(name, quote=True)}" loading="lazy"/>'
            f'<figcaption>{html.escape(_pretty_chart_name(name), quote=True)}</figcaption>'
            f"</figure>"
            for name in names
        )
        return (
            f'\n\n<div class="chart-gallery">'
            f'<div class="chart-gallery-title">{title}</div>'
            f'<div class="chart-grid">\n{cards}\n</div>'
            f"</div>"
        )
    except Exception:
        return ""


def run_data_analysis(files, question: str, model_label: str, history: list,
                       use_memory: bool = True, lang_key: str = "kh",
                       max_steps: Optional[int] = None,
                       worker_max_steps: Optional[int] = None,
                       execution_timeout: Optional[int] = None,
                       n_ctx: Optional[int] = None):
    """Hand uploaded data + the user's question to the data manager and collect its report.

    `use_memory` controls the "🧠 Conversation Memory" checkbox: when on,
    the manager remembers earlier turns about the SAME dataset (capped β€”
    see DATA_AGENT_MEMORY_TURNS) and old memory is dropped automatically
    if a different file is uploaded. When off, every question is answered
    from a clean slate regardless of what file is uploaded.

    A GENERATOR: yields (history, gallery_update, report_update) once per
    live agent step as the analysis runs (see agent_streaming.py), using
    None no-op placeholders for the gallery outputs during those
    intermediate yields so charts don't flicker to "empty" mid-run β€” then
    one final time with the real chart list (the report slot stays None:
    the report markdown lives in the final answer bubble and is exported
    to .docx on demand via the UI's πŸ’Ύ Save Report button, never
    auto-saved). This is easily the longest-running single call in the
    app (a full EDA β€” load, chart, correlate, write a report), so live
    progress matters here more than almost anywhere else.
    """
    history = history or []

    paths = save_data_files(files)
    if not paths:
        history.append({"role": "user", "content": question or "(no file)"})
        history.append({"role": "assistant", "content": "⚠️ Please upload a CSV or XLSX file first."})
        yield history, None, None
        return

    question = (question or "").strip() or (
        "Perform a full exploratory data analysis (EDA) on this dataset and "
        "generate a thorough Markdown report with multiple charts."
    )
    provider = mr.get_saved_provider("data")
    model_id = mr.resolve_model_id(model_label, provider=provider)
    n_ctx = n_ctx if n_ctx is not None else mr.get_saved_context_window("data")
    history.append({"role": "user", "content": f"πŸ“Ž {', '.join(Path(p).name for p in paths)}\n\n{question}"})

    try:
        stamp = datetime.datetime.now().strftime("report-%Y-%m-%d-%H%M%S")
        report_base = Path(mr.REPORT_DIRS["data"])
        report_dir = report_base / stamp
        report_dir.mkdir(parents=True, exist_ok=True)
        set_active_report_dir(report_dir)

        out_dir = Path(mr.DATA_OUTPUT_DIR)
        out_dir.mkdir(parents=True, exist_ok=True)

        # Snapshot pre-existing .png files in cwd to detect newly created charts
        t0_cwd_pngs = {p.resolve() for p in Path.cwd().glob("*.png")}

        # Now that a run can produce many charts (full EDA, not just one),
        # clear out PNGs left over from a previous analysis first β€” otherwise
        # they'd pile up and get mixed into this run's gallery below.
        for stale_png in out_dir.glob("*.png"):
            try:
                stale_png.unlink()
            except OSError:
                pass
        # The pair is rebuilt automatically when the model OR the uploaded
        # file set changes (the worker's instructions carry the file paths).
        agent = get_data_agent(model_id, max_steps=max_steps, worker_max_steps=worker_max_steps, execution_timeout=execution_timeout, provider=provider, n_ctx=n_ctx, files=paths)
        # The agent object is CACHED across turns, so the delegation flag
        # from a previous turn's run must not leak into this one (a stale
        # True would let a no-delegation answer pass the validator). The
        # step callback re-sets it during THIS run's delegation steps.
        # Same for the leaked-envelope rescue state: a stale rescued
        # findings blob must not be replayed into a new turn's rejection
        # message (and a stale `_data_worker_delegated` must not skip the
        # rescue entirely).
        try:
            agent._data_worker_delegated = False
            agent._data_worker_rescued_findings = None
        except Exception:
            pass
        # New/changed dataset β†’ old manager memory (referencing whatever the
        # previous file's columns/stats were) is no longer relevant, so
        # drop it even though the model itself hasn't changed. Only
        # relevant when memory is on β€” when it's off, reset=True below
        # already makes every run stateless regardless of dataset.
        # Clears agent.memory.steps directly on the SAME agent object β€”
        # see agent_memory.reset_if_context_changed()/reset_memory()'s
        # docstrings for why this (rather than tearing down and rebuilding
        # the agent, as an earlier version of this file did) is required
        # for the reset to actually stick.
        if use_memory:
            agent_memory.reset_if_context_changed(agent, _last_data_context, tuple(sorted(paths)))
        file_list_str = "\n".join(f"- {p}" for p in paths)

        task = build_data_task(question, file_list_str, lang_key)

        # See chat.py's chat_general_direct() matching comment β€” a no-op
        # unless the "🧠 Enable Model Reasoning" toggle (βš™οΈ Model Settings)
        # is off. Data Analysis's task prompt is already long, so a heavy
        # thinking-tuned model has even less MAX_NEW_TOKENS headroom left
        # for its actual code β€” this is one of the tabs most likely to
        # benefit from turning reasoning off.
        task = mr.apply_reasoning_toggle(task)
        t0 = time.time()
        # reset=False keeps this manager's memory across turns on the
        # SAME dataset (e.g. "now also break that down by region" after an
        # initial EDA) β€” see
        # https://huggingface.co/docs/smolagents/tutorials/memory. Capped
        # right after via agent_memory.cap_agent_memory(), and fully reset
        # above whenever the uploaded file(s) change. reset=True (memory
        # checkbox off) makes every question stateless instead.
        # Live step streaming β€” see agent_streaming.stream_agent_steps()'s
        # docstring / chat.py's matching usage in the other agentic tabs.
        # Token-budget-aware memory compaction (see agent_memory.py): before
        # this run, if the accumulated memory would push the next prompt past
        # the context window, condense the older turns into a rolling summary
        # instead of just dropping them β€” the fixed turn-cap below stays as
        # the post-run safety net. Dataset changes reset memory (and the
        # rolling summary) upstream via reset_if_context_changed().
        if use_memory and agent_memory.compact_agent_memory(
                agent, model_id=model_id,
                n_ctx=models._llm_n_ctx or mr.get_saved_context_window(),
                keep_recent_turns=mr.get_saved_memory_keep_recent("data"),
                budget_ratio=mr.get_saved_memory_compaction_ratio(),
                lang_key=lang_key):
            comp_msg = ("🧹 αž€αŸ†αž–αž»αž„αž”αž„αŸ’αžšαž½αž˜αž’αž„αŸ’αž‚αž…αž„αž…αžΆαŸ†αžŸαž“αŸ’αž‘αž“αžΆβ€¦" if lang_key == "kh"
                        else "🧹 Compacting conversation memory…")
            history.append({"role": "assistant", "content": comp_msg})
            yield history, None, None
            history.pop()
        result = None
        diag = None  # snapshot from the stream's final yield β€” the abort badge below reads it (every stream path ends with one)
        for step_msg, is_final, final_output, diag in agent_streaming.stream_agent_steps(agent, task, reset=not use_memory, lang_key=lang_key):
            if not is_final:
                if step_msg is not None:
                    history.append(step_msg)
                    yield history, None, None
                continue
            result = final_output
        if use_memory:
            agent_memory.cap_agent_memory(agent, max_turns=DATA_AGENT_MEMORY_TURNS)
        elapsed = time.time() - t0

        report_text = str(result)
        # Surface compaction activity in the footer (see agent_memory.py).
        compacted_n = getattr(agent, "_compaction_count", 0) or 0
        memory_txt = "on" if use_memory else "off"
        if use_memory and compacted_n:
            memory_txt = f"on (compacted {compacted_n}Γ—)"
        # The effective step budget the agent ACTUALLY ran with (the
        # DATA_AGENT_MAX_STEPS default when the Max Steps control is on
        # auto) β€” same 'what actually ran' footer segment as the chat tabs
        # (see agent_streaming._agent_steps_budget_txt). The managed
        # `data_worker` sub-agent's budget is included too. Kept in this
        # tab's existing '|'-separated style (vs the chat tabs' 'Β·').
        steps_txt = agent_streaming._agent_steps_budget_txt(agent)
        steps_seg = f" | {steps_txt}" if steps_txt else ""
        # The effective per-step execution timeout too β€” the manager itself
        # is a ToolCallingAgent (no Python executor), so the shared helper
        # finds the timeout on the managed `data_worker` CodeAgent (whose
        # executor the timeout actually caps). Same 'what actually ran'
        # semantics: the value the factory applied, or smolagents' own 30s
        # default when the Exec timeout control is on auto.
        exec_txt = agent_streaming._agent_exec_timeout_txt(agent)
        exec_seg = f" | {exec_txt}" if exec_txt else ""

        # Collect any .png files created in cwd (e.g. if the worker called plt.savefig('salary_by_department.png'))
        for p in Path.cwd().glob("*.png"):
            if p.resolve() not in t0_cwd_pngs:
                try:
                    dst = report_dir / p.name
                    if not dst.exists():
                        shutil.move(str(p), str(dst))
                    else:
                        p.unlink(missing_ok=True)
                except OSError:
                    pass

        # Sync all PNGs between out_dir and report_dir
        for p in out_dir.glob("*.png"):
            try:
                dst = report_dir / p.name
                if not dst.exists():
                    shutil.copy2(str(p), str(dst))
            except OSError:
                pass
        for p in report_dir.glob("*.png"):
            try:
                dst = out_dir / p.name
                if not dst.exists():
                    shutil.copy2(str(p), str(dst))
            except OSError:
                pass

        chart_files = sorted(str(p) for p in report_dir.glob("*.png"))
        # The chart gallery rides AFTER the <hr> footer so the .docx export
        # (chat.chat_data splits on the first <hr>) stays clean markdown β€”
        # the gallery is bubble-only, never part of the saved report.
        response = agent_streaming.sanitize_surrogates(
            report_text +
            agent_streaming._agent_abort_html(lang_key, diag) +
            f"\n\n<hr><sub>⏱ {elapsed:.1f}s | model: <code>{model_id}</code> "
            f"({DEVICE.upper()}){steps_seg}{exec_seg} | memory: {memory_txt}</sub>" +
            _chart_gallery_html(chart_files, lang_key)
        )
        history.append({"role": "assistant", "content": response})

        # No report file is ever auto-saved β€” the report markdown lives in the
        # final answer bubble (the export-text source); the user's πŸ’Ύ Save
        # Report button converts it on demand into a .docx under
        # user_data/reports/data_analysis/.
        yield history, (chart_files or None), None
        return

    except Exception as e:
        import traceback
        history.append({"role": "assistant", "content": f"❌ {e}\n\n{traceback.format_exc()}"})
        yield history, None, None
        return