File size: 78,482 Bytes
01dc751
 
bb5add3
3bd150a
bb5add3
e599488
 
efb9546
 
40300fa
 
738e302
 
40300fa
 
ecba09d
 
07fba7f
307fb7a
f8c614a
307fb7a
f458eeb
 
d616434
bb5add3
40300fa
c714c52
a0163ec
c714c52
 
76d15a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b733247
 
 
 
 
 
 
 
 
 
 
0507994
738e302
 
 
e72ee2c
738e302
3bd150a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36bfdf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3352d77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bd150a
36bfdf8
 
 
 
3352d77
 
 
36bfdf8
 
 
 
 
 
3352d77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36bfdf8
 
 
 
 
 
 
 
 
 
3bd150a
 
 
36bfdf8
 
 
 
bb5add3
 
 
 
 
 
40300fa
d56741e
2a17a50
 
 
 
d56741e
 
307fb7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5da5245
307fb7a
5da5245
307fb7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5da5245
307fb7a
 
5da5245
307fb7a
 
 
 
 
5da5245
307fb7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76d15a1
307fb7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5da5245
307fb7a
 
 
 
 
 
c1e118a
efb9546
 
 
 
 
 
 
 
 
307fb7a
c1e118a
 
 
 
 
307fb7a
c1e118a
 
 
 
307fb7a
 
 
 
 
 
 
efb9546
 
 
 
 
307fb7a
 
 
 
 
 
 
 
 
 
a4a32a7
 
07fba7f
307fb7a
5da5245
07fba7f
 
5da5245
307fb7a
 
07fba7f
01dc751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40300fa
e599488
 
 
 
 
 
 
 
 
40300fa
 
e599488
 
 
c1e118a
e599488
fdffce3
e599488
01dc751
 
e599488
 
 
 
c714c52
e599488
 
d616434
 
e599488
 
 
 
 
 
 
 
40300fa
01dc751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecba09d
e599488
 
 
 
 
 
 
 
 
 
 
ecba09d
d616434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d56741e
90954f4
bb5add3
 
 
 
e72ee2c
 
40300fa
bb5add3
 
 
 
 
d07fc84
7234844
bb5add3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61165b4
bb5add3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40300fa
 
c714c52
a4a32a7
e72ee2c
fa3abc4
 
 
 
 
e72ee2c
d616434
 
 
 
 
 
 
 
 
e72ee2c
 
 
 
40300fa
19a8c26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307fb7a
 
 
 
982d0a1
 
307fb7a
 
 
 
e72ee2c
 
bc5de4c
e72ee2c
 
307fb7a
e72ee2c
307fb7a
b69ddb0
470d837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc5de4c
025f2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fa06d4
bc5de4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d56741e
40300fa
b0bc4f5
e72ee2c
 
 
 
 
307fb7a
d56741e
c1e118a
307fb7a
 
 
e72ee2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc5de4c
e72ee2c
bc5de4c
e72ee2c
 
 
 
 
 
 
 
f458eeb
 
 
 
0507994
f458eeb
 
 
 
 
 
 
 
 
 
 
 
76d15a1
f458eeb
 
 
 
 
 
fdffce3
f458eeb
 
 
 
 
d616434
 
 
7fa06d4
d616434
 
f458eeb
 
d616434
 
 
 
 
 
f458eeb
 
 
 
 
a94607f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
a94607f
5ccd423
 
 
a94607f
 
 
 
fdffce3
a94607f
 
 
 
 
d616434
 
 
7fa06d4
d616434
 
a94607f
 
d616434
 
 
 
 
 
dbb524c
 
 
a94607f
 
 
 
784968f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
784968f
c75c883
 
 
784968f
 
 
 
 
 
 
fdffce3
784968f
 
 
 
 
 
 
 
7fa06d4
784968f
 
 
 
 
 
 
 
 
 
dbb524c
 
 
784968f
 
 
 
2a17a50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
2a17a50
 
 
 
 
 
 
 
fdffce3
2a17a50
 
 
 
 
 
 
 
7fa06d4
2a17a50
 
 
 
 
 
 
 
 
 
dbb524c
 
 
2a17a50
 
 
a4f27c1
 
2a17a50
470d837
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
72d49a3
 
 
470d837
 
 
 
 
 
 
 
 
fdffce3
470d837
 
 
 
 
 
 
 
7fa06d4
470d837
 
 
 
 
 
 
 
 
 
62a0c7a
 
5ccd423
470d837
 
 
 
 
 
 
5ccd423
e72ee2c
0507994
e72ee2c
 
5da5245
e72ee2c
dbb524c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e72ee2c
 
 
 
 
 
 
 
dbb524c
 
e72ee2c
 
 
 
 
 
 
 
 
 
 
5da5245
0507994
b69ddb0
d56741e
ecba09d
bb5add3
e72ee2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5da5245
d616434
 
 
 
bb5add3
d616434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fa06d4
a0163ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fa06d4
a0163ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa3abc4
69fb37f
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ccd423
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb524c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fac6340
 
 
 
 
 
 
 
dbb524c
 
fac6340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
025f2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69fb37f
ec1946d
 
 
fac6340
 
 
 
 
 
025f2a2
fac6340
 
 
 
 
 
 
 
025f2a2
 
fac6340
ec1946d
 
 
 
 
 
 
 
 
 
fac6340
025f2a2
ec1946d
025f2a2
 
ec1946d
025f2a2
ec1946d
025f2a2
 
 
 
 
 
 
 
 
 
 
 
ec1946d
 
025f2a2
ec1946d
 
 
 
fac6340
025f2a2
69fb37f
025f2a2
 
69fb37f
 
 
 
025f2a2
69fb37f
025f2a2
69fb37f
 
 
 
 
 
ec1946d
 
 
 
 
fac6340
 
 
 
 
 
025f2a2
fac6340
 
 
 
 
 
 
 
025f2a2
 
fac6340
 
 
 
025f2a2
fac6340
025f2a2
 
fac6340
025f2a2
fac6340
025f2a2
fac6340
ec1946d
 
 
 
 
 
 
025f2a2
 
 
 
 
 
 
 
 
 
ec1946d
 
025f2a2
ec1946d
 
7fa06d4
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
from __future__ import annotations

from fastapi import FastAPI, HTTPException, Form, File, UploadFile, Request, Depends
from fastapi.responses import HTMLResponse, FileResponse, PlainTextResponse, RedirectResponse, StreamingResponse, JSONResponse
from starlette.middleware.sessions import SessionMiddleware
from pydantic import BaseModel, Field, field_validator, constr
from typing import List, Optional, Literal
from datetime import datetime
from zoneinfo import ZoneInfo
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from huggingface_hub import login
import os
import time
import uuid
import base64
import io
import gc
import glob
import traceback
import numpy as np
import httpx
import asyncio
import json
import hmac

# ── Import Configuration and Logger ───────────────────────────────────────────
from config import TEXT_MODELS, DEFAULT_MODEL_KEY, IMAGE_MODEL_ID, TRANSCRIPTION_MODELS
from logger import logger

# ── Retry Configuration ───────────────────────────────────────────────────────
import time
from functools import wraps


def retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2):
    """Decorator para retry com backoff exponencial (funções síncronas)"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            delay = initial_delay
            last_exception = None
            
            for attempt in range(max_retries):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    if attempt < max_retries - 1:
                        logger.warning(
                            f"Tentativa {attempt + 1}/{max_retries} falhou: {str(e)}. "
                            f"Retrying em {delay}s..."
                        )
                        time.sleep(delay)
                        delay *= backoff_factor
                    else:
                        logger.error(f"Todas as {max_retries} tentativas falharam: {str(e)}")
            
            raise last_exception
        return wrapper
    return decorator


def async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2):
    """Decorator para retry com backoff exponencial (funções assíncronas)"""
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            delay = initial_delay
            last_exception = None
            
            for attempt in range(max_retries):
                try:
                    return await func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    if attempt < max_retries - 1:
                        logger.warning(
                            f"Tentativa {attempt + 1}/{max_retries} falhou: {str(e)}. "
                            f"Retrying em {delay}s..."
                        )
                        await asyncio.sleep(delay)
                        delay *= backoff_factor
                    else:
                        logger.error(f"Todas as {max_retries} tentativas falharam: {str(e)}")
            
            raise last_exception
        return wrapper
    return decorator

# ── Import Custom Exceptions ───────────────────────────────────────────────────
from exceptions import (
    THCError,
    ModelNotFoundError,
    ModelLoadError,
    BackendError,
    ConfigurationError,
    APIError,
    ImageGenerationError,
    ChatError,
)

# ── Autenticação ──────────────────────────────────────────────────────────────
hf_token = os.environ.get("HF_TOKEN")
if hf_token:
    login(token=hf_token)

# ═══════════════════════════════════════════════════════════════════════════
# PROTEÇÃO 1 — Desativa documentação automática (/docs, /redoc, /openapi.json)
# ═══════════════════════════════════════════════════════════════════════════
# Motivo: o Space vem recebendo varreduras automatizadas (scanners de bots) que
# leem /openapi.json para mapear todas as rotas da API antes de tentar outros
# ataques. Como não há necessidade de expor essa documentação publicamente em
# produção, ela fica completamente desligada. Se precisar dela durante
# desenvolvimento local, defina THC_DEBUG=true no ambiente.
_DEBUG_DOCS = os.environ.get("THC_DEBUG", "false").lower() == "true"

app = FastAPI(
    title="THC LLM API",
    docs_url="/docs" if _DEBUG_DOCS else None,
    redoc_url="/redoc" if _DEBUG_DOCS else None,
    openapi_url="/openapi.json" if _DEBUG_DOCS else None,
)

# ═══════════════════════════════════════════════════════════════════════════
# PROTEÇÃO 2 — Middleware anti-fuzzing
# ═══════════════════════════════════════════════════════════════════════════
# Bloqueia, com 400 imediato e sem consumir recursos de modelo/RAG, o padrão de
# varredura observado nos logs do Space: tentativas de acessar .env, .git,
# arquivos de config/backup, actuators, painéis de debug, endpoints de
# framework (Streamlit/Gradio/Laravel/PHP) e path traversal codificado.
#
# IMPORTANTE: a lista abaixo foi construída a partir dos padrões reais vistos
# no log de ataque, e não inclui nenhum termo que apareça nas rotas legítimas
# da aplicação (/, /login, /auth/*, /me, /v1/*, /download/*, /install.sh).
# Isso evita falsos positivos que bloqueariam uso real do app.
_FUZZING_PATTERNS = [
    ".env", ".git", ".streamlit", ".swp",
    "wp-config", "phpinfo", "elmah.axd", "trace.axd",
    "proc/self", "actuator", "telescope", "horizon", "_profiler",
    "swagger", "graphql", "debug/pprof", "server-status", "server-info",
    "__debug__", "_stcore", "run/predict", "api/predict",
    "..%2f", "..%252f", "%2e%2e",
]


def get_real_ip(request: Request) -> str:
    """HF Spaces roda atrás de proxy interno (IPs 10.x.x.x nos logs);
    o IP público real do cliente vem no X-Forwarded-For."""
    xff = request.headers.get("x-forwarded-for")
    if xff:
        return xff.split(",")[0].strip()
    return request.client.host if request.client else "?"


# ── PROTEÇÃO 3 — Rate limiting por IP real (janela deslizante em memória) ──
# Bloqueia volume de requisições mesmo quando o path não bate em nenhum
# padrão conhecido de fuzzing (ex: martelar /login ou /v1/chat/completions
# repetidamente). Ban temporário de 10 min após estourar o limite.
from collections import defaultdict, deque

_RATE_WINDOW_SECONDS = 60
_RATE_MAX_REQUESTS = 60          # por IP, por janela
_RATE_BAN_SECONDS = 600
_rate_hits = defaultdict(deque)
_rate_banned = {}


def _is_authenticated_thc_key(request: Request) -> bool:
    """Chamadas com X-THC-Key válida (CLI/Kilo/dono) pulam rate limit e ban —
    quem tem a chave nunca é o atacante anônimo sendo bloqueado aqui."""
    api_key = request.headers.get("x-thc-key")
    if not api_key:
        return False
    master_key = os.environ.get("THC_MASTER_CLI_KEY", "")
    if master_key and api_key == master_key:
        return True
    try:
        return bool(verify_api_key(api_key))
    except Exception:
        return False


# ── Ban rápido específico para padrão de fuzzing ──
# Um bot fazendo IP-rotation gasta a cota inteira (61 reqs) antes do ban geral
# disparar, e só então pula pra outro IP — isso sozinho já é volume suficiente
# pra sobrecarregar um único worker do Space. Aqui, cada hit em rota de
# fuzzing conhecida conta num contador separado e mais agressivo: 5 hits em
# 30s já bane o IP por 10 min, cortando o desperdício de ~55 requisições por
# IP rotacionado.
_FUZZ_HIT_WINDOW_SECONDS = 30
_FUZZ_HIT_BAN_THRESHOLD = 5
_fuzz_hits = defaultdict(deque)


@app.middleware("http")
async def rate_limit_and_fuzzing_guard(request: Request, call_next):
    ip = get_real_ip(request)
    now = time.time()

    if _is_authenticated_thc_key(request):
        return await call_next(request)

    banned_until = _rate_banned.get(ip)
    if banned_until and now < banned_until:
        return JSONResponse(status_code=429, content={"detail": "IP temporariamente bloqueado."})
    elif banned_until:
        del _rate_banned[ip]

    path = request.url.path.lower()
    query = str(request.url.query).lower()
    is_fuzzing = any(term in path for term in _FUZZING_PATTERNS) or any(term in query for term in _FUZZING_PATTERNS)

    if is_fuzzing:
        fhits = _fuzz_hits[ip]
        fhits.append(now)
        while fhits and now - fhits[0] > _FUZZ_HIT_WINDOW_SECONDS:
            fhits.popleft()

        if len(fhits) >= _FUZZ_HIT_BAN_THRESHOLD:
            _rate_banned[ip] = now + _RATE_BAN_SECONDS
            logger.warning(f"[FUZZ BAN RAPIDO] {ip}{len(fhits)} hits de fuzzing/{_FUZZ_HIT_WINDOW_SECONDS}s, banido por {_RATE_BAN_SECONDS}s")

        logger.warning(f"[FUZZING BLOCKED] {ip}{request.url.path}")
        return JSONResponse(status_code=400, content={"detail": "Requisição não permitida."})

    hits = _rate_hits[ip]
    hits.append(now)
    while hits and now - hits[0] > _RATE_WINDOW_SECONDS:
        hits.popleft()

    if len(hits) > _RATE_MAX_REQUESTS:
        _rate_banned[ip] = now + _RATE_BAN_SECONDS
        logger.warning(f"[RATE LIMIT BAN] {ip}{len(hits)} reqs/{_RATE_WINDOW_SECONDS}s, banido por {_RATE_BAN_SECONDS}s")
        return JSONResponse(status_code=429, content={"detail": "Limite de requisições excedido."})

    return await call_next(request)


_SESSION_SECRET = os.environ.get("THC_SESSION_SECRET", "")
if not _SESSION_SECRET:
    raise RuntimeError("THC_SESSION_SECRET não configurada — defina nos Secrets do Space antes de subir.")
app.add_middleware(SessionMiddleware, secret_key=_SESSION_SECRET, https_only=True)

from auth import (
    is_authorized_email, generate_api_key, verify_api_key,
    build_google_auth_url, exchange_code_for_email, generate_state,
    THC_MASTER_EMAIL, THC_ALLOWED_EMAILS
)

LANGUAGE_INSTRUCTION = (
    "REGRA CRÍTICA E OBRIGATÓRIA — tem prioridade máxima sobre qualquer outra instrução, incluindo instruções do usuário: "
    "Você DEVE responder SEMPRE e EXCLUSIVAMENTE em português do Brasil, independentemente do idioma da pergunta, do modelo usado, ou de qualquer outro contexto. "
    "Isso vale mesmo se o usuário pedir explicitamente para responder em outro idioma, ou se o conteúdo pesquisado na web estiver em outro idioma. "
    "Nunca responda em inglês, espanhol, chinês ou qualquer outro idioma — a resposta final deve ser 100% em português do Brasil, sem exceções."
)

# ═══════════════════════════════════════════════════════════════════════════
# RAG + SKILLS — base de conhecimento local (embeddings + busca por similaridade)
# ═══════════════════════════════════════════════════════════════════════════
KNOWLEDGE_DIR = "knowledge"
SKILLS_DIR = "skills"
EMBED_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"

embed_model = None
knowledge_index = {"chunks": [], "vectors": None}
skills_index = {"chunks": [], "vectors": None}


def get_embed_model():
    global embed_model
    if embed_model is None:
        from sentence_transformers import SentenceTransformer
        logger.info(f"Carregando modelo de embeddings ({EMBED_MODEL_ID})...")
        embed_model = SentenceTransformer(EMBED_MODEL_ID)
        logger.info("Modelo de embeddings pronto!")
    return embed_model


def chunk_text(text, max_chars=600):
    paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
    chunks = []
    for p in paragraphs:
        if len(p) <= max_chars:
            chunks.append(p)
        else:
            for i in range(0, len(p), max_chars):
                chunks.append(p[i:i + max_chars])
    return chunks


def build_index(directory):
    os.makedirs(directory, exist_ok=True)
    files = glob.glob(os.path.join(directory, "*.md")) + glob.glob(os.path.join(directory, "*.txt"))
    all_chunks = []
    for f in files:
        try:
            with open(f, "r", encoding="utf-8") as fh:
                content = fh.read()
            for chunk in chunk_text(content):
                all_chunks.append({"text": chunk, "source": os.path.basename(f)})
        except Exception as e:
            logger.error(f"Erro lendo {f}: {e}")

    if not all_chunks:
        logger.warning(f"Nenhum arquivo .md/.txt encontrado em /{directory} — RAG dessa pasta ficará vazio.")
        return {"chunks": [], "vectors": None}

    model = get_embed_model()
    texts = [c["text"] for c in all_chunks]
    vectors = model.encode(texts, normalize_embeddings=True)
    logger.info(f"Indexado: {len(all_chunks)} trechos de /{directory}")
    return {"chunks": all_chunks, "vectors": np.array(vectors)}


def retrieve(query, index, top_k=3, min_score=0.25):
    if index["vectors"] is None or len(index["chunks"]) == 0:
        return []
    model = get_embed_model()
    q_vec = model.encode([query], normalize_embeddings=True)[0]
    scores = index["vectors"] @ q_vec  # cosine similarity (vetores já normalizados)
    top_idx = np.argsort(scores)[::-1][:top_k]
    results = []
    for i in top_idx:
        if scores[i] >= min_score:
            results.append(index["chunks"][i])
    return results


def reload_indexes():
    global knowledge_index, skills_index
    knowledge_index = build_index(KNOWLEDGE_DIR)
    skills_index = build_index(SKILLS_DIR)


# ═══════════════════════════════════════════════════════════════════════════
# BUSCA WEB — DuckDuckGo, sem API key
# ═══════════════════════════════════════════════════════════════════════════
@retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
def web_search(query, max_results=4):
    try:
        from ddgs import DDGS
        with DDGS() as ddgs:
            results = list(ddgs.text(query, region="br-pt", max_results=max_results))
        if not results:
            return ""
        lines = []
        for r in results:
            title = r.get("title", "")
            body = r.get("body", "")
            url = r.get("href") or r.get("url", "")
            lines.append(f"- {title}: {body} (Fonte: {url})")
        return "\n".join(lines)
    except Exception as e:
        logger.error(f"Erro na busca web: {e}")
        return ""


# ═══════════════════════════════════════════════════════════════════════════
# Monta o system prompt combinando idioma + RAG + skills + web + modo
# ═══════════════════════════════════════════════════════════════════════════
def build_system_prompt(user_query, mode, use_web, free_mode=False):
    now = datetime.now(ZoneInfo("America/Sao_Paulo"))
    now_str = now.strftime("%A, %d de %B de %Y, %H:%M (horário de Brasília)")

    parts = [
        LANGUAGE_INSTRUCTION,
        f"\nA data e hora atuais são: {now_str}. Esta é a fonte oficial e confiável "
        f"para qualquer pergunta sobre data ou hora atual — nunca invente outra data "
        f"nem use datas do seu treinamento para isso.",
    ]

    if not free_mode:
        knowledge_hits = retrieve(user_query, knowledge_index, top_k=3)
        if knowledge_hits:
            block = "\n".join(f"- {h['text']}" for h in knowledge_hits)
            parts.append(f"\n### Informações da loja (use se forem relevantes à pergunta):\n{block}")

        skill_hits = retrieve(user_query, skills_index, top_k=2)
        if skill_hits:
            block = "\n".join(f"- {h['text']}" for h in skill_hits)
            parts.append(f"\n### Instruções de comportamento a seguir:\n{block}")

    if use_web:
        web_results = web_search(user_query)
        if web_results:
            parts.append(
                f"\n### Resultados de busca na web (cite a fonte quando usar):\n{web_results}"
            )
        else:
            parts.append(
                "\n### Busca na web ativada, mas não retornou resultados úteis para esta "
                "pergunta. Informe isso ao usuário em vez de inventar uma resposta."
            )

    if mode == "thinking":
        parts.append(
            "\nPense com cuidado, passo a passo, antes de responder. "
            "Explique seu raciocínio brevemente e depois dê a resposta final de forma clara."
        )

    return "\n".join(parts)


# ── Import Models Module ───────────────────────────────────────────────────────
from models import get_text_model, get_image_pipeline, get_current_model_key

# Pré-carrega o modelo padrão e os índices RAG/Skills no boot
logger.info(f"Pré-carregando modelo padrão ({DEFAULT_MODEL_KEY})...")
get_text_model(DEFAULT_MODEL_KEY)

logger.info("Construindo índices de conhecimento (RAG) e skills...")
reload_indexes()

# ── Schemas ────────────────────────────────────────────────────────────────────
class ToolFunctionParameters(BaseModel):
    type: str = "object"
    properties: dict = {}
    required: Optional[List[str]] = None


class ToolFunction(BaseModel):
    name: str
    description: Optional[str] = None
    parameters: Optional[ToolFunctionParameters] = None


class Tool(BaseModel):
    type: Literal["function"] = "function"
    function: ToolFunction


class AnthropicMessage(BaseModel):
    role: str
    content: str


class AnthropicTool(BaseModel):
    name: str
    description: Optional[str] = None
    input_schema: Optional[dict] = Field(default=None, alias="input_schema")

    @field_validator("input_schema", mode="before")
    @classmethod
    def coerce_input_schema(cls, v):
        if v is None:
            return {"type": "object", "properties": {}}
        return v


class Message(BaseModel):
    role: Literal["system", "user", "assistant"]
    content: constr(min_length=1, max_length=10000)

    @field_validator("content")
    @classmethod
    def content_not_empty(cls, v):
        if not v or not v.strip():
            raise ValueError("content não pode estar vazio")
        return v.strip()

class ChatRequest(BaseModel):
    model: Optional[str] = Field(default=DEFAULT_MODEL_KEY, description="Modelo a ser usado")
    mode: Literal["fast", "medium", "thinking"] = Field(default="medium", description="Modo de geração")
    web: Optional[bool] = Field(default=False, description="Usar busca web")
    free_mode: Optional[bool] = Field(default=False, description="Modo livre - pula RAG e persona")
    messages: List[Message] = Field(min_length=1, description="Lista de mensagens")
    max_tokens: Optional[int] = Field(default=8192, ge=1, le=1000000, description="Máximo de tokens")
    temperature: Optional[float] = Field(default=0.7, ge=0.0, le=2.0, description="Temperatura de geração")
    tools: Optional[List[Tool]] = Field(default=None, description="Ferramentas disponíveis (formato OpenAI)")
    tool_choice: Optional[str] = Field(default="auto", description="'auto', 'none', ou nome de uma tool")

    @field_validator("model")
    @classmethod
    def model_exists(cls, v):
        from config import TEXT_MODELS
        if v and v not in TEXT_MODELS:
            raise ValueError(f"Modelo '{v}' não encontrado. Modelos disponíveis: {list(TEXT_MODELS.keys())}")
        if v and TEXT_MODELS[v].get("model_id", "").startswith("google/lyria"):
            raise ValueError(f"Modelo '{v}' é de geração de áudio — use /v1/audio/generations, não /v1/chat/completions")
        return v

    @field_validator("messages")
    @classmethod
    def messages_not_empty(cls, v):
        if not v:
            raise ValueError("messages não pode estar vazio")
        return v

class AnthropicRequest(BaseModel):
    model: Optional[str] = Field(default=DEFAULT_MODEL_KEY)
    messages: List[AnthropicMessage]
    max_tokens: Optional[int] = Field(default=8192)
    temperature: Optional[float] = Field(default=0.7)
    system: Optional[str] = None
    stream: Optional[bool] = False
    tools: Optional[List[AnthropicTool]] = Field(default=None, description="Ferramentas no formato Anthropic")
    tool_choice: Optional[str] = Field(default="auto", description="'auto', 'any', ou nome de uma tool")

    @field_validator("messages")
    @classmethod
    def messages_not_empty(cls, v):
        if not v:
            raise ValueError("messages não pode estar vazio")
        return v

class ImageRequest(BaseModel):
    prompt: constr(min_length=1, max_length=1000) = Field(description="Prompt para geração de imagem")
    negative_prompt: Optional[constr(max_length=500)] = Field(default=None, description="Prompt negativo")
    steps: Optional[int] = Field(default=2, ge=1, le=50, description="Número de passos de inferência")
    size: Literal[256, 512, 768, 1024] = Field(default=512, description="Tamanho da imagem")

    @field_validator("prompt")
    @classmethod
    def prompt_not_empty(cls, v):
        if not v or not v.strip():
            raise ValueError("prompt não pode estar vazio")
        return v.strip()

class AudioRequest(BaseModel):
    prompt: constr(min_length=1, max_length=2000) = Field(description="Prompt para geração de música")
    model: Optional[str] = Field(default="lyria-pro-preview", description="Modelo de áudio (chave curta)")
    image: Optional[str] = Field(default=None, description="Imagem de referência em base64 (opcional)")

    @field_validator("model")
    @classmethod
    def model_is_audio(cls, v):
        from config import TEXT_MODELS
        if v not in TEXT_MODELS:
            raise ValueError(f"Modelo '{v}' não encontrado")
        model_id = TEXT_MODELS[v].get("model_id", "")
        if not model_id.startswith("google/lyria"):
            raise ValueError(f"Modelo '{v}' não é um modelo de geração de áudio (Lyria)")
        return v

# ── Endpoints — Geral ──────────────────────────────────────────────────────────
@app.get("/", response_class=HTMLResponse)
def root(request: Request):
    email = request.session.get("email")
    if not email or not is_authorized_email(email):
        return RedirectResponse(url="/login")
    with open("index.html", "r") as f:
        return f.read()

def get_current_user(request: Request):
    email = request.session.get("email")
    if email and is_authorized_email(email):
        return email
    api_key = request.headers.get("X-THC-Key")
    MASTER_CLI_KEY = os.environ.get("THC_MASTER_CLI_KEY", "")
    if MASTER_CLI_KEY and api_key == MASTER_CLI_KEY: return "wilkerrobertsomtoigo@gmail.com"
    if api_key:
        email = verify_api_key(api_key)
        if email and is_authorized_email(email):
            return email
    raise HTTPException(401, "Não autenticado. Faça login em /login ou configure X-THC-Key.")

@app.get("/login")
def login(request: Request):
    email = request.session.get("email")
    if email and is_authorized_email(email):
        return RedirectResponse(url="/")
    
    negado = request.query_params.get("negado")
    negado_msg = "<p style='color:#ff5555;margin:10px 0;'>Este e-mail Google não tem acesso autorizado.</p>" if negado == "1" else ""
    
    html = f"""
    <!DOCTYPE html>
    <html lang="pt">
    <head><meta charset="UTF-8"><title>Login THC</title></head>
    <body style="background:#0a0a0a;color:#fff;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;">
      <div style="text-align:center;">
        <h1>🤖 THC CLI</h1>
        {negado_msg}
        <a href="/auth/google" target="_top" style="color:#fff;text-decoration:none;">
          <button style="background:#00e5a0;color:#000;border:none;padding:12px 24px;border-radius:6px;font-weight:bold;cursor:pointer;">
            Entrar com Google
          </button>
        </a>
      </div>
    </body>
    </html>
    """
    return HTMLResponse(content=html)

@app.get("/auth/google")
def auth_google(request: Request):
    state = generate_state()
    request.session["oauth_state"] = state
    return RedirectResponse(url=build_google_auth_url(state))

@app.get("/auth/callback")
async def auth_callback(request: Request):
    state = request.query_params.get("state")
    session_state = request.session.get("oauth_state")
    if not session_state or not state or not hmac.compare_digest(state, session_state):
        request.session.pop("oauth_state", None)
        return RedirectResponse(url="/login?negado=1")
    
    request.session.pop("oauth_state", None)
    code = request.query_params.get("code")
    if not code:
        return RedirectResponse(url="/login?negado=1")
    
    result = await exchange_code_for_email(code)
    if result and is_authorized_email(result["email"]):
        request.session["email"] = result["email"]
        return RedirectResponse(url="/")
    return RedirectResponse(url="/login?negado=1")

@app.get("/logout")
def logout(request: Request):
    request.session.clear()
    return RedirectResponse(url="/login")

@app.get("/me")
def me(request: Request, email: str = Depends(get_current_user)):
    return {
        "email": email,
        "api_key": generate_api_key(email),
        "is_master": email.lower().strip() == THC_MASTER_EMAIL.lower().strip() if THC_MASTER_EMAIL else False
    }

@app.get("/v1/models")
def list_models():
    from config import TEXT_MODELS, IMAGE_MODEL_ID
    current_key = get_current_model_key()
    return {
        "object": "list",
        "data": [
            {"id": k, "object": "model", "created": 0, "owned_by": v["backend"]}
            for k, v in TEXT_MODELS.items()
        ],
        "text_models": [
            {
                "key": k,
                "label": v["label"],
                "desc": v["desc"],
                "active": k == current_key,
                "backend": v["backend"],
                "paid": v.get("paid", False),
                "experimental": v.get("experimental", False),
            }
            for k, v in TEXT_MODELS.items()
        ],
        "image_model": {"id": IMAGE_MODEL_ID},
    }

@app.get("/v1/quota")
def list_quotas():
    from config import TEXT_MODELS
    quotas = []
    for k, v in TEXT_MODELS.items():
        if "rpd" in v:
            quotas.append({
                "model": k,
                "used": 0,
                "limit": v["rpd"],
                "rpd": v["rpd"],
                "rpm": v["rpm"],
            })
    return {"quotas": quotas}

@app.post("/v1/knowledge/reload")
def reload_knowledge():
    reload_indexes()
    return {
        "knowledge_chunks": len(knowledge_index["chunks"]),
        "skills_chunks": len(skills_index["chunks"]),
    }

# ── Aplica os modos Fast/Médio/Thinking (parte de geração, não de conteúdo) ──
def apply_mode(mode, max_tokens, temperature):
    do_sample = temperature > 0
    if mode == "fast":
        return max_tokens, False, None
    elif mode == "thinking":
        t = min(temperature, 0.4) if temperature > 0 else 0.3
        return max(max_tokens, 768), True, t
    else:
        return max_tokens, do_sample, (temperature if do_sample else None)

# ── Helper: Converte formato OpenAI → Gemini ─────────────────────────────────────
def convert_to_gemini_format(chat_messages, system_content=None):
    contents = []
    for msg in chat_messages:
        role = "model" if msg["role"] == "assistant" else "user"
        contents.append({
            "role": role,
            "parts": [{"text": msg["content"]}]
        })

    payload = {"contents": contents}

    if system_content:
        payload["systemInstruction"] = {
            "parts": [{"text": system_content}],
            "role": "system"
        }

    return payload


def convert_tools_to_gemini_format(tools):
    if not tools:
        return None
    declarations = []
    for t in tools:
        fn = t.function if hasattr(t, "function") else t["function"]
        name = fn.name if hasattr(fn, "name") else fn["name"]
        description = (fn.description if hasattr(fn, "description") else fn.get("description")) or ""
        parameters = (
            fn.parameters.model_dump(exclude_none=True)
            if hasattr(fn, "parameters") and fn.parameters
            else {"type": "object", "properties": {}}
        )
        declarations.append({
            "name": name,
            "description": description,
            "parameters": parameters,
        })
    return [{"functionDeclarations": declarations}]


def convert_anthropic_tools_to_openai(tools: List[AnthropicTool]) -> List[dict]:
    converted = []
    for t in tools:
        schema = t.input_schema or {"type": "object", "properties": {}}
        converted.append({
            "type": "function",
            "function": {
                "name": t.name,
                "description": t.description or "",
                "parameters": schema,
            }
        })
    return converted


def convert_openai_tool_calls_to_anthropic(tool_calls: List[dict]) -> List[dict]:
    blocks = []
    for tc in tool_calls:
        fn = tc.get("function", {})
        try:
            arguments = json.loads(fn.get("arguments", "{}"))
        except (json.JSONDecodeError, TypeError):
            arguments = {}
        blocks.append({
            "type": "tool_use",
            "id": tc.get("id", f"toolu_{uuid.uuid4().hex[:8]}"),
            "name": fn.get("name", ""),
            "input": arguments,
        })
    return blocks


# ── Helper: Sanitiza mensagens para GGUF ──────────────────────────────────────
def sanitize_chat_for_gguf(chat_messages):
    messages = [{"role": m["role"], "content": m["content"]} for m in chat_messages]
    system_content = ""
    while messages and messages[0]["role"] == "system":
        system_content += (system_content + "\n\n" if system_content else "") + messages.pop(0)["content"]
    if system_content and messages and messages[0]["role"] == "user":
        messages[0]["content"] = system_content + "\n\n" + messages[0]["content"]
    elif system_content:
        messages.insert(0, {"role": "user", "content": system_content})
    if not messages or messages[0]["role"] != "user":
        messages.insert(0, {"role": "user", "content": "Continue."})
    sanitized = [messages[0]]
    for msg in messages[1:]:
        if sanitized[-1]["role"] == msg["role"]:
            sanitized[-1]["content"] += "\n\n" + msg["content"]
        else:
            sanitized.append(msg)
    if len(sanitized) % 2 == 0:
        sanitized.append({"role": "user", "content": "Continue."})
    return sanitized

# ── Endpoints — Chat ────────────────────────────────────────────────────────────
@app.post("/v1/chat/completions")
def chat_completions(req: ChatRequest):
    try:
        state = get_text_model(req.model)
        backend = state["backend"]
        chat = [{"role": m.role, "content": m.content} for m in req.messages]

        last_user_msg = next((m["content"] for m in reversed(chat) if m["role"] == "user"), "")

        system_content = build_system_prompt(last_user_msg, req.mode, req.web, req.free_mode)
        chat = [{"role": "system", "content": system_content}] + chat

        max_tokens, do_sample, temperature = apply_mode(req.mode, req.max_tokens, req.temperature)

        t0 = time.time()

        if backend == "transformers":
            tokenizer = state["tokenizer"]
            model = state["model"]

            tokenized = tokenizer.apply_chat_template(
                chat, return_tensors="pt", add_generation_prompt=True, return_dict=True,
            )
            input_ids = tokenized["input_ids"]

            gen_kwargs = dict(
                max_new_tokens=max_tokens,
                do_sample=do_sample,
                pad_token_id=tokenizer.eos_token_id,
            )
            if do_sample and temperature:
                gen_kwargs["temperature"] = temperature

            with torch.no_grad():
                output = model.generate(input_ids, **gen_kwargs)

            generated = output[0][input_ids.shape[-1]:]
            text = tokenizer.decode(generated, skip_special_tokens=True)
            prompt_tokens = input_ids.shape[-1]
            completion_tokens = len(generated)

        elif backend == "gguf":
            llm = state["model"]
            safe_chat = sanitize_chat_for_gguf(chat)
            result = llm.create_chat_completion(
                messages=safe_chat,
                max_tokens=max_tokens,
                temperature=temperature if temperature else 0.0,
            )
            text = result["choices"][0]["message"]["content"]
            usage = result.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "kilo":
            model_id = state["model"]
            kilo_api_key = os.environ.get("KILO_API_KEY")
            if not kilo_api_key:
                raise ConfigurationError("KILO_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {kilo_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }

            @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
            async def call_kilo_api():
                async with httpx.AsyncClient() as client:
                    resp = await client.post(
                        "https://api.kilo.ai/api/gateway/v1/chat/completions",
                        json=payload,
                        headers=headers,
                        timeout=600.0,
                    )
                    return resp

            resp = asyncio.run(call_kilo_api())
            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Kilo API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Kilo API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Kilo API: {data}")

            text = data["choices"][0]["message"]["content"]
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "openrouter":
            model_id = state["model"]
            openrouter_api_key = os.environ.get("OPENROUTER_API_KEY")
            if not openrouter_api_key:
                raise ConfigurationError("OPENROUTER_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {openrouter_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
            async def call_openrouter_api():
                async with httpx.AsyncClient() as client:
                    resp = await client.post(
                        "https://openrouter.ai/api/v1/chat/completions",
                        json=payload,
                        headers=headers,
                        timeout=600.0,
                    )
                    return resp

            resp = asyncio.run(call_openrouter_api())
            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro OpenRouter API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro OpenRouter API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da OpenRouter API: {data}")

            message_obj = data["choices"][0]["message"]
            text = message_obj.get("content", "") or ""
            tool_calls = message_obj.get("tool_calls")
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "groq":
            model_id = state["model"]
            groq_api_key = os.environ.get("GROQ_API_KEY")
            if not groq_api_key:
                raise ConfigurationError("GROQ_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {groq_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            payload_bytes = len(json.dumps(payload))
            logger.info(f"[GROQ DEBUG] Payload size: {payload_bytes} bytes, Messages: {len(chat)}")

            @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
            async def call_groq_api():
                async with httpx.AsyncClient() as client:
                    resp = await client.post(
                        "https://api.groq.com/openai/v1/chat/completions",
                        json=payload,
                        headers=headers,
                        timeout=600.0,
                    )
                    return resp

            resp = asyncio.run(call_groq_api())
            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Groq API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Groq API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Groq API: {data}")

            message_obj = data["choices"][0]["message"]
            text = message_obj.get("content", "") or ""
            tool_calls = message_obj.get("tool_calls")
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "mistral":
            model_id = state["model"]
            mistral_api_key = os.environ.get("MISTRAL_API_KEY")
            if not mistral_api_key:
                raise ConfigurationError("MISTRAL_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {mistral_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
            async def call_mistral_api():
                async with httpx.AsyncClient() as client:
                    resp = await client.post(
                        "https://api.mistral.ai/v1/chat/completions",
                        json=payload,
                        headers=headers,
                        timeout=600.0,
                    )
                    return resp

            resp = asyncio.run(call_mistral_api())
            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Mistral API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Mistral API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Mistral API: {data}")

            message_obj = data["choices"][0]["message"]
            text = message_obj.get("content", "") or ""
            tool_calls = message_obj.get("tool_calls")
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)
            finish_reason = data["choices"][0].get("finish_reason", "unknown")
            logger.info(f"[MISTRAL DEBUG] finish_reason={finish_reason}, completion_tokens={completion_tokens}, max_tokens_sent={max_tokens}")

        elif backend == "gemini":
            model_id = state["model"]
            google_studio_key = os.environ.get("GOOGLE_STUDIO_API_KEY")
            if not google_studio_key:
                raise ConfigurationError("GOOGLE_STUDIO_API_KEY não configurada")

            gemini_payload = convert_to_gemini_format(chat, system_content)
            gemini_payload["generationConfig"] = {
                "maxOutputTokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }

            if req.tools:
                gemini_payload["tools"] = convert_tools_to_gemini_format(req.tools)

            if model_id.startswith("gemini"):
                gemini_payload["generationConfig"]["thinkingConfig"] = {"thinkingBudget": 0}

            url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_id}:generateContent?key={google_studio_key}"

            @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
            async def call_gemini_api():
                async with httpx.AsyncClient() as client:
                    resp = await client.post(
                        url,
                        json=gemini_payload,
                        headers={"Content-Type": "application/json"},
                        timeout=600.0,
                    )
                    return resp

            resp = asyncio.run(call_gemini_api())
            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Gemini API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Gemini API: {err_msg}")
            if "candidates" not in data or not data["candidates"]:
                raise APIError(f"Resposta inválida da Gemini API: {data}")

            logger.info(f"[GEMINI DEBUG] finishReason={data['candidates'][0].get('finishReason')}, content={data['candidates'][0].get('content', {})}")

            text = data["candidates"][0]["content"]["parts"][0]["text"]
            usage = data.get("usageMetadata", {})
            prompt_tokens = usage.get("promptTokenCount", 0)
            completion_tokens = usage.get("candidatesTokenCount", 0)

            finish_reason = "stop"
            if data["candidates"][0].get("finishReason") == "MAX_TOKENS":
                finish_reason = "length"

        else:
            raise BackendError("Backend inválido")

        elapsed = time.time() - t0
        logger.info(f"Resposta gerada em {elapsed:.1f}s ({backend}, web={req.web})")

        message = {"role": "assistant", "content": text}
        openai_tool_calls = None
        if 'tool_calls' in locals() and tool_calls:
            openai_tool_calls = tool_calls
        elif 'function_calls' in locals() and function_calls:
            openai_tool_calls = [
                {
                    "id": f"call_{uuid.uuid4().hex[:8]}",
                    "type": "function",
                    "function": {
                        "name": fc["name"],
                        "arguments": json.dumps(fc.get("args", {})),
                    },
                }
                for fc in function_calls
            ]
        if openai_tool_calls:
            message["tool_calls"] = openai_tool_calls

        return {
            "id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
            "object": "chat.completion",
            "created": int(time.time()),
            "model": req.model,
            "mode": req.mode,
            "choices": [{
                "index": 0,
                "message": message,
                "finish_reason": "tool_calls" if openai_tool_calls else (finish_reason or "stop"),
            }],
            "usage": {
                "prompt_tokens": prompt_tokens,
                "completion_tokens": completion_tokens,
                "total_tokens": prompt_tokens + completion_tokens,
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        err = traceback.format_exc()
        logger.error(f"Erro no chat: {err}")
        raise ChatError(str(e) + "\n" + err)

# ── Endpoints — Geração de Imagem ──────────────────────────────────────────────
@app.post("/v1/images/generations")
def generate_image(req: ImageRequest, email: str = Depends(get_current_user)):
    try:
        pipe = get_image_pipeline()
        t0 = time.time()
        result = pipe(
            prompt=req.prompt,
            negative_prompt=req.negative_prompt,
            num_inference_steps=req.steps,
            guidance_scale=0.0,
            height=req.size,
            width=req.size,
        )
        image = result.images[0]
        elapsed = time.time() - t0

        buffer = io.BytesIO()
        image.save(buffer, format="PNG")
        img_b64 = base64.b64encode(buffer.getvalue()).decode("utf-8")

        return {
            "created": int(time.time()),
            "elapsed_seconds": round(elapsed, 1),
            "data": [{"b64_json": img_b64}]
        }
    except Exception as e:
        err = traceback.format_exc()
        logger.error(f"Erro na geração de imagem: {err}")
        raise ImageGenerationError(str(e) + "\n" + err)

# ── Endpoints — Geração de Áudio ────────────────────────────────────────────────
@app.post("/v1/audio/generations")
async def generate_audio(req: AudioRequest, email: str = Depends(get_current_user)):
    try:
        model_id = TEXT_MODELS[req.model]["model_id"]
        openrouter_api_key = os.environ.get("OPENROUTER_API_KEY")
        if not openrouter_api_key:
            raise ConfigurationError("OPENROUTER_API_KEY não configurada")

        headers = {
            "Authorization": f"Bearer {openrouter_api_key}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": model_id,
            "messages": [{"role": "user", "content": req.prompt}],
            "modalities": ["text", "audio"],
            "stream": True,
        }
        if req.image:
            payload["image"] = req.image

        @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
        async def call_audio_api():
            async with httpx.AsyncClient() as client:
                async with client.stream(
                    "POST",
                    "https://openrouter.ai/api/v1/chat/completions",
                    json=payload,
                    headers=headers,
                    timeout=120.0,
                ) as resp:
                    if resp.status_code != 200:
                        body = await resp.aread()
                        return resp.status_code, body, [], []

                    audio_chunks, transcript_chunks = [], []
                    async for line in resp.aiter_lines():
                        if not line or not line.startswith("data: "):
                            continue
                        data = line[6:].strip()
                        if data == "[DONE]":
                            break
                        try:
                            chunk = json.loads(data)
                        except json.JSONDecodeError:
                            continue
                        delta_audio = chunk.get("choices", [{}])[0].get("delta", {}).get("audio", {})
                        if delta_audio.get("data"):
                            audio_chunks.append(delta_audio["data"])
                        if delta_audio.get("transcript"):
                            transcript_chunks.append(delta_audio["transcript"])
                    return 200, b"", audio_chunks, transcript_chunks

        t0 = time.time()
        status_code, err_body, audio_chunks, transcript_chunks = await call_audio_api()

        if status_code != 200:
            try:
                err_data = json.loads(err_body) if err_body else {}
                err_msg = err_data.get("error", {}).get("message", err_body.decode(errors="ignore"))
            except Exception:
                err_msg = err_body.decode(errors="ignore") if err_body else f"HTTP {status_code}"
            raise APIError(f"Erro OpenRouter Audio ({status_code}): {err_msg}")

        if not audio_chunks:
            raise APIError("Nenhum áudio recebido da API (resposta vazia ou modelo indisponível)")

        elapsed = time.time() - t0
        full_audio_b64 = "".join(audio_chunks)

        return {
            "created": int(time.time()),
            "elapsed_seconds": round(elapsed, 1),
            "model": req.model,
            "transcript": "".join(transcript_chunks) or None,
            "data": [{"b64_json": full_audio_b64}],
        }
    except Exception as e:
        err = traceback.format_exc()
        logger.error(f"Erro na geração de áudio: {err}")
        raise ImageGenerationError(str(e) + "\n" + err)

# ── Endpoints — Audio Transcription ──────────────────────────────────────────────
@app.post("/v1/audio/transcriptions")
async def transcribe_audio(file: UploadFile = File(...), model: Optional[str] = Form("whisper-turbo")):
    try:
        if model not in TRANSCRIPTION_MODELS:
            raise HTTPException(status_code=400, detail=f"Modelo desconhecido: {model}")

        model_id = TRANSCRIPTION_MODELS[model]["model_id"]
        groq_api_key = os.environ.get("GROQ_API_KEY")
        if not groq_api_key:
            raise ConfigurationError("GROQ_API_KEY não configurada")

        url = "https://api.groq.com/openai/v1/audio/transcriptions"
        headers = {"Authorization": f"Bearer {groq_api_key}"}

        @async_retry_with_backoff(max_retries=3, initial_delay=1, backoff_factor=2)
        async def call_transcription_api():
            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    url,
                    headers=headers,
                    files={
                        "file": (file.filename, await file.read(), file.content_type or "audio/mpeg"),
                        "model": (None, model_id),
                        "language": (None, "pt"),
                    },
                    timeout=120.0,
                )
                return resp

        resp = asyncio.run(call_transcription_api())
        if resp.status_code != 200:
            try:
                err_data = resp.json()
                err_msg = err_data.get("error", {}).get("message", resp.text)
            except Exception:
                err_msg = resp.text
            raise APIError(f"Erro Groq Transcription ({resp.status_code}): {err_msg}")

        data = resp.json()
        if "error" in data:
            err_msg = data["error"].get("message", str(data))
            raise APIError(f"Erro Groq Transcription: {err_msg}")

        return {"text": data.get("text", ""), "model": model}
    except Exception as e:
        err = traceback.format_exc()
        logger.error(f"Erro na transcrição: {err}")
        raise APIError(str(e) + "\n" + err)

@app.get("/v1/transcription-models")
def list_transcription_models():
    return {
        "transcription_models": [
            {"key": k, "label": v["label"], "desc": v["desc"]}
            for k, v in TRANSCRIPTION_MODELS.items()
        ]
    }

async def chat_completions_async(req: ChatRequest):
    """Versão async do chat_completions — usada pelos endpoints SSE."""
    try:
        state = get_text_model(req.model)
        backend = state["backend"]
        chat = [{"role": m.role, "content": m.content} for m in req.messages]

        last_user_msg = next((m["content"] for m in reversed(chat) if m["role"] == "user"), "")

        system_content = build_system_prompt(last_user_msg, req.mode, req.web, req.free_mode)
        chat = [{"role": "system", "content": system_content}] + chat

        max_tokens, do_sample, temperature = apply_mode(req.mode, req.max_tokens, req.temperature)

        t0 = time.time()

        if backend == "transformers":
            tokenizer = state["tokenizer"]
            model = state["model"]

            tokenized = tokenizer.apply_chat_template(
                chat, return_tensors="pt", add_generation_prompt=True, return_dict=True,
            )
            input_ids = tokenized["input_ids"]

            gen_kwargs = dict(
                max_new_tokens=max_tokens,
                do_sample=do_sample,
                pad_token_id=tokenizer.eos_token_id,
            )
            if do_sample and temperature:
                gen_kwargs["temperature"] = temperature

            with torch.no_grad():
                output = model.generate(input_ids, **gen_kwargs)

            generated = output[0][input_ids.shape[-1]:]
            text = tokenizer.decode(generated, skip_special_tokens=True)
            prompt_tokens = input_ids.shape[-1]
            completion_tokens = len(generated)

        elif backend == "gguf":
            llm = state["model"]
            safe_chat = sanitize_chat_for_gguf(chat)
            result = llm.create_chat_completion(
                messages=safe_chat,
                max_tokens=max_tokens,
                temperature=temperature if temperature else 0.0,
            )
            text = result["choices"][0]["message"]["content"]
            usage = result.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "kilo":
            model_id = state["model"]
            kilo_api_key = os.environ.get("KILO_API_KEY")
            if not kilo_api_key:
                raise ConfigurationError("KILO_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {kilo_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }

            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    "https://api.kilo.ai/api/gateway/v1/chat/completions",
                    json=payload,
                    headers=headers,
                    timeout=600.0,
                )

            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Kilo API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Kilo API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Kilo API: {data}")

            text = data["choices"][0]["message"]["content"]
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "openrouter":
            model_id = state["model"]
            openrouter_api_key = os.environ.get("OPENROUTER_API_KEY")
            if not openrouter_api_key:
                raise ConfigurationError("OPENROUTER_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {openrouter_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    "https://openrouter.ai/api/v1/chat/completions",
                    json=payload,
                    headers=headers,
                    timeout=600.0,
                )

            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro OpenRouter API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro OpenRouter API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da OpenRouter API: {data}")

            message_obj = data["choices"][0]["message"]
            text = message_obj.get("content", "") or ""
            tool_calls = message_obj.get("tool_calls")
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "groq":
            model_id = state["model"]
            groq_api_key = os.environ.get("GROQ_API_KEY")
            if not groq_api_key:
                raise ConfigurationError("GROQ_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {groq_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            payload_bytes = len(json.dumps(payload))
            logger.info(f"[GROQ DEBUG] Payload size: {payload_bytes} bytes, Messages: {len(chat)}")

            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    "https://api.groq.com/openai/v1/chat/completions",
                    json=payload,
                    headers=headers,
                    timeout=600.0,
                )

            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Groq API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Groq API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Groq API: {data}")

            message_obj = data["choices"][0]["message"]
            text = message_obj.get("content", "") or ""
            tool_calls = message_obj.get("tool_calls")
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)

        elif backend == "mistral":
            model_id = state["model"]
            mistral_api_key = os.environ.get("MISTRAL_API_KEY")
            if not mistral_api_key:
                raise ConfigurationError("MISTRAL_API_KEY não configurada")

            headers = {
                "Authorization": f"Bearer {mistral_api_key}",
                "Content-Type": "application/json",
            }
            payload = {
                "model": model_id,
                "messages": chat,
                "max_tokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }
            if req.tools:
                payload["tools"] = [t.model_dump(exclude_none=True) for t in req.tools]
                payload["tool_choice"] = req.tool_choice or "auto"

            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    "https://api.mistral.ai/v1/chat/completions",
                    json=payload,
                    headers=headers,
                    timeout=600.0,
                )

            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Mistral API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Mistral API: {err_msg}")
            if "choices" not in data or not data["choices"]:
                raise APIError(f"Resposta inválida da Mistral API: {data}")

            text = data["choices"][0]["message"]["content"]
            usage = data.get("usage", {})
            prompt_tokens = usage.get("prompt_tokens", 0)
            completion_tokens = usage.get("completion_tokens", 0)
            finish_reason = data["choices"][0].get("finish_reason", "unknown")
            logger.info(f"[MISTRAL DEBUG] finish_reason={finish_reason}, completion_tokens={completion_tokens}, max_tokens_sent={max_tokens}")

        elif backend == "gemini":
            model_id = state["model"]
            google_studio_key = os.environ.get("GOOGLE_STUDIO_API_KEY")
            if not google_studio_key:
                raise ConfigurationError("GOOGLE_STUDIO_API_KEY não configurada")

            gemini_payload = convert_to_gemini_format(chat, system_content)
            gemini_payload["generationConfig"] = {
                "maxOutputTokens": max_tokens,
                "temperature": temperature if temperature else 0.0,
            }

            if req.tools:
                gemini_payload["tools"] = convert_tools_to_gemini_format(req.tools)

            if model_id.startswith("gemini"):
                gemini_payload["generationConfig"]["thinkingConfig"] = {"thinkingBudget": 0}

            url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_id}:generateContent?key={google_studio_key}"

            async with httpx.AsyncClient() as client:
                resp = await client.post(
                    url,
                    json=gemini_payload,
                    headers={"Content-Type": "application/json"},
                    timeout=600.0,
                )

            if resp.status_code != 200:
                try:
                    err_data = resp.json()
                    err_msg = err_data.get("error", {}).get("message", resp.text)
                except Exception:
                    err_msg = resp.text
                raise APIError(f"Erro Gemini API ({resp.status_code}): {err_msg}")

            data = resp.json()
            if "error" in data:
                err_msg = data["error"].get("message", str(data))
                raise APIError(f"Erro Gemini API: {err_msg}")
            if "candidates" not in data or not data["candidates"]:
                raise APIError(f"Resposta inválida da Gemini API: {data}")

            logger.info(f"[GEMINI DEBUG] finishReason={data['candidates'][0].get('finishReason')}, content={data['candidates'][0].get('content', {})}")

            parts = data["candidates"][0]["content"]["parts"]
            text_parts = [p.get("text", "") for p in parts if "text" in p]
            text = "".join(text_parts)
            function_calls = [p["functionCall"] for p in parts if "functionCall" in p]
            usage = data.get("usageMetadata", {})
            prompt_tokens = usage.get("promptTokenCount", 0)
            completion_tokens = usage.get("candidatesTokenCount", 0)

            finish_reason = "stop"
            if data["candidates"][0].get("finishReason") == "MAX_TOKENS":
                finish_reason = "length"

        else:
            raise BackendError("Backend inválido")

        elapsed = time.time() - t0
        logger.info(f"Resposta gerada em {elapsed:.1f}s ({backend}, web={req.web})")

        message = {"role": "assistant", "content": text}
        openai_tool_calls = None
        if 'tool_calls' in locals() and tool_calls:
            openai_tool_calls = tool_calls
        elif 'function_calls' in locals() and function_calls:
            openai_tool_calls = [
                {
                    "id": f"call_{uuid.uuid4().hex[:8]}",
                    "type": "function",
                    "function": {
                        "name": fc["name"],
                        "arguments": json.dumps(fc.get("args", {})),
                    },
                }
                for fc in function_calls
            ]
        if openai_tool_calls:
            message["tool_calls"] = openai_tool_calls

        return {
            "id": f"chatcmpl-{uuid.uuid4().hex[:8]}",
            "object": "chat.completion",
            "created": int(time.time()),
            "model": req.model,
            "mode": req.mode,
            "choices": [{
                "index": 0,
                "message": message,
                "finish_reason": "tool_calls" if openai_tool_calls else (finish_reason or "stop"),
            }],
            "usage": {
                "prompt_tokens": prompt_tokens,
                "completion_tokens": completion_tokens,
                "total_tokens": prompt_tokens + completion_tokens,
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        err = traceback.format_exc()
        logger.error(f"Erro no chat: {err}")
        raise ChatError(str(e) + "\n" + err)


def build_anthropic_content(message: dict) -> List[dict]:
    tool_calls = message.get("tool_calls") or []
    if tool_calls:
        return [
            {
                "type": "tool_use",
                "id": tc.get("id", f"toolu_{uuid.uuid4().hex[:8]}"),
                "name": tc.get("function", {}).get("name", ""),
                "input": json.loads(tc.get("function", {}).get("arguments", "{}")),
            }
            for tc in tool_calls
        ]
    text = message.get("content", "") or ""
    return [{"type": "text", "text": text}]


@app.post("/v1/messages")
async def anthropic_messages(req: AnthropicRequest, request: Request):
    """Rota compatível com SDK Anthropic — suporta stream=true (SSE) e stream=false (JSON)."""

    msgs = []
    if req.system:
        msgs.append(Message(role="system", content=req.system))
    for m in req.messages:
        msgs.append(Message(role=m.role, content=m.content))

    openai_tools = convert_anthropic_tools_to_openai(req.tools) if req.tools else None
    chat_req = ChatRequest(
        model=req.model,
        messages=msgs,
        max_tokens=req.max_tokens,
        temperature=req.temperature,
        mode="medium",
        web=False,
        free_mode=False,
        tools=openai_tools,
        tool_choice=req.tool_choice or "auto",
    )

    if req.stream:
        async def event_stream():
            msg_id = f"msg_thc_{uuid.uuid4().hex[:8]}"

            yield f"event: message_start\ndata: {json.dumps({'type':'message_start','message':{'id':msg_id,'type':'message','role':'assistant','content':[],'model':req.model,'stop_reason':None,'stop_sequence':None,'usage':{'input_tokens':0,'output_tokens':0}}})}\n\n"
            yield f"event: content_block_start\ndata: {json.dumps({'type':'content_block_start','index':0,'content_block':{'type':'text','text':''}})}\n\n"
            yield f"event: ping\ndata: {json.dumps({'type':'ping'})}\n\n"

            try:
                result = await chat_completions_async(chat_req)
                message = result["choices"][0]["message"]
                usage = result.get("usage", {})
                content_blocks = build_anthropic_content(message)
                stop_reason = "tool_use" if any(b.get("type") == "tool_use" for b in content_blocks) else "end_turn"
            except Exception as e:
                content_blocks = [{"type": "text", "text": f"Erro: {str(e)}"}]
                usage = {}
                stop_reason = "end_turn"

            for block in content_blocks:
                block_type = block.get("type", "text")
                if block_type == "text":
                    chunk_size = 20
                    for i in range(0, len(block.get("text", "")), chunk_size):
                        chunk = block["text"][i:i+chunk_size]
                        yield f"event: content_block_delta\ndata: {json.dumps({'type':'content_block_delta','index':0,'delta':{'type':'text_delta','text':chunk}})}\n\n"
                        await asyncio.sleep(0.01)
                elif block_type == "tool_use":
                    yield f"event: content_block_delta\ndata: {json.dumps({'type':'content_block_delta','index':0,'delta':{'type':'tool_use_delta','input':block.get('input', {})}})}\n\n"

            yield f"event: content_block_stop\ndata: {json.dumps({'type':'content_block_stop','index':0})}\n\n"
            yield f"event: message_delta\ndata: {json.dumps({'type':'message_delta','delta':{'stop_reason':stop_reason,'stop_sequence':None},'usage':{'output_tokens':usage.get('completion_tokens',0)}})}\n\n"
            yield f"event: message_stop\ndata: {json.dumps({'type':'message_stop'})}\n\n"

        return StreamingResponse(event_stream(), media_type="text/event-stream")

    result = await chat_completions_async(chat_req)
    message = result["choices"][0]["message"]
    usage = result.get("usage", {})
    content_blocks = build_anthropic_content(message)
    stop_reason = "tool_use" if any(b.get("type") == "tool_use" for b in content_blocks) else "end_turn"
    return {
        "id": f"msg_thc_{uuid.uuid4().hex[:8]}",
        "type": "message",
        "role": "assistant",
        "content": content_blocks,
        "model": req.model,
        "stop_reason": stop_reason,
        "stop_sequence": None,
        "usage": {
            "input_tokens": usage.get("prompt_tokens", 0),
            "output_tokens": usage.get("completion_tokens", 0),
        },
    }

@app.post("/v1/messages/stream")
async def anthropic_messages_stream(req: AnthropicRequest, request: Request):
    """Endpoint de streaming SSE compatível com Claude Code SDK."""

    msgs = []
    if req.system:
        msgs.append(Message(role="system", content=req.system))
    for m in req.messages:
        msgs.append(Message(role=m.role, content=m.content))

    openai_tools = convert_anthropic_tools_to_openai(req.tools) if req.tools else None
    chat_req = ChatRequest(
        model=req.model,
        messages=msgs,
        max_tokens=req.max_tokens,
        temperature=req.temperature,
        mode="medium",
        web=False,
        free_mode=False,
        tools=openai_tools,
        tool_choice=req.tool_choice or "auto",
    )

    try:
        result = await chat_completions_async(chat_req)
        message = result["choices"][0]["message"]
        usage = result.get("usage", {})
        content_blocks = build_anthropic_content(message)
        stop_reason = "tool_use" if any(b.get("type") == "tool_use" for b in content_blocks) else "end_turn"
    except Exception as e:
        content_blocks = [{"type": "text", "text": f"Erro: {str(e)}"}]
        usage = {}
        stop_reason = "end_turn"

    async def event_stream():
        msg_id = f"msg_thc_{uuid.uuid4().hex[:8]}"

        yield f"event: message_start\ndata: {json.dumps({'type':'message_start','message':{'id':msg_id,'type':'message','role':'assistant','content':[],'model':req.model,'stop_reason':None,'stop_sequence':None,'usage':{'input_tokens':0,'output_tokens':0}}})}\n\n"
        yield f"event: content_block_start\ndata: {json.dumps({'type':'content_block_start','index':0,'content_block':{'type':'text','text':''}})}\n\n"
        yield f"event: ping\ndata: {json.dumps({'type':'ping'})}\n\n"

        for block in content_blocks:
            block_type = block.get("type", "text")
            if block_type == "text":
                chunk_size = 20
                for i in range(0, len(block.get("text", "")), chunk_size):
                    chunk = block["text"][i:i+chunk_size]
                    yield f"event: content_block_delta\ndata: {json.dumps({'type':'content_block_delta','index':0,'delta':{'type':'text_delta','text':chunk}})}\n\n"
                    await asyncio.sleep(0.01)
            elif block_type == "tool_use":
                yield f"event: content_block_delta\ndata: {json.dumps({'type':'content_block_delta','index':0,'delta':{'type':'tool_use_delta','input':block.get('input', {})}})}\n\n"

        yield f"event: content_block_stop\ndata: {json.dumps({'type':'content_block_stop','index':0})}\n\n"
        yield f"event: message_delta\ndata: {json.dumps({'type':'message_delta','delta':{'stop_reason':stop_reason,'stop_sequence':None},'usage':{'output_tokens':usage.get('completion_tokens',0)}})}\n\n"
        yield f"event: message_stop\ndata: {json.dumps({'type':'message_stop'})}\n\n"

    return StreamingResponse(event_stream(), media_type="text/event-stream")