File size: 72,765 Bytes
14c2a54
 
 
 
 
 
 
dd0ce1d
 
 
 
 
e24dc64
 
dd0ce1d
800a4cc
14c2a54
dd0ce1d
14c2a54
 
 
a77683f
dd0ce1d
 
 
 
 
 
 
 
 
 
14f8edc
9486c75
14c2a54
9486c75
e24dc64
 
 
 
 
 
 
 
 
 
 
 
 
 
a77683f
e24dc64
14c2a54
 
 
 
 
 
 
 
 
 
 
 
9486c75
 
14c2a54
9486c75
14c2a54
e24dc64
 
 
 
 
14c2a54
 
 
 
 
 
 
e24dc64
14c2a54
e24dc64
a77683f
e24dc64
 
a77683f
 
 
 
a2d4ce0
 
 
a77683f
e24dc64
a77683f
e24dc64
 
a77683f
 
 
 
 
e24dc64
 
a77683f
 
 
 
e24dc64
14c2a54
 
2ee88d8
 
 
 
 
 
 
 
 
 
 
14c2a54
a77683f
 
 
a2d4ce0
 
 
 
 
 
 
 
 
 
 
a77683f
 
14c2a54
 
e24dc64
14c2a54
 
a77683f
14c2a54
 
 
a77683f
14c2a54
 
 
a77683f
e24dc64
a77683f
e24dc64
 
a77683f
14c2a54
 
 
 
 
a2d4ce0
 
 
 
 
e24dc64
a2d4ce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e24dc64
 
a77683f
 
 
e24dc64
 
a77683f
e24dc64
 
 
 
14c2a54
 
e24dc64
14c2a54
 
e24dc64
 
 
 
 
14c2a54
e24dc64
14c2a54
 
 
e24dc64
14c2a54
e24dc64
 
 
a77683f
14c2a54
 
 
 
e24dc64
 
 
 
14c2a54
 
 
e24dc64
a77683f
e24dc64
 
 
14c2a54
 
e24dc64
14c2a54
e24dc64
 
 
14c2a54
e24dc64
 
 
14c2a54
e24dc64
 
 
14c2a54
e24dc64
 
 
 
 
14c2a54
 
 
 
 
e24dc64
14c2a54
 
 
e24dc64
14c2a54
 
e24dc64
a77683f
e24dc64
14c2a54
 
 
e24dc64
 
 
 
 
14c2a54
 
7ac75d0
 
14c2a54
 
 
7ac75d0
 
14c2a54
 
 
800a4cc
 
e24dc64
7ac75d0
 
 
 
 
 
 
 
e24dc64
2ee88d8
e24dc64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c2a54
7ac75d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba2913
7ac75d0
 
 
 
1ba2913
7ac75d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba2913
7ac75d0
 
 
 
 
 
 
 
1ba2913
7ac75d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ba2913
 
14c2a54
 
 
e24dc64
14c2a54
7ac75d0
e24dc64
 
 
7ac75d0
 
 
800a4cc
 
e24dc64
7ac75d0
14c2a54
e24dc64
14c2a54
e24dc64
 
 
 
 
 
ef8d579
a77683f
e24dc64
a77683f
e24dc64
14c2a54
 
7ac75d0
 
e24dc64
7ac75d0
 
e24dc64
 
7ac75d0
e24dc64
 
 
7ac75d0
 
 
 
 
 
 
 
 
 
e24dc64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c2a54
a2d4ce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ee88d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c2a54
e24dc64
c49003e
e24dc64
 
 
 
 
 
a2d4ce0
 
 
 
 
 
 
 
 
 
 
 
e24dc64
a77683f
 
 
a2d4ce0
a77683f
 
 
e24dc64
14c2a54
a2d4ce0
 
 
a77683f
14c2a54
 
e24dc64
 
 
14c2a54
 
a2d4ce0
 
14c2a54
 
 
e24dc64
14c2a54
 
 
e24dc64
14c2a54
a2d4ce0
e24dc64
14c2a54
 
a2d4ce0
14c2a54
 
a2d4ce0
14c2a54
a2d4ce0
14c2a54
a2d4ce0
14c2a54
a2d4ce0
14c2a54
a2d4ce0
14c2a54
a2d4ce0
 
 
 
 
 
 
 
14c2a54
a2d4ce0
 
 
 
 
14c2a54
 
a2d4ce0
14c2a54
a2d4ce0
14c2a54
 
 
e24dc64
 
 
14c2a54
 
 
 
 
e24dc64
 
 
 
 
795d4f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e24dc64
 
 
14c2a54
643c6a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ef8f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643c6a1
5ef8f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643c6a1
 
5ef8f7c
14c2a54
e24dc64
800a4cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366a75e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
812aca2
 
 
 
 
 
 
 
 
fc3c608
812aca2
 
fc3c608
812aca2
 
800a4cc
812aca2
 
 
 
 
 
800a4cc
812aca2
 
 
 
 
 
fc3c608
812aca2
 
 
 
 
fc3c608
 
 
 
 
 
812aca2
fc3c608
812aca2
fc3c608
812aca2
fc3c608
 
812aca2
 
fc3c608
812aca2
fc3c608
812aca2
fc3c608
 
 
 
 
812aca2
 
 
fc3c608
 
 
 
812aca2
 
 
fc3c608
812aca2
 
 
fc3c608
812aca2
fc3c608
 
 
 
812aca2
 
 
 
 
 
 
fc3c608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
812aca2
fc3c608
 
 
812aca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3c608
 
 
 
812aca2
 
 
fc3c608
 
 
 
812aca2
 
 
 
 
 
 
fc3c608
 
812aca2
 
 
fc3c608
812aca2
fc3c608
 
 
 
812aca2
 
fc3c608
812aca2
 
 
 
 
 
 
 
 
fc3c608
 
800a4cc
366a75e
fc3c608
 
812aca2
800a4cc
14c2a54
812aca2
 
 
 
 
 
 
 
 
 
 
 
7ac75d0
e24dc64
2ee88d8
7ac75d0
2ee88d8
7ac75d0
e24dc64
7ac75d0
 
 
 
 
 
 
 
 
 
 
14c2a54
812aca2
 
 
 
 
 
 
 
 
 
 
 
7ac75d0
14c2a54
e24dc64
14c2a54
800a4cc
 
 
 
366a75e
812aca2
 
 
 
 
fc3c608
 
800a4cc
7ac75d0
 
 
 
 
 
 
 
 
800a4cc
 
 
 
2ee88d8
812aca2
800a4cc
 
 
 
 
366a75e
812aca2
 
 
 
 
fc3c608
 
800a4cc
14c2a54
e24dc64
14c2a54
 
 
 
 
 
 
 
 
16fd36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a77683f
16fd36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800a4cc
812aca2
 
 
fc3c608
812aca2
 
 
fc3c608
 
812aca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3c608
 
 
812aca2
fc3c608
812aca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc3c608
812aca2
 
 
 
fc3c608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800a4cc
 
 
 
 
 
 
 
 
fc3c608
800a4cc
 
 
fc3c608
 
 
 
 
800a4cc
14c2a54
 
 
16fd36e
 
 
 
 
 
 
 
 
 
 
 
 
14c2a54
 
 
 
643c6a1
14c2a54
 
 
16fd36e
 
 
 
 
 
 
 
 
 
 
e24dc64
14c2a54
 
795d4f4
 
fc3c608
 
812aca2
 
 
 
 
 
14c2a54
fc3c608
 
366a75e
2ee88d8
812aca2
800a4cc
 
812aca2
 
 
800a4cc
 
 
 
 
 
 
 
fc3c608
2ee88d8
 
 
14c2a54
2ee88d8
 
14c2a54
 
 
812aca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800a4cc
812aca2
 
14c2a54
 
e24dc64
366a75e
 
 
 
 
 
 
 
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
"""
RegTech BR — Hugging Face Space
================================
Compliance analyzer for Brazilian crypto asset regulation.
Uses FAISS RAG + Claude Sonnet 4.6 to produce structured risk assessments.
"""

import os
import sys
import json
import re
import types
import html
import warnings
import unicodedata
import uuid
from pathlib import Path

import numpy as np
import requests

warnings.filterwarnings("ignore", category=DeprecationWarning, message=".*audioop.*")

try:
    import audioop as _audioop
    sys.modules.setdefault("pyaudioop", _audioop)
except Exception:
    dummy_audioop = types.ModuleType("audioop")
    sys.modules.setdefault("audioop", dummy_audioop)
    sys.modules.setdefault("pyaudioop", dummy_audioop)

import gradio as gr

INDEX_DIR = Path(".")

print("Loading RegTech BR index...", flush=True)

required_files = [
    INDEX_DIR / "chunks_meta.jsonl",
    INDEX_DIR / "embeddings.npy",
    INDEX_DIR / "faiss_index.bin",
]

missing_files = [str(p) for p in required_files if not p.exists()]

if missing_files:
    for p in sorted(Path(".").iterdir()):
        if p.is_file():
            print(f" - {p.name} | {p.stat().st_size / 1024:.2f} KB", flush=True)
    raise FileNotFoundError(
        "Missing required index files:\n" + "\n".join(missing_files)
    )

import faiss
from sentence_transformers import SentenceTransformer

CHUNKS: list[dict] = []
with open(INDEX_DIR / "chunks_meta.jsonl", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if line:
            CHUNKS.append(json.loads(line))

EMBEDDINGS = np.load(INDEX_DIR / "embeddings.npy")
INDEX = faiss.read_index(str(INDEX_DIR / "faiss_index.bin"))
MODEL = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2")

print(f"Index ready — {len(CHUNKS)} chunks, {INDEX.ntotal} vectors", flush=True)


# ============================================================
# Normalization and routing
# ============================================================

def normalize(text: str) -> str:
    text = unicodedata.normalize("NFD", text or "")
    text = "".join(c for c in text if unicodedata.category(c) != "Mn")
    text = text.lower()
    text = re.sub(r"[^a-z0-9]+", " ", text)
    return re.sub(r"\s+", " ", text).strip()


AUTHORITY_KW = {
    "BCB": [
        "banco central", "bcb", "bacen", "psav", "psaav",
        "prestadora de servicos de ativos virtuais",
        "prestadores de servicos de ativos virtuais",
        "ativo virtual", "ativos virtuais", "criptoativo", "criptoativos",
        "autorizacao", "autorizar", "autorizada",
        "cambio", "capital internacional", "mercado de cambio",
        "segregacao patrimonial", "segregacao", "patrimonial",
        "segregation", "segregate", "segregated", "commingle", "commingled",
        "client assets", "customer assets", "customer funds", "own funds",
        "custody", "custodial", "safekeeping",
        "ativos dos clientes", "ativos de clientes",
        "ativos de titularidade dos clientes",
        "circular", "resolucao bcb", "instrucao normativa bcb",
    ],
    "CVM": [
        "cvm", "comissao de valores", "valores mobiliarios", "valor mobiliario",
        "token", "tokens", "security token", "oferta publica",
        "oferta publica de distribuicao", "investidor", "dividendos",
        "receita da plataforma", "direito de voto", "captar", "captacao",
        "rwa", "parecer", "parecer de orientacao",
    ],
    "COAF": [
        "coaf", "pessoa exposta politicamente", "pessoas expostas politicamente",
        "pep", "politically exposed", "kyc", "conheca seu cliente",
        "identificacao do cliente", "cliente anonimo", "anonimo", "anonima",
        "prevencao", "lavagem", "terrorismo", "pld", "ftp", "pld ftp", "aml", "cft",
    ],
}



def detect_language(text: str) -> str:
    """Simple heuristic: if majority of common words are Portuguese, return 'pt', else 'en'."""
    pt_markers = ["nossa", "nosso", "não", "nao", "para", "dos", "das", "uma", "com", "são", "sao",
                  "que", "por", "mas", "como", "qual", "quais", "ativos", "clientes", "serviços",
                  "empresa", "plataforma", "banco", "central", "criptoativos"]
    q = normalize(text)
    hits = sum(1 for m in pt_markers if m in q)
    return "pt" if hits >= 2 else "en"

SOURCE_KW = {
    "lei_14478": ["lei 14 478", "lei 14478", "lei n 14 478", "marco legal", "lei dos criptoativos"],
    "decreto_11563": ["decreto 11 563", "decreto 11563", "decreto n 11 563"],
    "bcb_circular_3978": ["circular 3978", "circular n 3978", "pld", "ftp", "lavagem", "terrorismo", "kyc", "identificacao do cliente", "anonimo", "anonima"],
    "bcb_in701": [
        "instrucao normativa 701", "instrucao normativa bcb 701", "certificacao tecnica",
        "segregacao", "segregacao patrimonial", "ativos dos clientes",
        "ativos virtuais de titularidade dos clientes", "segregation", "segregate",
        "client assets", "customer assets", "customer funds", "own funds", "custody"
    ],
    "bcb_res548": [
        "resolucao 548", "resolucao bcb 548", "autorizacao psav", "autorizacao", "psav",
        "authorization", "formal authorization", "without authorization", "virtual asset service provider",
        "segregation", "client assets", "customer assets"
    ],
    "cvm": ["cvm", "valores mobiliarios", "valor mobiliario", "token", "tokens", "oferta publica", "dividendos", "direito de voto"],
    "coaf": ["coaf", "pep", "pessoa exposta politicamente", "pessoas expostas politicamente"],
}


def detect_route(query: str) -> dict:
    q = normalize(query)
    route = {"authority_filters": [], "source_id_contains": [], "query_expansion": []}

    if any(normalize(k) in q for k in SOURCE_KW["lei_14478"]):
        route["source_id_contains"].append("lei_14478")
        route["query_expansion"].extend(["Lei 14.478 de 2022", "marco legal dos criptoativos", "prestadora de serviços de ativos virtuais"])

    if any(normalize(k) in q for k in SOURCE_KW["decreto_11563"]):
        route["source_id_contains"].append("decreto_11563")
        route["query_expansion"].extend(["Decreto 11.563 de 2023", "Banco Central do Brasil", "prestadoras de serviços de ativos virtuais"])

    hits = {a: sum(1 for k in kws if normalize(k) in q) for a, kws in AUTHORITY_KW.items()}
    max_hits = max(hits.values()) if hits else 0
    if max_hits:
        route["authority_filters"] = [a for a, h in hits.items() if h == max_hits or h >= 2]

    for key, kws in SOURCE_KW.items():
        if any(normalize(k) in q for k in kws):
            route["source_id_contains"].append(key)

    if any(t in q for t in [
        "segregacao", "patrimonial", "ativos dos clientes", "ativos de clientes",
        "segregation", "segregate", "segregated", "client assets", "customer assets",
        "customer funds", "own funds", "commingle", "commingled", "custody"
    ]):
        route["authority_filters"].append("BCB")
        route["source_id_contains"].extend(["bcb_in701", "bcb_res548", "lei_14478", "decreto_11563"])
        route["query_expansion"].extend([
            "segregação patrimonial de ativos virtuais",
            "segregation of client assets",
            "client assets must be segregated from own funds",
            "ativos de titularidade da instituição",
            "ativos de titularidade de clientes e usuários",
            "prestadora de serviços de ativos virtuais"
        ])

    if any(t in q for t in [
        "sem autorizacao", "autorizacao", "banco central", "psav",
        "without authorization", "formal authorization", "authorization", "authorisation",
        "central bank", "virtual asset service provider", "vasp"
    ]):
        route["authority_filters"].append("BCB")
        route["source_id_contains"].extend(["bcb_res548", "bcb_in701", "lei_14478", "decreto_11563"])
        route["query_expansion"].extend(["autorização para prestadora de serviços de ativos virtuais", "Banco Central do Brasil", "PSAV", "Resolução BCB 548"])

    if any(t in q for t in ["kyc", "anonimo", "anonima", "identificacao", "lavagem"]):
        route["authority_filters"].extend(["BCB", "COAF"])
        route["source_id_contains"].extend(["bcb_circular_3978", "coaf_res036"])
        route["query_expansion"].extend(["identificação e qualificação de clientes", "cliente anônimo", "prevenção à lavagem de dinheiro", "financiamento do terrorismo"])

    for key in ["authority_filters", "source_id_contains", "query_expansion"]:
        route[key] = list(dict.fromkeys(route[key]))

    return route


def route_boost(chunk: dict, route: dict) -> float:
    boost = 0.0
    source_id = normalize(str(chunk.get("source_id", "")))
    authority = chunk.get("authority")
    for token in route.get("source_id_contains", []):
        token_norm = normalize(str(token))
        if token_norm and token_norm in source_id:
            boost += 0.35
    if authority in route.get("authority_filters", []):
        boost += 0.08
    return min(boost, 0.55)


def lexical_boost(query_norm: str, chunk: dict) -> float:
    tags = chunk.get("tags", [])
    if not isinstance(tags, list):
        tags = [str(tags)]
    parts = " ".join([str(chunk.get("source_id", "")), str(chunk.get("source_label", "")), str(chunk.get("authority", "")), " ".join(str(t) for t in tags), str(chunk.get("text", ""))])
    chunk_norm = normalize(parts)
    terms = [t for t in query_norm.split() if len(t) >= 4]
    if not terms:
        return 0.0
    unique_terms = list(dict.fromkeys(terms))
    hits = sum(1 for t in unique_terms if t in chunk_norm)
    return min(0.12, hits / max(6, len(unique_terms)) * 0.12)


def retrieve(query: str, top_k: int = 6) -> list[dict]:
    route = detect_route(query)
    expanded = query + "\n" + "\n".join(route.get("query_expansion", []))
    q_vec = MODEL.encode([expanded], normalize_embeddings=True, convert_to_numpy=True).astype(np.float32)
    k_search = min(len(CHUNKS), max(top_k * 20, 30))
    scores, indices = INDEX.search(q_vec, k_search)
    query_norm = normalize(expanded)
    ranked = []
    for score, idx in zip(scores[0], indices[0]):
        if idx < 0:
            continue
        semantic_score = float(score)
        if semantic_score < 0.20:
            continue
        chunk = CHUNKS[int(idx)].copy()
        final_score = semantic_score + lexical_boost(query_norm, chunk) + route_boost(chunk, route)
        chunk["_score"] = semantic_score
        chunk["_final"] = final_score
        ranked.append(chunk)
    ranked.sort(key=lambda r: float(r.get("_final", 0.0)), reverse=True)
    seen = set()
    unique = []
    for r in ranked:
        raw_cid = r.get("chunk_id", r.get("source_id", "unknown"))
        try:
            cid = json.dumps(raw_cid, sort_keys=True, ensure_ascii=False, default=str)
        except Exception:
            cid = str(raw_cid)
        if cid not in seen:
            seen.add(cid)
            unique.append(r)
    return unique[:top_k]


def format_context(results: list[dict]) -> str:
    lines = []
    for i, r in enumerate(results, 1):
        article = f" — {r['article_hint']}" if r.get("article_hint") else ""
        norm = f" [{r['normative_reference_hint']}]" if r.get("normative_reference_hint") else ""
        lines.append(
            f"[SOURCE {i}] {r.get('source_label', '')}{article}{norm}\n"
            f"Source ID: {r.get('source_id', '?')} | Authority: {r.get('authority', '?')} | Score: {float(r.get('_final', 0.0)):.3f}\n"
            f"{str(r.get('text', ''))[:700]}..."
        )
    return "\n\n---\n\n".join(lines)


# ============================================================
# Claude API
# ============================================================

SYSTEM = """You are RegTech BR, a specialist AI in Brazilian crypto asset regulation.
Analyze the compliance query and produce a structured JSON assessment.
Respond ONLY with valid JSON — no markdown fences.
Use EXACTLY these snake_case keys:
{
  "risk_level": "LOW | MEDIUM | HIGH | UNCLEAR",
  "compliance_status": "COMPLIANT | NON-COMPLIANT | REQUIRES_REVIEW | INSUFFICIENT_INFO",
  "applicable_regulations": ["list of regulation names"],
  "relevant_articles": ["list of specific article references"],
  "finding": "2-5 sentence assessment",
  "corrective_action": "specific steps or 'No action required'",
  "confidence": "HIGH | MEDIUM | LOW",
  "authority": "BCB | CVM | COAF | mixed | federal",
  "suggested_followups": ["3 short follow-up questions in the same language as the query"]
}
Rules:
- Always populate applicable_regulations and relevant_articles as non-empty arrays.
- Use only regulation/article references present in the retrieved context.
- If an exact article is unclear, cite the closest source/article_hint from the retrieved context instead of leaving the array empty.
- If the query describes operating without required authorization, flag high risk.
- If the query describes weak KYC or anonymous transactions, flag high risk.
- If the query describes no segregation of client assets, flag high risk.
- If the query describes tokens with dividends, voting rights, or public fundraising, flag CVM securities risk.
- Base the answer strictly on the retrieved regulatory context.
- Always add a "suggested_followups" key: an array of 3 short follow-up questions in the SAME language as the query (Portuguese or English). Each question should explore a related compliance angle not yet covered by the finding.
"""


def extract_json_object(raw: str) -> str:
    raw = (raw or "").strip()
    raw = re.sub(r"^```(?:json)?", "", raw, flags=re.IGNORECASE).strip()
    raw = re.sub(r"```$", "", raw).strip()
    if raw.startswith("{") and raw.endswith("}"):
        return raw
    start = raw.find("{")
    end = raw.rfind("}")
    if start >= 0 and end > start:
        return raw[start:end + 1]
    return raw


# ============================================================
# Claude output normalization and safety fallback
# ============================================================

KEY_ALIASES = {
    "risk_level": [
        "risk_level", "riskLevel", "risk", "level", "nivel_risco", "nível_risco",
        "nivel_de_risco", "nível_de_risco",
    ],
    "compliance_status": [
        "compliance_status", "complianceStatus", "status", "compliance",
        "status_conformidade", "conformidade",
    ],
    "applicable_regulations": [
        "applicable_regulations", "applicableRegulations", "applicable regulation",
        "applicable regulations", "regulations", "regulation", "laws", "legal_basis",
        "legalBasis", "normas_aplicaveis", "normas_aplicáveis", "regulacoes_aplicaveis",
        "regulações_aplicáveis", "regulamentacoes", "regulamentações",
    ],
    "relevant_articles": [
        "relevant_articles", "relevantArticles", "relevant articles", "articles",
        "article_references", "legal_references", "citations", "references",
        "artigos_relevantes", "artigos", "dispositivos", "dispositivos_relevantes",
    ],
    "finding": [
        "finding", "findings", "assessment", "analysis", "analise", "análise",
        "conclusao", "conclusão", "avaliacao", "avaliação",
    ],
    "corrective_action": [
        "corrective_action", "correctiveAction", "action", "recommended_action",
        "recommendation", "recomendacao", "recomendação", "acao_corretiva", "ação_corretiva",
    ],
    "confidence": [
        "confidence", "confidence_level", "confidenceLevel", "confianca", "confiança",
    ],
    "authority": [
        "authority", "authority_type", "regulator", "agency", "orgao", "órgão",
        "autoridade", "autoridade_competente",
    ],
}


def _norm_key(key: str) -> str:
    key = unicodedata.normalize("NFD", str(key or ""))
    key = "".join(c for c in key if unicodedata.category(c) != "Mn")
    key = re.sub(r"[^a-zA-Z0-9]+", "_", key).strip("_").lower()
    return key


def _lookup_alias(data: dict, canonical_key: str):
    if not isinstance(data, dict):
        return None

    direct_aliases = KEY_ALIASES.get(canonical_key, [])
    for alias in direct_aliases:
        if alias in data:
            return data.get(alias)

    norm_to_original = {_norm_key(k): k for k in data.keys()}
    for alias in direct_aliases:
        norm_alias = _norm_key(alias)
        if norm_alias in norm_to_original:
            return data.get(norm_to_original[norm_alias])

    return None


def as_list(value) -> list[str]:
    """Coerce Claude output into a clean list of strings.

    Handles arrays, strings, numbers, and arrays of objects such as:
    [{"name": "Lei 14.478/2022"}, {"article": "Art. 7º"}]
    """
    if value is None:
        return []
    if isinstance(value, list):
        out = []
        for item in value:
            out.extend(as_list(item))
        return list(dict.fromkeys([str(v).strip() for v in out if str(v).strip()]))
    if isinstance(value, dict):
        preferred = [
            "name", "title", "reference", "article", "regulation", "law",
            "text", "label", "value", "source", "source_label",
        ]
        for key in preferred:
            if key in value and value[key]:
                return as_list(value[key])
        return [
            "; ".join(f"{k}: {v}" for k, v in value.items() if v)
        ]
    text_value = str(value).strip()
    if not text_value:
        return []
    return [text_value]


def infer_regulations_from_results(results: list[dict], max_items: int = 4) -> list[str]:
    regs = []
    for r in results or []:
        label = str(r.get("source_label") or "").strip()
        norm_ref = str(r.get("normative_reference_hint") or "").strip()
        source_id = str(r.get("source_id") or "").strip()

        if label:
            item = label
            if norm_ref and norm_ref not in item:
                item = f"{item}{norm_ref}"
        elif norm_ref:
            item = norm_ref
        else:
            item = source_id

        if item:
            regs.append(item)

    return list(dict.fromkeys(regs))[:max_items]


def infer_articles_from_results(results: list[dict], max_items: int = 6) -> list[str]:
    articles = []
    for r in results or []:
        article = str(r.get("article_hint") or "").strip()
        norm_ref = str(r.get("normative_reference_hint") or "").strip()
        label = str(r.get("source_label") or "").strip()
        source_id = str(r.get("source_id") or "").strip()

        if article and norm_ref:
            item = f"{norm_ref}{article}"
        elif article and label:
            item = f"{label}{article}"
        elif article:
            item = article
        elif norm_ref:
            item = norm_ref
        elif source_id:
            item = source_id
        else:
            item = ""

        if item:
            articles.append(item)

    return list(dict.fromkeys(articles))[:max_items]


def canonicalize_report(report: dict, results: list[dict]) -> dict:
    """Normalize Claude response keys and guarantee non-empty legal-reference arrays."""
    if not isinstance(report, dict):
        report = {}

    canonical = dict(report)

    for key in KEY_ALIASES:
        value = _lookup_alias(report, key)
        if value is not None:
            canonical[key] = value

    canonical["risk_level"] = str(canonical.get("risk_level", "UNCLEAR")).upper().replace("-", "_")
    canonical["compliance_status"] = (
        str(canonical.get("compliance_status", "INSUFFICIENT_INFO"))
        .upper()
        .replace("_", "-")
    )
    canonical["confidence"] = str(canonical.get("confidence", "LOW")).upper()

    regs = as_list(canonical.get("applicable_regulations"))
    if not regs:
        regs = infer_regulations_from_results(results)
        print(
            "[WARN] applicable_regulations empty or missing in Claude response; "
            f"filled from retrieved sources: {regs}",
            flush=True,
        )

    articles = as_list(canonical.get("relevant_articles"))
    if not articles:
        articles = infer_articles_from_results(results)
        print(
            "[WARN] relevant_articles empty or missing in Claude response; "
            f"filled from retrieved sources: {articles}",
            flush=True,
        )

    canonical["applicable_regulations"] = regs
    canonical["relevant_articles"] = articles

    if not canonical.get("finding"):
        canonical["finding"] = "Assessment generated from the retrieved regulatory context."
    if not canonical.get("corrective_action"):
        canonical["corrective_action"] = "Review the cited regulatory sources and update the compliance procedure accordingly."
    if not canonical.get("authority"):
        authorities = [str(r.get("authority")) for r in results or [] if r.get("authority")]
        canonical["authority"] = "mixed" if len(set(authorities)) > 1 else (authorities[0] if authorities else "?")

    return canonical


def debug_print_claude(raw: str, clean: str, parsed: dict | None = None) -> None:
    print("\n" + "=" * 72, flush=True)
    print("CLAUDE RAW RESPONSE START", flush=True)
    print(raw or "<EMPTY RAW RESPONSE>", flush=True)
    print("CLAUDE RAW RESPONSE END", flush=True)
    print("-" * 72, flush=True)
    print("CLAUDE EXTRACTED JSON START", flush=True)
    print(clean or "<EMPTY EXTRACTED JSON>", flush=True)
    print("CLAUDE EXTRACTED JSON END", flush=True)
    if isinstance(parsed, dict):
        print("-" * 72, flush=True)
        print(f"CLAUDE PARSED KEYS: {sorted(parsed.keys())}", flush=True)
        print(
            "CLAUDE LEGAL ARRAYS: "
            f"applicable_regulations={parsed.get('applicable_regulations')!r}; "
            f"relevant_articles={parsed.get('relevant_articles')!r}",
            flush=True,
        )
    print("=" * 72 + "\n", flush=True)


def call_claude(query: str, context: str) -> dict | None:
    api_key = os.environ.get("ANTHROPIC_API_KEY", "")
    if not api_key:
        print("Missing ANTHROPIC_API_KEY.", flush=True)
        return None

    prompt = (
        f"COMPLIANCE QUERY:\n{query}\n\n"
        f"REGULATORY CONTEXT:\n\n{context}\n\n"
        "Produce a structured compliance assessment. "
        "Return ONLY valid JSON using EXACTLY these keys: "
        "risk_level, compliance_status, applicable_regulations, relevant_articles, "
        "finding, corrective_action, confidence, authority, suggested_followups. "
        "The arrays applicable_regulations, relevant_articles, and suggested_followups must be non-empty."
    )

    try:
        response = requests.post(
            "https://api.anthropic.com/v1/messages",
            headers={
                "Content-Type": "application/json",
                "x-api-key": api_key,
                "anthropic-version": "2023-06-01",
            },
            json={
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 1400,
                "system": SYSTEM,
                "messages": [{"role": "user", "content": prompt}],
            },
            timeout=90,
        )

        print(f"Claude HTTP status: {response.status_code}", flush=True)
        response.raise_for_status()

        payload = response.json()
        raw = "".join(
            block.get("text", "")
            for block in payload.get("content", [])
            if block.get("type") == "text"
        )
        clean = extract_json_object(raw)

        try:
            parsed = json.loads(clean)
            debug_print_claude(raw, clean, parsed)
            return parsed
        except json.JSONDecodeError as json_exc:
            debug_print_claude(raw, clean, None)
            print(f"Claude JSON parse error: {json_exc}", flush=True)
            return None

    except Exception as exc:
        print(f"Claude error: {type(exc).__name__}: {exc}", flush=True)
        return None


# ============================================================
# HTML rendering
# ============================================================

RISK_COLOR = {
    "HIGH": "#dc2626",
    "MEDIUM": "#d97706",
    "LOW": "#16a34a",
    "UNCLEAR": "#6b7280",
}

STATUS_ICON = {
    "NON-COMPLIANT": "⛔",
    "COMPLIANT": "✅",
    "REQUIRES_REVIEW": "⚠️",
    "INSUFFICIENT_INFO": "❓",
}


def esc(value) -> str:
    return html.escape("" if value is None else str(value))


def render_value_rows(items, accent: str, empty_label: str) -> str:
    """Render legal references without ul/li, because Gradio/theme CSS can hide list items."""
    values = as_list(items)
    if not values:
        values = [empty_label]
        accent = "#94a3b8"

    rows = []
    for item in values:
        rows.append(
            f"""
            <div style="display:flex;align-items:flex-start;gap:0.55rem;
                        margin:0.35rem 0;padding:0.45rem 0.55rem;border-radius:6px;
                        background:#0f172a;border:1px solid #334155;overflow:visible">
              <span style="color:{accent};font-weight:700;line-height:1.35;flex:0 0 auto">•</span>
              <span style="color:{accent};font-size:0.82rem;line-height:1.45;
                           white-space:normal;word-break:break-word;overflow-wrap:anywhere;display:block">{esc(item)}</span>
            </div>
            """
        )
    return "".join(rows)




def render_followups(followups: list, lang: str = "en") -> str:
    """Render suggested follow-up questions as clickable chips below the evidence."""
    items = [str(f).strip() for f in (followups or []) if str(f).strip()]
    if not items:
        return ""

    label = "Explore related questions" if lang == "en" else "Explorar questões relacionadas"
    chips = "".join(
        f"""<div onclick="
            var tb = document.querySelector('.query-box textarea');
            if(tb){{tb.value={json.dumps(item)};tb.dispatchEvent(new Event('input',{{bubbles:true}}));}}
        " style="cursor:pointer;background:#0f172a;border:1px solid #1e3a5f;border-radius:8px;
                 padding:0.6rem 0.9rem;margin:0.35rem 0;color:#93c5fd;font-size:0.82rem;
                 font-family:'IBM Plex Mono',monospace;line-height:1.45;
                 transition:border-color 0.15s,background 0.15s"
           onmouseover="this.style.borderColor='#38bdf8';this.style.background='#172554'"
           onmouseout="this.style.borderColor='#1e3a5f';this.style.background='#0f172a'">
          <span style="color:#475569;margin-right:0.4rem">→</span>{esc(item)}
        </div>"""
        for item in items[:4]
    )

    return f"""
<div style="font-family:'IBM Plex Mono',monospace;background:#0a0f1e;border:1px solid #172554;
            border-radius:12px;padding:1rem 1.1rem;margin-top:0.5rem">
  <div style="color:#475569;font-size:0.72rem;text-transform:uppercase;
              letter-spacing:0.12em;margin-bottom:0.6rem">{esc(label)}</div>
  {chips}
</div>
"""

def render_report(report: dict, query: str, results: list[dict]) -> str:
    risk = str(report.get("risk_level", "UNCLEAR")).upper()
    status = str(report.get("compliance_status", "INSUFFICIENT_INFO")).upper().replace("_", "-")
    confidence = str(report.get("confidence", "LOW")).upper()
    authority = str(report.get("authority", "?"))

    color = RISK_COLOR.get(risk, "#6b7280")
    icon = STATUS_ICON.get(status, "❓")

    regs_items = as_list(report.get("applicable_regulations"))
    arts_items = as_list(report.get("relevant_articles"))

    print(
        "RENDER LEGAL ARRAYS: "
        f"regulations_count={len(regs_items)}; articles_count={len(arts_items)}; "
        f"regulations={regs_items!r}; articles={arts_items!r}",
        flush=True,
    )

    regs_html = render_value_rows(regs_items, "#93c5fd", "Not specified by Claude or fallback")
    arts_html = render_value_rows(arts_items, "#86efac", "Not specified by Claude or fallback")

    seen_src = set()
    unique_results = []
    for r in results:
        sid = str(r.get("source_id", ""))
        if sid not in seen_src:
            seen_src.add(sid)
            unique_results.append(r)

    srcs = "".join(
        f'<span style="background:#1e3a5f;color:#bfdbfe;padding:3px 9px;'
        f'border-radius:5px;font-size:0.75rem;margin:3px;display:inline-block;'
        f'border:1px solid #2563eb">{esc(r.get("source_id", ""))}</span>'
        for r in unique_results
    )

    finding = esc(report.get("finding", "—"))
    corrective_action = esc(report.get("corrective_action", "—"))

    return f"""
<div style="font-family:'IBM Plex Mono',monospace;background:#0f172a;color:#e2e8f0;
            padding:1.5rem;border-radius:12px;border:1px solid #1e3a5f;line-height:1.6;
            overflow:visible">
  <div style="display:flex;gap:1rem;align-items:center;margin-bottom:1.2rem;flex-wrap:wrap">
    <span style="background:{color};color:#fff;padding:4px 14px;border-radius:6px;
                 font-weight:700;font-size:0.9rem;letter-spacing:0.05em">
      {esc(risk)} RISK
    </span>
    <span style="background:#1e293b;color:#e2e8f0;padding:4px 14px;border-radius:6px;
                 font-size:0.9rem;border:1px solid #334155">
      {icon} {esc(status)}
    </span>
    <span style="color:#cbd5e1;font-size:0.8rem">
      confidence: {esc(confidence)} · authority: {esc(authority)}
    </span>
  </div>

  <div style="background:#1e293b;border-radius:8px;padding:1rem;margin-bottom:1rem;
              border-left:3px solid {color}">
    <div style="color:#cbd5e1;font-size:0.75rem;text-transform:uppercase;
                letter-spacing:0.1em;margin-bottom:0.5rem">Finding</div>
    <div style="color:#f8fafc;font-size:0.88rem">{finding}</div>
  </div>

  <div style="background:#1e293b;border-radius:8px;padding:1rem;margin-bottom:1rem">
    <div style="color:#cbd5e1;font-size:0.75rem;text-transform:uppercase;
                letter-spacing:0.1em;margin-bottom:0.5rem">Corrective Action</div>
    <div style="color:#f8fafc;font-size:0.88rem">{corrective_action}</div>
  </div>

  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));
              gap:1rem;margin-bottom:1rem;align-items:start;overflow:visible">
    <div style="background:#1e293b;border-radius:8px;padding:1rem;min-height:96px;
                border:1px solid #334155;overflow:visible">
      <div style="color:#cbd5e1;font-size:0.75rem;text-transform:uppercase;
                  letter-spacing:0.1em;margin-bottom:0.65rem">Applicable Regulations</div>
      <div style="display:block;overflow:visible">{regs_html}</div>
    </div>
    <div style="background:#1e293b;border-radius:8px;padding:1rem;min-height:96px;
                border:1px solid #334155;overflow:visible">
      <div style="color:#cbd5e1;font-size:0.75rem;text-transform:uppercase;
                  letter-spacing:0.1em;margin-bottom:0.65rem">Relevant Articles</div>
      <div style="display:block;overflow:visible">{arts_html}</div>
    </div>
  </div>

  <div style="margin-top:0.8rem">
    <div style="color:#cbd5e1;font-size:0.7rem;text-transform:uppercase;
                letter-spacing:0.1em;margin-bottom:0.4rem">Sources retrieved</div>
    {srcs}
  </div>
</div>
"""


def render_error(msg: str) -> str:
    return f"""
<div style="background:#1c1917;color:#fca5a5;padding:1.2rem;border-radius:8px;
            border:1px solid #7f1d1d;font-family:monospace">
  ⚠️ {esc(msg)}
</div>
"""



def render_evidence_summary(results: list[dict]) -> str:
    """Render a compact, visible summary of the retrieved RAG evidence."""
    if not results:
        return """
<div style="font-family:'IBM Plex Mono',monospace;background:#0f172a;color:#94a3b8;
            padding:1rem;border-radius:10px;border:1px solid #1e3a5f;margin-top:0.8rem">
  No retrieved evidence to display.
</div>
"""

    rows = []
    for i, r in enumerate(results, 1):
        source_id = esc(r.get("source_id", "unknown"))
        authority = esc(r.get("authority", "?"))
        article = esc(r.get("article_hint", "—") or "—")
        norm = esc(r.get("normative_reference_hint", "") or "")
        score = f"{float(r.get('_final', 0.0)):.3f}"
        text = esc(str(r.get("text", ""))[:260].strip())
        norm_line = f" · {norm}" if norm else ""
        rows.append(f"""
  <div style="background:#111827;border:1px solid #26364f;border-radius:8px;
              padding:0.85rem;margin:0.55rem 0">
    <div style="display:flex;gap:0.5rem;align-items:center;flex-wrap:wrap;margin-bottom:0.35rem">
      <span style="color:#e2e8f0;font-weight:700">SOURCE {i}</span>
      <span style="background:#1e3a5f;color:#93c5fd;padding:2px 8px;border-radius:4px;font-size:0.72rem">{source_id}</span>
      <span style="color:#94a3b8;font-size:0.72rem">{authority} · {article}{norm_line} · score {score}</span>
    </div>
    <div style="color:#cbd5e1;font-size:0.78rem;line-height:1.55">{text}...</div>
  </div>
""")

    return f"""
<div style="font-family:'IBM Plex Mono',monospace;background:#0f172a;color:#e2e8f0;
            padding:1rem;border-radius:12px;border:1px solid #1e3a5f;margin:1rem 0">
  <div style="color:#94a3b8;font-size:0.75rem;text-transform:uppercase;
              letter-spacing:0.1em;margin-bottom:0.4rem">
    Evidence retrieved from RAG
  </div>
  <div style="color:#64748b;font-size:0.74rem;margin-bottom:0.5rem">
    Compact view of the chunks used as context for Claude. The full raw context remains available below.
  </div>
  {''.join(rows)}
</div>
"""


# ============================================================
# Gradio app
# ============================================================

def build_dynamic_scenarios(max_items: int = 9) -> list[str]:
    """Build UI scenarios from the currently loaded regulatory index.

    This keeps the dropdown aligned with the corpus mounted in the Space.
    When the raw regulations/index are updated, the scenario list changes
    without manually editing fixed example strings.
    """
    corpus_parts = []
    for c in CHUNKS:
        tags = c.get("tags", [])
        if not isinstance(tags, list):
            tags = [tags]
        corpus_parts.extend([
            str(c.get("source_id", "")),
            str(c.get("source_label", "")),
            str(c.get("authority", "")),
            str(c.get("article_hint", "")),
            str(c.get("normative_reference_hint", "")),
            " ".join(str(t) for t in tags),
            str(c.get("text", ""))[:900],
        ])
    corpus_blob = normalize(" ".join(corpus_parts))
    source_ids = {str(c.get("source_id", "")) for c in CHUNKS}

    def has_any(*terms: str) -> bool:
        return any(normalize(t) in corpus_blob for t in terms if t)

    def has_source(*tokens: str) -> bool:
        return any(any(tok in sid for sid in source_ids) for tok in tokens)

    scenarios: list[str] = []

    def add_when(condition: bool, text: str) -> None:
        if condition and text not in scenarios:
            scenarios.append(text)

    # Corpus-driven regulatory themes. These appear only when the loaded
    # index contains matching rules/sources, so they evolve with the corpus.
    add_when(
        has_source("bcb_res548") or has_any("autorizacao", "psav", "prestadora de servicos de ativos virtuais"),
        "A crypto platform wants to operate exchange, custody, or intermediation services in Brazil before formal BCB authorization. What is the compliance risk?",
    )
    add_when(
        has_source("bcb_res520", "bcb_in701") or has_any("segregacao patrimonial", "ativos de titularidade dos clientes", "client assets"),
        "A PSAV keeps client virtual assets in wallets or accounts mixed with its own corporate treasury. Which segregation and custody obligations should be checked?",
    )
    add_when(
        has_source("bcb_in701") or has_any("certificacao tecnica", "instrucao normativa bcb 701"),
        "A PSAV is preparing its technical certification package for BCB review. Which governance, security, and operational evidence should be validated?",
    )
    add_when(
        has_source("bcb_circular_3978") or has_any("pld", "ftp", "lavagem", "terrorismo", "kyc", "cliente anonimo"),
        "A crypto service allows simplified onboarding and small anonymous transfers. Which AML/CFT and customer identification controls are required?",
    )
    add_when(
        has_any("cvm", "valores mobiliarios", "oferta publica", "dividendos", "direito de voto", "token"),
        "A token pays revenue share, grants voting rights, and will be publicly offered to Brazilian investors. Is there CVM securities risk?",
    )
    add_when(
        has_any("coaf", "pessoa exposta politicamente", "pep"),
        "A customer is a politically exposed person using a crypto platform. What enhanced due diligence or reporting obligations may apply?",
    )
    add_when(
        has_any("cambio", "capital internacional", "cross border", "stablecoin", "pagamento internacional"),
        "A platform uses stablecoins or crypto rails for cross-border payments and FX-like settlement. Which Brazilian regulatory perimeter should be assessed?",
    )
    add_when(
        has_any("diretor responsavel", "responsavel por pld", "responsavel formalmente designado", "governanca"),
        "A crypto platform has no formally appointed officer responsible for AML/CFT and compliance controls. What is the regulatory exposure?",
    )

    # Add source-specific scenarios so newly added documents can appear in the UI
    # even before a custom scenario rule is written for them.
    latest_by_source: dict[str, dict] = {}
    for c in CHUNKS:
        sid = str(c.get("source_id", "")).strip()
        if sid and sid not in latest_by_source:
            latest_by_source[sid] = c

    priority_terms = ["2026", "2025", "psav", "bcb", "cvm", "coaf", "lei_14478", "decreto_11563"]

    def source_priority(item: tuple[str, dict]) -> tuple[int, str]:
        sid, c = item
        hay = normalize(" ".join([
            sid,
            str(c.get("source_label", "")),
            str(c.get("normative_reference_hint", "")),
        ]))
        score = sum(1 for t in priority_terms if normalize(t) in hay)
        return (-score, sid)

    for sid, c in sorted(latest_by_source.items(), key=source_priority):
        if len(scenarios) >= max_items:
            break
        label = str(c.get("source_label", "") or sid).strip()
        article = str(c.get("article_hint", "") or "").strip()
        authority = str(c.get("authority", "") or "").strip()
        article_part = f", especially {article}" if article else ""
        authority_part = f" ({authority})" if authority else ""
        text = (
            f"Review a crypto compliance issue under {label}{authority_part}{article_part}. "
            "Which obligations, risks, and corrective actions should be checked?"
        )
        if text not in scenarios:
            scenarios.append(text)

    fallback = [
        "Describe a crypto product, policy, or control gap and assess which Brazilian crypto regulations may apply.",
        "Review whether a virtual asset service provider needs BCB authorization, AML/CFT controls, or CVM analysis.",
    ]
    return (scenarios or fallback)[:max_items]


SCENARIOS = build_dynamic_scenarios()


def scenario_note(message: str, color: str = "#94a3b8") -> str:
    return (
        f"<div style='color:{color};font-size:0.76rem;"
        "font-family:IBM Plex Mono,monospace;margin-top:0.35rem'>"
        f"{esc(message)}"
        "</div>"
    )


def load_next_scenario(cursor: int | None) -> tuple[str, dict, int, str]:
    """Cycle through generated scenarios one by one.

    Each click loads a different scenario into the query box, updates the
    dropdown selection, and advances the internal cursor. This avoids the
    previous behavior where the same selected scenario was repeatedly copied.
    """
    choices = build_dynamic_scenarios()
    if not choices:
        return (
            "",
            gr.update(choices=[], value=None),
            0,
            scenario_note("No scenarios were generated from the current index.", "#fca5a5"),
        )

    try:
        idx = int(cursor or 0) % len(choices)
    except Exception:
        idx = 0

    scenario = choices[idx]
    next_cursor = (idx + 1) % len(choices)
    note = scenario_note(
        f"Loaded scenario {idx + 1}/{len(choices)}. Click Load next scenario to rotate to another issue."
    )
    return scenario, gr.update(choices=choices, value=scenario), next_cursor, note


def refresh_scenarios() -> tuple[dict, int, str]:
    choices = build_dynamic_scenarios()
    note = scenario_note(
        f"Regenerated {len(choices)} scenarios from the currently loaded regulatory index. "
        "To reflect new laws or resolutions, update the corpus/index first, then restart or refresh."
    )
    return gr.update(choices=choices, value=None), 0, note


def infer_followups(query: str, results: list[dict], lang: str = "en") -> list[str]:
    """Fallback follow-up questions when Claude omits suggested_followups."""
    source_blob = normalize(" ".join(str(r.get("source_id", "")) + " " + str(r.get("source_label", "")) for r in results or []))

    if lang == "pt":
        base = [
            "Quais documentos e evidências seriam necessários para demonstrar conformidade ao regulador?",
            "Há risco de enquadramento simultâneo por BCB, CVM ou COAF neste caso?",
            "Quais controles internos deveriam ser priorizados antes de continuar a operação?",
        ]
        if "cvm" in source_blob:
            base.insert(0, "Esse produto pode ser tratado como valor mobiliário ou oferta pública sujeita à CVM?")
        if "coaf" in source_blob or "3978" in source_blob:
            base.insert(0, "Quais obrigações de PLD/FTP, KYC e comunicação devem ser avaliadas?")
        if "548" in source_blob or "psav" in source_blob:
            base.insert(0, "A atividade exige autorização prévia do Banco Central como PSAV?")
        return list(dict.fromkeys(base))[:3]

    base = [
        "Which documents and evidence would be needed to demonstrate compliance to the regulator?",
        "Is there simultaneous BCB, CVM, or COAF perimeter risk in this case?",
        "Which internal controls should be prioritized before continuing the operation?",
    ]
    if "cvm" in source_blob:
        base.insert(0, "Could this product be treated as a security or public offering subject to CVM oversight?")
    if "coaf" in source_blob or "3978" in source_blob:
        base.insert(0, "Which AML/CFT, KYC, and reporting obligations should be assessed?")
    if "548" in source_blob or "psav" in source_blob:
        base.insert(0, "Does this activity require prior BCB authorization as a PSAV?")
    return list(dict.fromkeys(base))[:3]


def write_context_file(query: str, context: str, results: list[dict], report: dict | None = None) -> str:
    """Write the full RAG context to a downloadable text file for audit/debug use."""
    out_dir = Path(os.environ.get("REGTECH_CONTEXT_DIR", "/tmp/regtech_br_contexts"))
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / f"regtech_br_retrieved_context_{uuid.uuid4().hex[:10]}.txt"

    source_lines = []
    for i, r in enumerate(results or [], 1):
        source_lines.append(
            f"[{i}] source_id={r.get('source_id', '?')} | "
            f"authority={r.get('authority', '?')} | "
            f"article_hint={r.get('article_hint', '') or '—'} | "
            f"normative_reference_hint={r.get('normative_reference_hint', '') or '—'} | "
            f"score={float(r.get('_final', 0.0)):.3f}"
        )

    report_json = json.dumps(report or {}, ensure_ascii=False, indent=2, default=str)
    sources_summary = "\n".join(source_lines)
    content = f"""RegTech BR — Retrieved Regulatory Context
=========================================

Compliance query
----------------
{query}

Structured assessment JSON
--------------------------
{report_json}

Retrieved sources summary
-------------------------
{sources_summary}

Full raw RAG context
--------------------
{context}
"""
    out_path.write_text(content, encoding="utf-8")
    return str(out_path)


def render_context_download(path: str) -> str:
    """Render a lightweight download card without gr.File.

    Gradio 4.44.0 can crash while generating API metadata for gr.File
    on Spaces. A plain HTML link avoids that schema bug.
    The launch() call exposes REGTECH_CONTEXT_DIR through allowed_paths.
    """
    if not path:
        return ""

    safe_path = esc(path)
    filename = esc(Path(path).name)
    return f"""
<div style="font-family:'IBM Plex Mono',monospace;background:#0f172a;color:#e2e8f0;
            padding:0.9rem 1rem;border-radius:10px;border:1px solid #1e3a5f;
            margin:0.8rem 0">
  <div style="color:#94a3b8;font-size:0.72rem;text-transform:uppercase;
              letter-spacing:0.1em;margin-bottom:0.35rem">
    Download audit context
  </div>
  <div style="color:#64748b;font-size:0.74rem;margin-bottom:0.55rem">
    Full raw retrieved regulatory context exported as a text file.
  </div>
  <a href="/file={safe_path}" download="{filename}"
     style="display:inline-block;background:#1e3a5f;color:#bfdbfe;border:1px solid #2563eb;
            border-radius:6px;padding:0.45rem 0.7rem;text-decoration:none;font-size:0.78rem">
    Download {filename}
  </a>
</div>
"""


def make_followup_button_updates(followups: list[str], lang: str):
    """Prepare a compact recommendation panel using real Gradio buttons.

    Native Radio cards can inherit light theme styles in Spaces, making text
    difficult to read on a dark UI. Buttons give stable contrast and make the
    interaction clearer: each recommendation is a next-search action.
    """
    items = [str(f).strip() for f in followups if str(f).strip()][:3]
    visible = bool(items)
    if lang == "pt":
        title = "Pesquise mais com estas recomendações"
        subtitle = "Clique em uma recomendação para carregá-la no campo principal. Depois, execute Analyze para fazer uma nova busca RAG."
    else:
        title = "Research further with these recommendations"
        subtitle = "Click a recommendation to load it into the main input. Then run Analyze to start a new RAG search."

    header = f"""
<div class="followup-panel-copy followup-panel-shell">
  <div class="followup-panel-kicker">{esc(title)}</div>
  <div class="followup-panel-subtitle">{esc(subtitle)}</div>
</div>
""" if visible else ""

    button_updates = []
    for i in range(3):
        if i < len(items):
            button_updates.append(gr.update(value=f"→ {items[i]}", visible=True))
        else:
            button_updates.append(gr.update(value="", visible=False))

    return gr.update(value=header, visible=visible), items, *button_updates


def render_followup_detail(selected: str, original_query: str = "") -> str:
    """Render an explanatory card when a recommendation is selected."""
    selected = str(selected or "").strip()
    original_query = str(original_query or "").strip()
    if not selected:
        return ""

    lang = detect_language(original_query or selected)
    title = "Investigação recomendada" if lang == "pt" else "Recommended next investigation"
    subtitle = (
        "A recomendação foi carregada no campo principal. Clique em Analyze para pesquisar esse novo ângulo no índice regulatório."
        if lang == "pt"
        else "The recommendation was loaded into the main input. Click Analyze to search this new angle in the regulatory index."
    )
    original_label = "Prompt inicial" if lang == "pt" else "Initial prompt"
    next_label = "Pergunta para pesquisar" if lang == "pt" else "Question to research"
    why_label = "Por que isso ajuda" if lang == "pt" else "Why this helps"
    why_text = (
        "Ela transforma a conclusão anterior em uma checagem adicional: autorização, custódia, evidências, controles ou perímetro regulatório."
        if lang == "pt"
        else "It turns the previous assessment into an additional check: authorization, custody, evidence, controls, or regulatory perimeter."
    )

    original_html = ""
    if original_query:
        original_html = f"""
        <div class="recommendation-mini">
          <div class="recommendation-mini-label">{esc(original_label)}</div>
          <div class="recommendation-mini-text">{esc(original_query[:420])}</div>
        </div>
        """

    return f"""
<div class="recommendation-card">
  <div class="recommendation-kicker">{esc(title)}</div>
  <div class="recommendation-subtitle">{esc(subtitle)}</div>
  {original_html}
  <div class="recommendation-mini recommendation-next">
    <div class="recommendation-mini-label">{esc(next_label)}</div>
    <div class="recommendation-mini-text">{esc(selected)}</div>
  </div>
  <div class="recommendation-hint"><b>{esc(why_label)}:</b> {esc(why_text)}</div>
</div>
"""


def apply_followup_by_index(index: int, followup_items: list[str], original_query: str = "") -> tuple[str, str]:
    """Load a button-selected follow-up into the query box and show a detail card."""
    try:
        items = [str(x).strip() for x in (followup_items or []) if str(x).strip()]
        selected = items[index] if index < len(items) else ""
    except Exception:
        selected = ""
    return selected, render_followup_detail(selected, original_query)


QUICK_CHECK_META = {
    "BCB": {
        "title": "BCB · Authorization",
        "focus": "Checks whether the activity falls inside the Central Bank authorization perimeter for PSAV/VASP operations.",
        "inspect": "authorization status, corporate structure, service scope, custody/intermediation activity, and transitional risk.",
    },
    "CVM": {
        "title": "CVM · Securities",
        "focus": "Checks whether token rights may create securities, public offering, or investment contract risk.",
        "inspect": "revenue share, voting rights, fundraising, investor expectation of profit, and public distribution mechanics.",
    },
    "COAF": {
        "title": "COAF · AML/KYC",
        "focus": "Checks AML/CFT exposure, customer identification, suspicious activity monitoring, and reporting obligations.",
        "inspect": "KYC thresholds, anonymous transactions, PEP handling, transaction monitoring, and escalation/reporting procedures.",
    },
    "Lei 14.478": {
        "title": "Lei 14.478",
        "focus": "Checks the federal legal perimeter for virtual asset service providers and the legal basis for complementary regulation.",
        "inspect": "service-provider characterization, virtual asset scope, regulator competence, and relationship with BCB/CVM/COAF rules.",
    },
    "Segregação": {
        "title": "Segregação",
        "focus": "Checks whether client assets are separated from the company’s own funds and whether custody controls are adequate.",
        "inspect": "wallet/account separation, proof of reserves, custody agreements, reconciliation, and insolvency protection controls.",
    },
}


def render_quick_check_detail(label: str, loaded_query: str, current_prompt: str = "") -> str:
    """Show contextual guidance when a quick regulatory check button is clicked."""
    meta = QUICK_CHECK_META.get(label, {})
    title = meta.get("title", label)
    current_prompt = str(current_prompt or "").strip()
    lang = detect_language(current_prompt or loaded_query)

    focus_pt = {
        "BCB": "Verifica se a atividade entra no perímetro de autorização do Banco Central para operações de PSAV/VASP.",
        "CVM": "Verifica se os direitos do token podem gerar risco de valor mobiliário, oferta pública ou contrato de investimento.",
        "COAF": "Verifica exposição de PLD/FTP, identificação de clientes, monitoramento e comunicação de operações suspeitas.",
        "Lei 14.478": "Verifica o enquadramento legal federal das prestadoras de serviços de ativos virtuais e a base das normas complementares.",
        "Segregação": "Verifica se os ativos dos clientes estão separados dos recursos próprios da empresa e se a custódia é adequada.",
    }
    inspect_pt = {
        "BCB": "autorização, estrutura societária, escopo dos serviços, custódia/intermediação e risco de transição.",
        "CVM": "participação em receitas, direito de voto, captação, expectativa de lucro do investidor e oferta pública.",
        "COAF": "limites de KYC, transações anônimas, PEP, monitoramento transacional e comunicação/escalonamento.",
        "Lei 14.478": "caracterização da PSAV, escopo de ativo virtual, competência regulatória e relação com BCB/CVM/COAF.",
        "Segregação": "separação de carteiras/contas, proof of reserves, contratos de custódia, reconciliação e proteção em insolvência.",
    }

    if lang == "pt":
        kicker = "Check regulatório selecionado"
        focus = focus_pt.get(label, meta.get("focus", "Carrega uma consulta regulatória no campo principal."))
        inspect = inspect_pt.get(label, meta.get("inspect", "o perímetro regulatório e as evidências de controle."))
        inspect_label = "O que este check vai investigar"
        context_label = "Contexto do prompt inicial"
        query_label = "Consulta carregada"
        relation_label = "Como usar"
        relation = "A consulta foi colocada no campo principal. Clique em Analyze para rodar uma nova análise contra o índice regulatório, usando este novo ângulo como aprofundamento do caso inicial."
    else:
        kicker = "Quick regulatory check selected"
        focus = meta.get("focus", "Loads a regulatory test query into the main input.")
        inspect = meta.get("inspect", "the relevant regulatory perimeter and control evidence.")
        inspect_label = "What this check will inspect"
        context_label = "Initial prompt context"
        query_label = "Loaded example query"
        relation_label = "How to use"
        relation = "The query was placed in the main input. Click Analyze to run a new assessment against the regulatory index using this new angle as a follow-up to the original case."

    related = ""
    if current_prompt:
        related = f"""
        <div class="quick-detail-mini">
          <div class="quick-detail-label">{esc(context_label)}</div>
          <div class="quick-detail-text">{esc(current_prompt[:420])}</div>
        </div>
        """

    return f"""
<div class="quick-detail-card">
  <div class="quick-detail-kicker">{esc(kicker)}</div>
  <div class="quick-detail-title">{esc(title)}</div>
  <div class="quick-detail-body">{esc(focus)}</div>
  <div class="quick-detail-mini">
    <div class="quick-detail-label">{esc(inspect_label)}</div>
    <div class="quick-detail-text">{esc(inspect)}</div>
  </div>
  {related}
  <div class="quick-detail-mini quick-detail-query">
    <div class="quick-detail-label">{esc(query_label)}</div>
    <div class="quick-detail-text">{esc(loaded_query)}</div>
  </div>
  <div class="quick-detail-hint"><b>{esc(relation_label)}:</b> {esc(relation)}</div>
</div>
"""


def load_shortcut_with_detail(label: str, current_prompt: str = "", analyzed_prompt: str = "") -> tuple[str, str]:
    """Load a quick check and show extra context tied to the original analyzed prompt."""
    query = load_shortcut(label)
    context_prompt = str(analyzed_prompt or "").strip() or str(current_prompt or "").strip()
    return query, render_quick_check_detail(label, query, context_prompt)


def empty_followup_outputs():
    """Return blank updates for the recommendation button panel."""
    hidden_header = gr.update(value="", visible=False)
    hidden_buttons = [gr.update(value="", visible=False) for _ in range(3)]
    return hidden_header, [], *hidden_buttons


def analyze(query: str):
    hidden_download = ""
    empty_detail = ""
    empty_state = ""
    followup_header, followup_state, f1, f2, f3 = empty_followup_outputs()

    if not query or not query.strip():
        return (
            render_error("Please enter a compliance query."),
            "",
            hidden_download,
            followup_header,
            followup_state,
            f1,
            f2,
            f3,
            empty_detail,
            empty_state,
        )

    query = query.strip()
    lang = detect_language(query)
    print("\n" + "=" * 72, flush=True)
    print(f"NEW QUERY [{lang.upper()}]: {query}", flush=True)

    results = retrieve(query)
    print(f"Retrieved chunks: {len(results)}", flush=True)
    for i, r in enumerate(results, 1):
        print(
            f"[RAG {i}] source_id={r.get('source_id')} | "
            f"authority={r.get('authority')} | "
            f"article_hint={r.get('article_hint')} | "
            f"normative_reference_hint={r.get('normative_reference_hint')} | "
            f"final_score={float(r.get('_final', 0.0)):.3f}",
            flush=True,
        )

    if not results:
        return (
            render_error("No relevant regulatory chunks found. Try rephrasing your query."),
            "",
            hidden_download,
            followup_header,
            followup_state,
            f1,
            f2,
            f3,
            empty_detail,
            query,
        )

    context = format_context(results)
    report = call_claude(query, context)
    if not report:
        context_path = write_context_file(query, context, results, report=None)
        return (
            render_error("Could not reach Claude API. Check that ANTHROPIC_API_KEY is set as a Space Secret."),
            render_evidence_summary(results),
            render_context_download(context_path),
            followup_header,
            followup_state,
            f1,
            f2,
            f3,
            empty_detail,
            query,
        )

    report = canonicalize_report(report, results)
    print(
        "FINAL NORMALIZED REPORT LEGAL ARRAYS: "
        f"applicable_regulations={report.get('applicable_regulations')!r}; "
        f"relevant_articles={report.get('relevant_articles')!r}",
        flush=True,
    )

    followups = as_list(report.get("suggested_followups"))
    if not followups:
        followups = infer_followups(query, results, lang)
        print(f"[WARN] suggested_followups empty; filled from fallback: {followups!r}", flush=True)

    followup_header, followup_state, f1, f2, f3 = make_followup_button_updates(followups, lang)
    context_path = write_context_file(query, context, results, report=report)

    return (
        render_report(report, query, results),
        render_evidence_summary(results),
        render_context_download(context_path),
        followup_header,
        followup_state,
        f1,
        f2,
        f3,
        empty_detail,
        query,
    )


CSS = """
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;700&family=IBM+Plex+Sans:wght@300;400;600&display=swap');
body { background: #0a0f1e !important; }
.gradio-container {
    background: #0a0f1e !important;
    font-family: 'IBM Plex Sans', sans-serif !important;
    max-width: 900px !important;
    margin: 0 auto !important;
}
#header {
    text-align: center;
    padding: 2rem 0 1rem;
    border-bottom: 1px solid #1e3a5f;
    margin-bottom: 1.5rem;
}
#header h1 {
    font-family: 'IBM Plex Mono', monospace;
    font-size: 1.8rem;
    color: #38bdf8;
    letter-spacing: -0.02em;
    margin: 0 0 0.3rem;
}
#header p {
    color: #94a3b8;
    font-size: 0.86rem;
    margin: 0;
}
.input-panel {
    background: #0f172a;
    border: 1px solid #1e3a5f;
    border-radius: 14px;
    padding: 1rem;
    margin-bottom: 0.75rem;
}
.query-box textarea {
    background: #0b1220 !important;
    border: 1px solid #1e3a5f !important;
    color: #e2e8f0 !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-size: 0.9rem !important;
    border-radius: 8px !important;
}
.query-box textarea:focus {
    border-color: #38bdf8 !important;
    box-shadow: 0 0 0 2px rgba(56,189,248,0.15) !important;
}
.analyze-btn {
    background: #0369a1 !important;
    color: #fff !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-weight: 700 !important;
    letter-spacing: 0.05em !important;
    border: none !important;
    border-radius: 8px !important;
    height: 44px !important;
    font-size: 0.85rem !important;
    transition: background 0.2s !important;
}
.analyze-btn:hover { background: #0284c7 !important; }
.shortcut-panel {
    background: transparent;
    border: 1px solid #172554;
    border-radius: 12px;
    padding: 0.75rem 0.85rem;
    margin: 0.3rem 0 1.1rem;
}
.shortcut-title {
    color: #64748b;
    font-family: 'IBM Plex Mono', monospace;
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    margin-bottom: 0.55rem;
}
.shortcut-row { gap: 0.5rem !important; }
.chip-btn {
    background: #111827 !important;
    color: #93c5fd !important;
    border: 1px solid #1e3a5f !important;
    border-radius: 999px !important;
    min-height: 34px !important;
    height: 34px !important;
    padding: 0 0.85rem !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-size: 0.78rem !important;
    font-weight: 600 !important;
    box-shadow: none !important;
}
.chip-btn:hover {
    background: #1e3a5f !important;
    color: #dbeafe !important;
    border-color: #38bdf8 !important;
}
.context-box textarea {
    background: #0f172a !important;
    border: 1px solid #1e293b !important;
    color: #cbd5e1 !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-size: 0.75rem !important;
}

.followup-panel,
.followup-panel-shell {
    background: #0f172a !important;
    border: 1px solid #1e3a5f !important;
    border-radius: 16px !important;
    padding: 1rem !important;
    margin: 1rem 0 0.55rem !important;
    box-shadow: 0 0 0 1px rgba(56,189,248,0.04) inset !important;
}
.followup-panel-copy {
    font-family: 'IBM Plex Mono', monospace;
    background: transparent;
    margin-bottom: 0.65rem;
}
.followup-panel-kicker {
    color: #38bdf8;
    font-size: 0.76rem;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    margin-bottom: 0.35rem;
}
.followup-panel-subtitle {
    color: #cbd5e1;
    font-size: 0.78rem;
    line-height: 1.55;
}
.followup-btn {
    background: #0b1220 !important;
    color: #bfdbfe !important;
    border: 1px solid #26364f !important;
    border-radius: 10px !important;
    min-height: 48px !important;
    height: auto !important;
    padding: 0.65rem 0.8rem !important;
    margin: 0.25rem 0 !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-size: 0.79rem !important;
    font-weight: 500 !important;
    text-align: left !important;
    white-space: normal !important;
    line-height: 1.45 !important;
    box-shadow: none !important;
}
.followup-btn:hover {
    background: #172554 !important;
    color: #eff6ff !important;
    border-color: #38bdf8 !important;
}
.followup-btn span,
.followup-btn div,
.followup-btn p {
    color: inherit !important;
    white-space: normal !important;
    text-align: left !important;
}
.quick-accordion,
.quick-accordion > div,
.quick-accordion details,
.quick-accordion summary,
.quick-accordion .wrap,
.quick-accordion .block {
    background: #0a0f1e !important;
    color: #e2e8f0 !important;
    border-color: #172554 !important;
}
.quick-accordion {
    border: 1px solid #172554 !important;
    border-radius: 14px !important;
    margin-top: 1.1rem !important;
    overflow: hidden !important;
}
.quick-accordion summary {
    color: #dbeafe !important;
    font-family: 'IBM Plex Mono', monospace !important;
    font-size: 0.82rem !important;
    letter-spacing: 0.02em !important;
}
.quick-note {
    background: #0f172a;
    border: 1px solid #1e3a5f;
    color: #cbd5e1;
    border-radius: 12px;
    padding: 0.85rem 1rem;
    margin-bottom: 0.85rem;
    font-family: 'IBM Plex Mono', monospace;
    font-size: 0.78rem;
    line-height: 1.55;
}
.quick-note-title {
    color: #38bdf8;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    font-size: 0.7rem;
    margin-bottom: 0.25rem;
}
#quick_checks,
#quick_checks details,
#quick_checks summary,
#quick_checks > div,
#quick_checks .wrap,
#quick_checks .block,
#quick_checks .form,
#quick_checks .prose {
    background: #0a0f1e !important;
    color: #e2e8f0 !important;
    border-color: #172554 !important;
}
#quick_checks summary {
    color: #dbeafe !important;
}
#quick_checks button {
    box-shadow: none !important;
}

.recommendation-card {
    font-family: 'IBM Plex Mono', monospace;
    background: #0f172a;
    border: 1px solid #1e3a5f;
    border-radius: 14px;
    padding: 1rem;
    margin: 0.45rem 0 1rem;
}
.recommendation-kicker,
.quick-detail-kicker {
    color: #38bdf8;
    font-size: 0.72rem;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    margin-bottom: 0.35rem;
}
.recommendation-subtitle,
.quick-detail-body,
.quick-detail-hint,
.recommendation-hint {
    color: #cbd5e1;
    font-size: 0.78rem;
    line-height: 1.55;
    margin-bottom: 0.7rem;
}
.recommendation-mini,
.quick-detail-mini {
    background: #0b1220;
    border: 1px solid #26364f;
    border-radius: 10px;
    padding: 0.7rem;
    margin: 0.55rem 0;
}
.recommendation-next,
.quick-detail-query {
    border-color: #2563eb;
}
.recommendation-mini-label,
.quick-detail-label {
    color: #64748b;
    font-size: 0.68rem;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    margin-bottom: 0.28rem;
}
.recommendation-mini-text,
.quick-detail-text {
    color: #bfdbfe;
    font-size: 0.78rem;
    line-height: 1.5;
    word-break: break-word;
}
.quick-detail-card {
    font-family: 'IBM Plex Mono', monospace;
    background: #0f172a;
    border: 1px solid #1e3a5f;
    border-radius: 14px;
    padding: 1rem;
    margin-top: 0.8rem;
}
.quick-detail-title {
    color: #f8fafc;
    font-size: 0.95rem;
    font-weight: 700;
    margin-bottom: 0.45rem;
}
.file-output {
    background: #0f172a !important;
    border: 1px solid #172554 !important;
    border-radius: 12px !important;
    padding: 0.6rem !important;
    margin: 0.75rem 0 1rem !important;
}
.quick-note {
    color: #cbd5e1;
    font-family: 'IBM Plex Mono', monospace;
    font-size: 0.78rem;
    line-height: 1.55;
    background:#0f172a;
    border:1px solid #172554;
    border-radius:12px;
    padding:0.8rem;
    margin-bottom:0.7rem;
}
label { color: #94a3b8 !important; font-size: 0.8rem !important; }
"""

SHORTCUT_QUERIES = {
    "BCB": "Nossa plataforma presta serviços de compra, venda, custódia e intermediação de criptoativos para clientes no Brasil, mas ainda não possui autorização formal do Banco Central. Quais são os riscos e obrigações aplicáveis?",
    "CVM": "Nosso token concede participação em receitas, direito de voto e será ofertado publicamente a investidores brasileiros. Isso pode caracterizar valor mobiliário ou oferta sujeita à CVM?",
    "COAF": "Permitimos transações pequenas com cadastro simplificado e parte dos clientes pode operar sem identificação completa. Quais controles de PLD/FTP, KYC e comunicação devem ser avaliados?",
    "Lei 14.478": "Qual é o enquadramento regulatório de uma prestadora de serviços de ativos virtuais segundo a Lei 14.478/2022 e normas complementares?",
    "Segregação": "Nossa exchange mantém ativos virtuais de clientes em carteiras misturadas com recursos próprios da empresa. Quais obrigações de segregação patrimonial e custódia devem ser observadas?",
}


def load_shortcut(label: str) -> str:
    return SHORTCUT_QUERIES.get(label, "")


with gr.Blocks(css=CSS, title="RegTech BR") as demo:
    gr.HTML("""
    <div id="header">
      <h1>⚖ RegTech BR</h1>
      <p>AI-assisted screening for Brazilian crypto compliance · BCB · CVM · COAF</p>
    </div>
    """)

    with gr.Group(elem_classes=["input-panel"]):
        with gr.Row():
            with gr.Column(scale=4):
                query_box = gr.Textbox(
                    label="Compliance query or document excerpt",
                    placeholder="Describe a crypto product, policy, control gap, or regulatory question in Portuguese or English...",
                    lines=5,
                    elem_classes=["query-box"],
                )
            with gr.Column(scale=1, min_width=130):
                analyze_btn = gr.Button("Analyze →", elem_classes=["analyze-btn"])

    report_html = gr.HTML(label="Compliance Assessment")

    evidence_html = gr.HTML(label="Evidence retrieved from RAG")

    current_query_state = gr.State("")

    followup_items_state = gr.State([])

    followup_header_html = gr.HTML(value="", visible=False)
    followup_btn_1 = gr.Button("", visible=False, elem_classes=["followup-btn"])
    followup_btn_2 = gr.Button("", visible=False, elem_classes=["followup-btn"])
    followup_btn_3 = gr.Button("", visible=False, elem_classes=["followup-btn"])

    followup_detail_html = gr.HTML(label="Selected recommendation details")

    context_download_html = gr.HTML(label="Download full retrieved regulatory context")

    with gr.Accordion("Quick regulatory checks — guided examples", open=False, elem_id="quick_checks", elem_classes=["quick-accordion"]):
        gr.HTML("""
        <div class="quick-note">
          <div class="quick-note-title">Guided checks</div>
          Use these options when the assessment raises doubts or when you want to test another regulatory angle.
          Each button loads a focused example, explains what it investigates, and keeps the previous prompt as context.
        </div>
        """)
        with gr.Row(elem_classes=["shortcut-row"]):
            bcb_btn = gr.Button("BCB · Authorization", elem_classes=["chip-btn"])
            cvm_btn = gr.Button("CVM · Securities", elem_classes=["chip-btn"])
            coaf_btn = gr.Button("COAF · AML/KYC", elem_classes=["chip-btn"])
            lei_btn = gr.Button("Lei 14.478", elem_classes=["chip-btn"])
            seg_btn = gr.Button("Segregação", elem_classes=["chip-btn"])
        quick_detail_html = gr.HTML(label="Quick check details")

    gr.HTML("""
    <div style="text-align:center;color:#475569;font-size:0.74rem;
                padding:1.5rem 0 0.5rem;font-family:'IBM Plex Mono',monospace">
      ⚠ Experimental compliance screening. Not legal advice. Results require qualified professional review.<br>
      RegTech BR · Fernando Rodrigues · Kaggle: fernandosr85
    </div>
    """)

    bcb_btn.click(fn=lambda current, analyzed: load_shortcut_with_detail("BCB", current, analyzed), inputs=[query_box, current_query_state], outputs=[query_box, quick_detail_html])
    cvm_btn.click(fn=lambda current, analyzed: load_shortcut_with_detail("CVM", current, analyzed), inputs=[query_box, current_query_state], outputs=[query_box, quick_detail_html])
    coaf_btn.click(fn=lambda current, analyzed: load_shortcut_with_detail("COAF", current, analyzed), inputs=[query_box, current_query_state], outputs=[query_box, quick_detail_html])
    lei_btn.click(fn=lambda current, analyzed: load_shortcut_with_detail("Lei 14.478", current, analyzed), inputs=[query_box, current_query_state], outputs=[query_box, quick_detail_html])
    seg_btn.click(fn=lambda current, analyzed: load_shortcut_with_detail("Segregação", current, analyzed), inputs=[query_box, current_query_state], outputs=[query_box, quick_detail_html])

    followup_btn_1.click(fn=lambda items, original: apply_followup_by_index(0, items, original), inputs=[followup_items_state, current_query_state], outputs=[query_box, followup_detail_html])
    followup_btn_2.click(fn=lambda items, original: apply_followup_by_index(1, items, original), inputs=[followup_items_state, current_query_state], outputs=[query_box, followup_detail_html])
    followup_btn_3.click(fn=lambda items, original: apply_followup_by_index(2, items, original), inputs=[followup_items_state, current_query_state], outputs=[query_box, followup_detail_html])

    analyze_outputs = [
        report_html,
        evidence_html,
        context_download_html,
        followup_header_html,
        followup_items_state,
        followup_btn_1,
        followup_btn_2,
        followup_btn_3,
        followup_detail_html,
        current_query_state,
    ]

    analyze_btn.click(fn=analyze, inputs=[query_box], outputs=analyze_outputs)
    query_box.submit(fn=analyze, inputs=[query_box], outputs=analyze_outputs)

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    context_dir = os.environ.get("REGTECH_CONTEXT_DIR", "/tmp/regtech_br_contexts")
    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=port,
        share=True,
        show_api=False,
        allowed_paths=[context_dir],
    )