File size: 121,989 Bytes
b65c05c
bcb6bfc
 
b65c05c
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
8cf49a5
b65c05c
 
8cf49a5
 
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
 
 
b65c05c
 
 
 
 
 
f565b32
 
8cf49a5
bcb6bfc
 
8cf49a5
 
bcb6bfc
b65c05c
 
8cf49a5
b65c05c
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
8cf49a5
b65c05c
 
 
 
bcb6bfc
b65c05c
 
 
 
 
bcb6bfc
 
b65c05c
 
 
 
 
 
bcb6bfc
 
 
 
 
 
b65c05c
bcb6bfc
 
 
 
 
 
b65c05c
 
 
bcb6bfc
b65c05c
 
 
 
 
 
 
 
bcb6bfc
b65c05c
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
8cf49a5
b65c05c
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
 
 
 
 
8cf49a5
b65c05c
8cf49a5
 
 
 
b65c05c
8cf49a5
 
 
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
b65c05c
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
 
b65c05c
 
 
8cf49a5
b65c05c
 
 
 
8cf49a5
b65c05c
 
 
 
 
 
 
 
 
 
 
 
8cf49a5
bcb6bfc
b65c05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
# TIKTOKBOT - PHIÊN BẢN API VỚI FASTAPI (PHIÊN BẢN HOÀN CHỈNH)
import nest_asyncio
nest_asyncio.apply()
# --- CÁC THƯ VIỆN CHUẨN ---
import httpx
from collections import deque
import io
from PIL import Image
import socket, aiodns, asyncio, time
import re
import traceback
import os, random, datetime, pandas as pd, pickle, base64, requests, subprocess, functools, json
import textwrap
import downloader

# --- CÁC THƯ VIỆN FRAMEWORK ---
from fastapi import FastAPI, Request, BackgroundTasks
from pydantic import BaseModel
from contextlib import asynccontextmanager

# --- CÁC THƯ VIỆN GOOGLE ---
import google.generativeai as genai
import vertexai
from vertexai.vision_models import ImageGenerationModel
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request as GoogleAuthRequest
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
import telegram

# --- BỘ ĐỆM CHỐNG LẶP REQUEST ---
processed_update_ids = deque(maxlen=500)

# --- CẤU HÌNH ĐƯỜNG DẪN VÀ BIẾN TOÀN CỤC ---
# [Sửa Lỗi 2] Chuyển đổi sang dùng biến tạm và ID của Google Drive
CODE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = "/tmp/autogen_bot_data"
ORIGINAL_EXCEL_FILENAME = "Input.xlsx"
WORKING_EXCEL_PATH = os.path.join(DATA_DIR, ORIGINAL_EXCEL_FILENAME)
DRIVE_IMAGE_FOLDER_ID = "11hVHlobQ0eOVgJMJvdUf2dmIqmXgTa1A"
DRIVE_EXCEL_FILE_ID = "1XNN2NuV8clrxv1cZTa_8HM-HCNzv2oDt"

# --- [THÊM MỚI] Cấu hình cho file Excel chứa nội dung MP3 đã tạo ---
MP3_CONTENT_EXCEL_FILENAME = "GenMP3.xlsx"
MP3_CONTENT_EXCEL_PATH = os.path.join(DATA_DIR, MP3_CONTENT_EXCEL_FILENAME)
DRIVE_MP3_CONTENT_FILE_ID = "1HEOaVxpYLN-VY2uD-uL1TwS2Fc72mpva"
DRIVE_FACEBOOK_VIDEO_FOLDER_ID  = "1AQ_XhyhGiE77r7BvuV4w-V_lgVaBb0QV"

# Các đường dẫn tài nguyên cục bộ khác
FONT_FILE_PATH = os.path.join(CODE_DIR, "Font/UVNButLong2.TTF")
YTB_MP3_BG_PATH = os.path.join(CODE_DIR, "YTB/Sound/ytb.mp3")
YTB_ACCOUNT_SRC_PATH = os.path.join(CODE_DIR, "YTB/Account/")
IMAGE_SAVE_PATH = os.path.join(DATA_DIR, "Image/")
MP3_SAVE_PATH = os.path.join(DATA_DIR, "Sound/")
MP4_SAVE_PATH = os.path.join(DATA_DIR, "Video/")
TEMP_PATH = os.path.join(DATA_DIR, "Temp/")
YTB_ACCOUNT_PATH = os.path.join(DATA_DIR, "YTB/Account/")
BG_CHERRY_PATH = os.path.join(CODE_DIR, "Input", "bg2.mp4")

# Các biến cấu hình khác
PROJECT_ID = 'awesome-ridge-467516-t6'
LOCATION = 'us-central1'
MODALNAME = 'imagen-3.0-generate-preview-06-2024'
GOOGLE_APP_SCRIPT_URL = os.getenv("GOOGLE_APP_SCRIPT_URL")
TELEGRAM_BOT_TOKEN_FROM_ENV = os.getenv("TELEGRAM_BOT_TOKEN")
bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN_FROM_ENV)
GOOGLE_TTS_API_KEY = ""
GEMINI_API_KEYS_LIST = []
user_sessions = {}

# --- FUNCTION FOR DEBUGGING ---
def log_environment_variables():
    """Logs critical environment variables at startup."""
    print("\n--- ✅ Logging Environment Variables at Startup ---")
    vars_to_check = [
        "GOOGLE_APP_SCRIPT_URL",
        "TELEGRAM_BOT_TOKEN",
        "GOOGLE_TTS_API_KEY",
        "GOOGLE_APP_CREDENTIALS_JSON"
    ]
    for var in vars_to_check:
        value = os.getenv(var)
        if not value:
            print(f"    - ❌ {var}: NOT SET!")
        else:
            if "TOKEN" in var or "KEY" in var:
                print(f"    - ✅ {var}: Set (value ending in '...{value[-4:]}')")
            elif "JSON" in var:
                 print(f"    - ✅ {var}: Set (length: {len(value)})")
            else:
                print(f"    - ✅ {var}: {value}")
    print("------------------------------------------------\n")

# --- DNS FIX ---
original_getaddrinfo = socket.getaddrinfo
async def custom_getaddrinfo_async(host, port, family=0, type=0, proto=0, flags=0):
    resolver = aiodns.DNSResolver(nameservers=['8.8.8.8', '8.8.4.4'])
    try:
        result = await resolver.query(host, 'A')
        addrlist = []
        for record in result:
            addrlist.append((socket.AF_INET, socket.SOCK_STREAM, 6, '', (record.host, port)))
        return addrlist
    except aiodns.error.DNSError:
        loop = asyncio.get_running_loop()
        return await loop.run_in_executor(None, original_getaddrinfo, host, port, family, type, proto, flags)
def custom_getaddrinfo_sync(*args, **kwargs):
    try: loop = asyncio.get_running_loop()
    except RuntimeError: loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
    return loop.run_until_complete(custom_getaddrinfo_async(*args, **kwargs))
socket.getaddrinfo = custom_getaddrinfo_sync

# --- CÁC HÀM GỬI TIN QUA WORKER ---
# [LOGGING] Thêm log chi tiết vào các hàm gửi tin
async def send_telegram_message(chat_id, text, reply_markup=None):
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ [FATAL] GOOGLE_APP_SCRIPT_URL is not set. Cannot send message.")
        return False
    
    print(f"--- [LOG] Preparing to send message to chat_id: {chat_id}")
    payload = {"action": "sendMessage", "chat_id": chat_id, "text": text, "reply_markup": reply_markup}
    
    try:
        async with httpx.AsyncClient() as client:
            print(f"--- [LOG] Sending POST to Worker URL: {GOOGLE_APP_SCRIPT_URL}")
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=20.0)
            print(f"--- [LOG] Worker responded with status: {response.status_code}")
            response.raise_for_status()
        print(f"--> Successfully sent message to chat_id {chat_id}")
        return True
    except httpx.TimeoutException as e:
        print(f"❌ [ERROR] Timeout when calling Worker for sendMessage: {e}")
        return False
    except httpx.HTTPStatusError as e:
        print(f"❌ [ERROR] HTTP Error when calling Worker for sendMessage: {e.response.status_code} - {e.response.text}")
        return False
    except httpx.RequestError as e:
        print(f"❌ [ERROR] Network error when calling Worker for sendMessage: {e}")
        return False

async def send_telegram_video(chat_id, video_path, caption):
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ [FATAL] GOOGLE_APP_SCRIPT_URL is not set. Cannot send video.")
        return
    
    print(f"--- [LOG] Preparing to send video '{os.path.basename(video_path)}' to chat_id: {chat_id}")
    try:
        with open(video_path, 'rb') as vf:
            video_b64 = base64.b64encode(vf.read()).decode('utf-8')
        
        payload = {
            "action": "sendVideo", 
            "chat_id": chat_id, 
            "caption": caption, 
            "video_b64": video_b64, 
            "filename": os.path.basename(video_path)
        }
        
        async with httpx.AsyncClient() as client:
            print(f"--- [LOG] Sending POST to Worker URL for video: {GOOGLE_APP_SCRIPT_URL}")
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=120.0)
            print(f"--- [LOG] Worker responded with status for video: {response.status_code}")
            response.raise_for_status()
        
        print(f"--> Successfully sent video to chat_id {chat_id}")
    except httpx.TimeoutException as e:
        print(f"❌ [ERROR] Timeout when calling Worker for sendVideo: {e}")
    except httpx.HTTPStatusError as e:
        print(f"❌ [ERROR] HTTP Error when calling Worker for sendVideo: {e.response.status_code} - {e.response.text}")
    except httpx.RequestError as e:
        print(f"❌ [ERROR] Network error when calling Worker for sendVideo: {e}")
    except Exception as e:
        print(f"❌ [ERROR] General error in send_telegram_video: {e}")


async def edit_telegram_message_text(chat_id, message_id, text, reply_markup=None):
    """Gửi yêu cầu chỉnh sửa văn bản tin nhắn qua Worker."""
    if not GOOGLE_APP_SCRIPT_URL: return
    print(f"--- [LOG] Preparing to EDIT message_id: {message_id} in chat_id: {chat_id}")
    payload = {
        "action": "editMessageText",
        "chat_id": chat_id,
        "message_id": message_id,
        "text": text,
        "reply_markup": reply_markup
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=20.0)
            response.raise_for_status()
        print(f"--> Successfully edited message {message_id}")
    except Exception as e:
        print(f"❌ [ERROR] Worker error on editMessageText: {e}")

async def edit_telegram_reply_markup(chat_id, message_id, reply_markup):
    """Gửi yêu cầu chỉ chỉnh sửa bàn phím qua Worker."""
    if not GOOGLE_APP_SCRIPT_URL: return
    print(f"--- [LOG] Preparing to EDIT markup for message_id: {message_id}")
    payload = {
        "action": "editMessageReplyMarkup",
        "chat_id": chat_id,
        "message_id": message_id,
        "reply_markup": reply_markup
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=20.0)
            response.raise_for_status()
        print(f"--> Successfully edited markup for {message_id}")
    except Exception as e:
        print(f"❌ [ERROR] Worker error on editMessageReplyMarkup: {e}")

async def answer_telegram_callback_query(callback_query_id, text=None, show_alert=False):
    """Gửi yêu cầu trả lời callback query qua Worker."""
    if not GOOGLE_APP_SCRIPT_URL: return
    payload = {
        "action": "answerCallbackQuery",
        "callback_query_id": callback_query_id,
        "text": text,
        "show_alert": show_alert
    }
    try:
        async with httpx.AsyncClient() as client:
            # Yêu cầu này thường rất nhanh, không cần timeout cao
            await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=10.0)
    except Exception:
        # Lỗi ở đây không quá nghiêm trọng, có thể bỏ qua
        pass




# --- [Sửa Lỗi 2] CÁC HÀM TƯƠNG TÁC VỚI GOOGLE DRIVE ---
async def get_drive_credentials(chat_id: int) -> Credentials | None:
    """Chỉ đọc và trả về credentials cho Google Drive đã được tạo khi khởi động."""
    working_token_path = os.path.join(YTB_ACCOUNT_PATH, "driverjson.pickle")
    if not os.path.exists(working_token_path):
        await send_telegram_message(chat_id, "❌ Lỗi nghiêm trọng: Không tìm thấy file token chính của Drive.")
        return None

    with open(working_token_path, 'rb') as token:
        credentials = pickle.load(token)

    # Kiểm tra và refresh nếu cần
    if not credentials or not credentials.valid:
         if credentials and credentials.expired and credentials.refresh_token:
            try:
                credentials.refresh(GoogleAuthRequest())
                with open(working_token_path, 'wb') as token:
                    pickle.dump(credentials, token)
                print("✅ Token Drive chính đã được làm mới.")
            except Exception as e:
                await send_telegram_message(chat_id, f"⚠️ Lỗi khi refresh token Drive: {e}")
                return None
         else:
            return None
    return credentials
    
async def get_youtube_credentials_from_drive(drive_service, account_number: int, chat_id: int) -> Credentials | None:
    """Tải file token của YouTube từ Drive và trả về credentials."""
    try:
        token_filename = f'token_youtube_account_{account_number}.pickle'
        print(f"Đang tìm kiếm file token '{token_filename}' trên Drive...")

        # Tìm file token trong thư mục YTB/Account trên Drive
        # Giả sử bạn có ID của thư mục YTB/Account trên Drive
        ytb_account_folder_id = "17ZTgiJaFRGS8Qxo5rO9sytaWxotlKhpa" # <-- Cần thay ID này
        query = f"name='{token_filename}' and '{ytb_account_folder_id}' in parents and trashed=false"
        response = drive_service.files().list(q=query, fields='files(id, name)').execute()
        files = response.get('files', [])

        if not files:
            await send_telegram_message(chat_id, f"❌ Lỗi: Không tìm thấy file token '{token_filename}' trên Google Drive.")
            return None

        file_id = files[0].get('id')
        local_yt_token_path = os.path.join(TEMP_PATH, token_filename)

        # Tải file token YouTube về thư mục tạm
        await download_file_from_drive(drive_service, file_id, local_yt_token_path)

        # Đọc credentials từ file tạm vừa tải về
        with open(local_yt_token_path, 'rb') as token:
            credentials = pickle.load(token)

        # Xóa file tạm sau khi đọc
        os.remove(local_yt_token_path)

        return credentials

    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi lấy token YouTube từ Drive: {e}")
        return None

async def download_file_from_drive(drive_service, file_id: str, save_path: str):
    # [THÊM MỚI] Kiểm tra nếu file đã tồn tại để tránh tải lại không cần thiết
    if os.path.exists(save_path):
        print(f"☑️ File '{save_path}' đã tồn tại, bỏ qua tải xuống.")
        return
    request = drive_service.files().get_media(fileId=file_id)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while not done:
        status, done = downloader.next_chunk()
        print(f"Đang tải file {file_id}: {int(status.progress() * 100)}%.")
    with open(save_path, 'wb') as f:
        f.write(fh.getvalue())
    print(f"✅ Tải file thành công về '{save_path}'")

async def upload_file_to_drive(drive_service, local_path: str, file_id: str):
    # [CHỈNH SỬA] Thay đổi mimetype để linh hoạt hơn
    file_extension = os.path.splitext(local_path)[1]
    mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if file_extension == '.xlsx' else 'application/octet-stream'
    media = MediaFileUpload(local_path, mimetype=mimetype)
    drive_service.files().update(fileId=file_id, media_body=media).execute()
    print(f"✅ Upload file '{local_path}' lên Drive ID '{file_id}' thành công.")

async def delete_file_from_drive(drive_service, file_id: str):
    drive_service.files().delete(fileId=file_id).execute()
    print(f"✅ Đã xóa file ID '{file_id}' khỏi Drive.")

async def get_image_list_from_drive(drive_service):
    query = f"'{DRIVE_IMAGE_FOLDER_ID}' in parents and trashed=false"
    response = drive_service.files().list(q=query, fields='files(id, name)').execute()
    return response.get('files', [])

# --- HÀM KHỞI ĐỘNG BOT ---
async def setup_bot_async():
    print("--- [TRACE] Entering setup_bot_async ---")
    global GOOGLE_TTS_API_KEY, GEMINI_API_KEYS_LIST
    for path in [DATA_DIR, IMAGE_SAVE_PATH, MP3_SAVE_PATH, MP4_SAVE_PATH, TEMP_PATH, YTB_ACCOUNT_PATH]:
        os.makedirs(path, exist_ok=True)
    print("✅ Đã tạo các thư mục lưu trữ.")

    base64_pickle_string = os.getenv("PICKLE_TOKEN_B64")
    if not base64_pickle_string:
        print("❌ LỖI NGHIÊM TRỌNG: Secret 'PICKLE_TOKEN_B64' chưa được thiết lập.")
        return False
    try:
        pickle_binary_data = base64.b64decode(base64_pickle_string)
        working_token_path = os.path.join(YTB_ACCOUNT_PATH, "driverjson.pickle")
        with open(working_token_path, "wb") as f:
            f.write(pickle_binary_data)
        print(f"✅ Đã tạo file token chính tại: {working_token_path}")
    except Exception as e:
        print(f"❌ Lỗi khi giải mã và tạo file token chính: {e}")
        return False

    try:
        ADMIN_CHAT_ID = 6685326330
        credentials = await get_drive_credentials(ADMIN_CHAT_ID)
        if not credentials: return False
        
        drive_service = build('drive', 'v3', credentials=credentials)
        print("✅ Đã kết nối thành công với Google Drive API.")
        
        # [CHỈNH SỬA] Tải cả 2 file excel khi khởi động
        await download_file_from_drive(drive_service, DRIVE_EXCEL_FILE_ID, WORKING_EXCEL_PATH)
        await download_file_from_drive(drive_service, DRIVE_MP3_CONTENT_FILE_ID, MP3_CONTENT_EXCEL_PATH)


        df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
        
        tts_key_value = df_input.iloc[1, 3] 
        if pd.notna(tts_key_value):
            GOOGLE_TTS_API_KEY = str(tts_key_value).strip()
            print("✅ Đã đọc thành công Google TTS API Key từ Excel (ô D2).")
        else:
            print("❌ LỖI: Không tìm thấy Google TTS API Key tại ô D2 của sheet 'Input'.")
            return False

        #GEMINI_API_KEYS_LIST = df_input.iloc[1:, 0].dropna().astype(str).tolist()
        GEMINI_API_KEYS_LIST = [key for key in df_input.iloc[:, 0].tolist()[1:] if pd.notna(key) and str(key).strip()]
 
        if not GEMINI_API_KEYS_LIST:
            print("❌ LỖI: Không tìm thấy key Gemini nào trong cột A (từ A2) của sheet 'Input'.")
            return False
        print(f"✅ Đã đọc thành công {len(GEMINI_API_KEYS_LIST)} key Gemini từ Excel.")
       
        print("⏳ Đang khởi tạo Vertex AI...")
        vertexai.init(project=PROJECT_ID, location=LOCATION, credentials=credentials)
        print("✅ Khởi tạo Vertex AI thành công.")
    except Exception as e:
        print(f"❌ LỖI nghiêm trọng trong quá trình khởi tạo: {e}")
        return False
        
    print("🎉 Khởi tạo bot thành công!")
    print("--- [TRACE] Exiting setup_bot_async ---")
    return True

# --- CÁC HÀM XỬ LÝ EXCEL ---
# --- [CHỈNH SỬA] Các hàm đọc/ghi Excel được tái cấu trúc để chấp nhận `file_path` ---
# Điều này cho phép chúng ta làm việc với cả file Input.xlsx và GenMP3.xlsx
async def update_excel_cell(file_path: str, sheet_name: str, cell: str, value: str):
    """Cập nhật một ô cụ thể trong một file Excel chỉ định."""
    try:
        async with asyncio.Lock():
            try:
                # Đọc tất cả các sheet từ file Excel hiện có
                with pd.ExcelFile(file_path, engine='openpyxl') as xls:
                    book = {sheet: pd.read_excel(xls, sheet_name=sheet, header=None) for sheet in xls.sheet_names}
            except FileNotFoundError:
                # Nếu file không tồn tại, tạo một "book" rỗng
                book = {}
            
            # Lấy dataframe cho sheet cần cập nhật, hoặc tạo mới nếu chưa có
            df = book.get(sheet_name, pd.DataFrame())

            # Chuyển đổi tọa độ cell (ví dụ: 'A1') sang chỉ số 0-based
            col_idx = ord(cell[0].upper()) - ord('A')
            row_idx = int(cell[1:]) - 1

            # Mở rộng dataframe nếu chỉ số nằm ngoài phạm vi hiện tại
            while row_idx >= len(df):
                new_row = pd.DataFrame([[None] * len(df.columns)], index=[len(df)])
                df = pd.concat([df, new_row], ignore_index=True)
            while col_idx >= len(df.columns):
                df[len(df.columns)] = None

            # Ghi giá trị vào ô
            df.iloc[row_idx, col_idx] = value
            book[sheet_name] = df

            # Ghi lại toàn bộ "book" vào file Excel
            with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
                for s_name, s_data in book.items():
                    s_data.to_excel(writer, sheet_name=s_name, index=False, header=False)
    except Exception as e:
        print(f"❌ LỖI khi cập nhật Excel tại '{file_path}': {e}")

async def read_excel_cell(file_path: str, sheet_name: str, cell: str) -> str | None:
    """Đọc một ô cụ thể từ một file Excel chỉ định."""
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name, header=None, engine='openpyxl')
        col_idx = ord(cell[0].upper()) - ord('A')
        row_idx = int(cell[1:]) - 1
        if row_idx < df.shape[0] and col_idx < df.shape[1]:
            value = df.iloc[row_idx, col_idx]
            return None if pd.isna(value) else str(value).strip()
        return None
    except Exception as e:
        print(f"❌ LỖI khi đọc Excel từ '{file_path}': {e}")
        return None

# --- CÁC HÀM LOGIC PHỤ ---
async def generate_with_gemini_auto_retry(prompt: str):
    global GEMINI_API_KEYS_LIST
    if not GEMINI_API_KEYS_LIST:
        raise Exception("Danh sách API key của Gemini trống.")
    start_index = random.randint(0, len(GEMINI_API_KEYS_LIST) - 1)
    current_index = start_index
    while True:
        try:
            current_key = GEMINI_API_KEYS_LIST[current_index]
            genai.configure(api_key=current_key)
            model = genai.GenerativeModel('models/gemini-2.0-flash')
            response = await model.generate_content_async(prompt)
            return response
        except Exception as e:
            print(f"⚠️ Key Gemini index {current_index} bị lỗi: {e}. Đang chuyển key...")
            current_index = (current_index + 1) % len(GEMINI_API_KEYS_LIST)
            if current_index == start_index:
                raise Exception("Tất cả các API key của Gemini đều lỗi hoặc hết hạn mức.") from e

async def enhance_prompt(idea: str) -> str | None:
    try:
        request = (
            f"You are an expert AI prompt engineer. Your task is to enhance the following user's idea into a detailed, artistic, and effective prompt for an image generation AI like Midjourney or Imagen. The final image should be a cinematic, ultra-realistic, and emotionally resonant vertical photograph (9:16 aspect ratio).\n\n"
            f"**User's Idea:** \"{idea}\"\n\n"
            f"**Your Enhancement Guidelines:**\n"
            f"1.  **Style:** Specify 'cinematic, ultra-realistic vertical photograph, 9:16 aspect ratio'.\n"
            f"2.  **Subject & Scene:** Describe the main subject and the surrounding environment in vivid detail. What is the subject doing? What is the mood?\n"
            f"3.  **Lighting:** Describe the lighting in detail (e.g., 'soft morning light filtering through a misty forest', 'dramatic Rembrandt lighting', 'golden hour glow').\n"
            f"4.  **Color Palette:** Suggest a dominant color palette (e.g., 'warm earth tones', 'cool blues and muted grays', 'vibrant neon colors').\n"
            f"5.  **Composition:** Use photographic terms like 'rule of thirds', 'leading lines', 'depth of field', 'wide-angle shot'.\n"
            f"6.  **Details & Emotion:** Add sensory details and emotional keywords to evoke a specific feeling (e.g., 'serene', 'melancholy', 'hopeful', 'mysterious').\n"
            f"7.  **Technical Specs:** Include terms like '8K, professional photography, sharp focus, high detail'.\n\n"
            f"**Output:** Provide only the final, enhanced prompt as a single line of text. Do not include any explanations or extra text."
        )
        response = await generate_with_gemini_auto_retry(request)
        return response.text.strip().replace("\n", " ").replace("*", "")
    except Exception as e:
        print(f"❌ Lỗi khi tối ưu hóa prompt (enhance_prompt): {e}")
        return None

def _split_sentences(text: str) -> list[str]:
    """Chia văn bản thành các câu một cách thông minh."""
    # Thay thế các dấu xuống dòng và khoảng trắng thừa bằng một dấu cách duy nhất
    text = re.sub(r'\s+', ' ', text).strip()
    if not text:
        return []
    # Sử dụng regex để tách câu dựa trên các dấu câu phổ biến
    sentences = re.split(r'(?<=[.?!…])\s+', text)
    return [s.strip() for s in sentences if s.strip()]

def ffmpeg_escape_text(text: str) -> str:
    """

    Escapes text to be safely used in an FFmpeg drawtext filter.

    Handles single quotes, colons, commas, brackets, percent signs, and backslashes.

    """
    if not isinstance(text, str):
        return ""
    # Trình tự escape rất quan trọng: backslash phải được xử lý trước tiên.
    return text.replace('\\', '\\\\') \
               .replace("'", "'\\\\''") \
               .replace(':', '\\:') \
               .replace(',', '\\,') \
               .replace('[', '\\[') \
               .replace(']', '\\]') \
               .replace('%', '%%')


async def convert_text_to_mp3(text: str, chat_id: int) -> tuple[str | None, str | None]:
    """

    Chuyển đổi văn bản thành file WAV với cơ chế retry thông minh (Exponential Backoff).

    """
    global GEMINI_API_KEYS_LIST
    
    async def send_error_log(base_message: str):
        error_traceback = traceback.format_exc()
        detailed_error_message = (f"❌ **Lỗi trong quá trình tạo Audio**\n\n" f"**Nguyên nhân:** {base_message}\n\n" f"--- Dấu vết lỗi (Traceback) ---\n" f"{error_traceback}")
        if len(detailed_error_message) > 4000: detailed_error_message = "...\n" + detailed_error_message[-4000:]
        await send_telegram_message(chat_id, detailed_error_message)

    if not GEMINI_API_KEYS_LIST:
        return None, "Lỗi cấu hình: Danh sách API key của Gemini trống."
    sentences = _split_sentences(text)
    if not sentences:
        return None, "Lỗi nội dung: Văn bản đầu vào không chứa câu hợp lệ."

    temp_wav_files = []
    last_api_error = "Không có lỗi API cụ thể."
    
    # --- Cấu hình cho cơ chế Backoff ---
    base_delay = 2  # Thời gian chờ ban đầu (giây)
    max_delay = 60 # Thời gian chờ tối đa
    max_retries_per_sentence = len(GEMINI_API_KEYS_LIST) * 2 # Cho phép thử lại mỗi key 2 lần
    
    for i, sentence in enumerate(sentences):
        print(f"--- Đang xử lý câu {i+1}/{len(sentences)}: '{sentence[:50]}...'")
        styled_text = f"(Giọng nam trầm ấm, trang nghiêm, tốc độ hơi nhanh, ngắt nghỉ tự nhiên) {sentence}"
        
        start_index = random.randint(0, len(GEMINI_API_KEYS_LIST) - 1)
        current_index = start_index
        attempts = 0
        success = False

        while attempts < max_retries_per_sentence:
            api_key = GEMINI_API_KEYS_LIST[current_index]
            url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key={api_key}"
            payload = { "model": "gemini-2.5-flash-preview-tts", "contents": [{"parts": [{"text": styled_text}]}], "generationConfig": { "responseModalities": ["AUDIO"], "speechConfig": { "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": "Algenib" }}}}}
            
            try:
                async with httpx.AsyncClient(timeout=60.0) as client:
                    response = await client.post(url, json=payload)
                    response.raise_for_status()
                
                response_json = response.json()
                candidate = response_json.get("candidates", [{}])[0]
                audio_part = candidate.get("content", {}).get("parts", [{}])[0]
                audio_content = audio_part.get("inlineData", {}).get("data")
                
                if audio_content:
                    audio_bytes = base64.b64decode(audio_content)
                    temp_raw_path = os.path.join(TEMP_PATH, f"part_{i}.raw")
                    with open(temp_raw_path, "wb") as f: f.write(audio_bytes)
                    temp_wav_path = os.path.join(TEMP_PATH, f"part_{i}.wav")
                    ffmpeg_pcm_to_wav = ['ffmpeg', '-y', '-f', 's16le', '-ar', '24000', '-ac', '1', '-i', temp_raw_path, temp_wav_path]
                    process = await asyncio.create_subprocess_exec(*ffmpeg_pcm_to_wav, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    await process.communicate()
                    if process.returncode != 0: raise ValueError("FFmpeg thất bại khi chuyển đổi raw PCM sang WAV.")
                    temp_wav_files.append(temp_wav_path)
                    os.remove(temp_raw_path)
                    success = True
                    break # Thoát khỏi vòng lặp while khi thành công
                else:
                    last_api_error = "Phản hồi API không chứa dữ liệu audio."
                    raise ValueError(last_api_error)

            except httpx.HTTPStatusError as e:
                last_api_error = str(e)
                if e.response.status_code == 429:
                    delay = min(base_delay * (2 ** (attempts // len(GEMINI_API_KEYS_LIST))) + random.uniform(0, 1), max_delay)
                    print(f"⚠️ API bị rate limit (429). Đang chờ {delay:.2f} giây trước khi thử lại...")
                    await asyncio.sleep(delay)
                else:
                    print(f"⚠️ Key Gemini index {current_index} bị lỗi HTTP {e.response.status_code}. Đang chuyển key...")
                    await asyncio.sleep(1) # Thêm 1s chờ nhỏ cho các lỗi HTTP khác
            except Exception as e:
                last_api_error = str(e)
                print(f"⚠️ Key Gemini index {current_index} bị lỗi TTS khác: {e}. Đang chuyển key...")
                await asyncio.sleep(1)
            
            # Chuyển sang key tiếp theo và tăng số lần thử
            current_index = (current_index + 1) % len(GEMINI_API_KEYS_LIST)
            attempts += 1

        if not success:
            error_msg = f"Tất cả các API key đều thất bại cho câu {i+1} sau nhiều lần thử. Lỗi cuối cùng: {last_api_error}"
            print(f"❌ {error_msg}")
            await send_error_log(error_msg)
            for f in temp_wav_files: 
                if os.path.exists(f): os.remove(f)
            return None, error_msg

    # --- Phần ghép file WAV (giữ nguyên) ---
    # ... (code ghép file không thay đổi)
    if not temp_wav_files: return None, "Không tạo được file audio tạm nào."

    try:
        print(f"✅ Đã tạo {len(temp_wav_files)} file audio nhỏ. Bắt đầu ghép nối...")
        final_wav_path = os.path.join(MP3_SAVE_PATH, f"autogen_audio_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.wav")
        concat_list_path = os.path.join(TEMP_PATH, "concat_list.txt")
        silence_wav_path = os.path.join(TEMP_PATH, "silence.wav")
        silence_duration = 0.7 
        if not os.path.exists(silence_wav_path):
            ffmpeg_create_silence = [ 'ffmpeg', '-y', '-f', 'lavfi', '-i', f'anullsrc=r=24000:cl=mono', '-t', str(silence_duration), silence_wav_path ]
            process = await asyncio.create_subprocess_exec(*ffmpeg_create_silence, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            await process.communicate()
            if process.returncode != 0: raise ValueError("Không thể tạo file im lặng.")
        with open(concat_list_path, "w") as f:
            for i, wav_file in enumerate(temp_wav_files):
                f.write(f"file '{os.path.abspath(wav_file)}'\n")
                if i < len(temp_wav_files) - 1: f.write(f"file '{os.path.abspath(silence_wav_path)}'\n")
        ffmpeg_cmd = [ 'ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', final_wav_path ]
        process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0: raise subprocess.CalledProcessError(process.returncode, ffmpeg_cmd, stderr=stderr)
        
        file_size_kb = os.path.getsize(final_wav_path) / 1024
        #await send_telegram_message(chat_id, f"✅ (Log) Đã ghép audio thành công:\n- Path: `{final_wav_path}`\n- Size: {file_size_kb:.2f} KB")

        print(f"✅ Ghép nối thành file WAV thành công: {final_wav_path}")
        return final_wav_path, None
    except Exception as e:
        error_detail = f"Lỗi FFMPEG khi ghép file: {e}"
        print(f"❌ {error_detail}")
        await send_error_log(error_detail)
        return None, error_detail
    finally:
        for f in temp_wav_files:
            if os.path.exists(f): os.remove(f)
        if os.path.exists(concat_list_path): os.remove(concat_list_path)




# THAY THẾ HOÀN TOÀN HÀM CŨ BẰNG HÀM MỚI DƯỚI ĐÂY
async def convert_text_to_mp32(text: str, chat_id: int) -> tuple[str | None, str | None]:
    """

    Chuyển đổi văn bản thành file WAV.

    [FINAL-2 CORRECTED] Sử dụng chính xác 100% model và payload từ mã nguồn tham khảo của người dùng.

    """
    global GEMINI_API_KEYS_LIST
    # Hàm phụ để gửi lỗi và traceback
    async def send_error_log(base_message: str):
        error_traceback = traceback.format_exc()
        detailed_error_message = (f"❌ **Lỗi trong quá trình tạo Audio**\n\n" f"**Nguyên nhân:** {base_message}\n\n" f"--- Dấu vết lỗi (Traceback) ---\n" f"{error_traceback}")
        if len(detailed_error_message) > 4000: detailed_error_message = "...\n" + detailed_error_message[-4000:]
        await send_telegram_message(chat_id, detailed_error_message)

    if not GEMINI_API_KEYS_LIST:
        return None, "Lỗi cấu hình: Danh sách API key của Gemini trống."
    sentences = _split_sentences(text)
    if not sentences:
        return None, "Lỗi nội dung: Văn bản đầu vào không chứa câu hợp lệ."

    temp_wav_files = []
    last_api_error = "Không có lỗi API cụ thể."
    
    for i, sentence in enumerate(sentences):
        print(f"--- Đang xử lý câu {i+1}/{len(sentences)}: '{sentence[:50]}...'")
        #styled_text = sentence
        styled_text = f"(Giọng nam trầm ấm, trang nghiêm, tốc độ hơi nhanh, ngắt nghỉ tự nhiên) {sentence}"
        start_index = random.randint(0, len(GEMINI_API_KEYS_LIST) - 1)
        current_index = start_index
        success = False
        while True:
            api_key = GEMINI_API_KEYS_LIST[current_index]
            
            # [SỬA LẠI CHO ĐÚNG 100% THEO FILE THAM KHẢO CỦA BẠN]
            url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key={api_key}"
            payload = {
                "model": "gemini-2.5-flash-preview-tts", # <--- SỬA LẠI ĐÚNG TÊN MODEL
                "contents": [{"parts": [{"text": styled_text}]}],
                "generationConfig": {
                    "responseModalities": ["AUDIO"],
                    "speechConfig": {
                        "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": "Algenib" }}
                    }
                }
            }
            
            try:
                async with httpx.AsyncClient(timeout=60.0) as client:
                    response = await client.post(url, json=payload)
                    response.raise_for_status()
                
                response_json = response.json()
                candidate = response_json.get("candidates", [{}])[0]
                audio_part = candidate.get("content", {}).get("parts", [{}])[0]
                audio_content = audio_part.get("inlineData", {}).get("data")
                
                if audio_content:
                    audio_bytes = base64.b64decode(audio_content)
                    temp_raw_path = os.path.join(TEMP_PATH, f"part_{i}.raw")
                    with open(temp_raw_path, "wb") as f: f.write(audio_bytes)
                    temp_wav_path = os.path.join(TEMP_PATH, f"part_{i}.wav")
                    ffmpeg_pcm_to_wav = ['ffmpeg', '-y', '-f', 's16le', '-ar', '24000', '-ac', '1', '-i', temp_raw_path, temp_wav_path]
                    process = await asyncio.create_subprocess_exec(*ffmpeg_pcm_to_wav, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    await process.communicate()
                    if process.returncode != 0: raise ValueError("FFmpeg thất bại khi chuyển đổi raw PCM sang WAV.")
                    temp_wav_files.append(temp_wav_path)
                    os.remove(temp_raw_path)
                    success = True
                    break
                else:
                    last_api_error = "Phản hồi API không chứa dữ liệu audio."
                    raise ValueError(last_api_error)
            except Exception as e:
                last_api_error = str(e)
                print(f"⚠️ Key Gemini index {current_index} bị lỗi TTS: {e}. Đang chuyển key...")
                current_index = (current_index + 1) % len(GEMINI_API_KEYS_LIST)
                if current_index == start_index:
                    error_msg = f"Tất cả các API key đều thất bại cho câu {i+1}. Lỗi cuối cùng: {last_api_error}"
                    print(f"❌ {error_msg}")
                    await send_error_log(error_msg)
                    for f in temp_wav_files: 
                        if os.path.exists(f): os.remove(f)
                    return None, error_msg
        
    # --- Phần ghép file WAV (giữ nguyên, đã đúng) ---
    if not temp_wav_files: return None, "Không tạo được file audio tạm nào."

    try:
        print(f"✅ Đã tạo {len(temp_wav_files)} file audio nhỏ. Bắt đầu ghép nối...")
        final_wav_path = os.path.join(MP3_SAVE_PATH, f"autogen_audio_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.wav")
        concat_list_path = os.path.join(TEMP_PATH, "concat_list.txt")
        silence_wav_path = os.path.join(TEMP_PATH, "silence.wav")
        silence_duration = 0.7 
        if not os.path.exists(silence_wav_path):
            ffmpeg_create_silence = [ 'ffmpeg', '-y', '-f', 'lavfi', '-i', f'anullsrc=r=24000:cl=mono', '-t', str(silence_duration), silence_wav_path ]
            process = await asyncio.create_subprocess_exec(*ffmpeg_create_silence, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            await process.communicate()
            if process.returncode != 0: raise ValueError("Không thể tạo file im lặng.")
        with open(concat_list_path, "w") as f:
            for i, wav_file in enumerate(temp_wav_files):
                f.write(f"file '{os.path.abspath(wav_file)}'\n")
                if i < len(temp_wav_files) - 1: f.write(f"file '{os.path.abspath(silence_wav_path)}'\n")
        ffmpeg_cmd = [ 'ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', final_wav_path ]
        process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0: raise subprocess.CalledProcessError(process.returncode, ffmpeg_cmd, stderr=stderr)
        
        # [THÊM MỚI] Gửi log xác nhận tạo file WAV thành công qua Telegram
        file_size_kb = os.path.getsize(final_wav_path) / 1024
        #await send_telegram_message(chat_id, f"✅ (Log) Đã ghép audio thành công:\n- Path: `{final_wav_path}`\n- Size: {file_size_kb:.2f} KB")

        print(f"✅ Ghép nối thành file WAV thành công: {final_wav_path}")
        return final_wav_path, None
    except Exception as e:
        error_detail = f"Lỗi FFMPEG khi ghép file: {e}"
        print(f"❌ {error_detail}")
        await send_error_log(error_detail)
        return None, error_detail
    finally:
        for f in temp_wav_files:
            if os.path.exists(f): os.remove(f)
        if os.path.exists(concat_list_path): os.remove(concat_list_path)

async def summarize_text_for_video(text: str, excel_row: int) -> list[str]:
    try:
        request = (f"Tóm tắt nội dung sau thành 2 câu thật ngắn gọn và hấp dẫn để làm phụ đề video. Mỗi câu 6-10 từ. Chỉ trả về 2 câu này, mỗi câu trên một dòng.\n\nNội dung: \"{text}\"")
        response = await generate_with_gemini_auto_retry(request)
        lines = [line.strip().replace('"', '').replace(':', '') for line in response.text.strip().split('\n') if line.strip()]
        if len(lines) >= 2:
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"D{excel_row}", lines[0])
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"E{excel_row}", lines[1])
            return lines[:2]
        elif len(lines) == 1:
             await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"D{excel_row}", lines[0])
             await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"E{excel_row}", "")
             return [lines[0], ""]
        return ["", ""]
    except Exception as e:
        print(f"❌ Lỗi khi tóm tắt nội dung cho hàng {excel_row}: {e}")
        return ["", ""]

# --- [THÊM MỚI] Hàm tóm tắt chỉ trả về text, không ghi vào Excel ---
# Dùng cho chức năng "Auto Get Contens MP3" để tránh ghi nhầm file
async def summarize_text_only(text: str) -> list[str]:
    """Tóm tắt văn bản thành 2 dòng và chỉ trả về kết quả, không ghi vào file."""
    try:
        request = (f"Tóm tắt nội dung sau thành 2 câu thật ngắn gọn và hấp dẫn. Mỗi câu 6-10 từ. Chỉ trả về 2 câu này, mỗi câu trên một dòng.\n\nNội dung: \"{text}\"")
        response = await generate_with_gemini_auto_retry(request)
        lines = [line.strip().replace('"', '').replace(':', '') for line in response.text.strip().split('\n') if line.strip()]
        if len(lines) >= 2:
            return lines[:2]
        elif len(lines) == 1:
            return [lines[0], ""]
        return ["", ""]
    except Exception as e:
        print(f"❌ Lỗi khi tóm tắt nội dung (text_only): {e}")
        return ["", ""]


def calculate_word_timestamps(text: str, mp3_duration: float) -> list[tuple[str, float, float]]:
    words = text.split()
    if not words: return []
    pause_time = (text.count('.') + text.count('?') + text.count('!')) * 0.75 + text.count(',') * 0.3
    net_speech_time = max(0, mp3_duration - pause_time)
    time_per_word = net_speech_time / len(words) if words else 0
    timestamps, current_time = [], 0.0
    for word in words:
        start_time = current_time
        duration = time_per_word
        current_time += duration
        if word.endswith(('.', '?', '!')): current_time += 0.7
        elif word.endswith(','): current_time += 0.25
        timestamps.append((word, start_time, start_time + duration))
    return timestamps


async def generate_video(image_path: str, mp3_path: str, line1: str, line2: str, karaoke_text: str | None, chat_id: int) -> str | None:
    """

    Tạo video từ ảnh và âm thanh.

    [UPDATED] Thêm log chi tiết gửi qua Telegram để gỡ lỗi.

    """
    # Hàm phụ gửi log lỗi chi tiết
    async def send_video_error_log(base_message: str):
        error_traceback = traceback.format_exc()
        detailed_error_message = (f"❌ **Lỗi trong quá trình tạo Video MP4**\n\n" f"**Nguyên nhân:** {base_message}\n\n" f"--- Dấu vết lỗi (Traceback) ---\n" f"{error_traceback}")
        if len(detailed_error_message) > 4000: detailed_error_message = "...\n" + detailed_error_message[-4000:]
        await send_telegram_message(chat_id, detailed_error_message)

    try:
        # [LOG 1] Kiểm tra sự tồn tại của các file đầu vào
        log_msg_1 = "--- ⚙️ (Log) Bắt đầu `generate_video` ---\n"
        log_msg_1 += f"Ảnh: `{image_path}` (Tồn tại: {os.path.exists(image_path)})\n"
        log_msg_1 += f"Audio: `{mp3_path}` (Tồn tại: {os.path.exists(mp3_path)})"
        #await send_telegram_message(chat_id, log_msg_1)
        
        # ... (phần lấy kích thước ảnh giữ nguyên)
        with Image.open(image_path) as img:
            w, h = img.size

        # [LOG 2] Lấy độ dài file audio bằng ffprobe
        #await send_telegram_message(chat_id, f"--- ⚙️ (Log) Đang lấy độ dài audio bằng `ffprobe`...")
        loop = asyncio.get_event_loop()
        ffprobe_cmd = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', mp3_path]
        result = await loop.run_in_executor(None, functools.partial(subprocess.check_output, ffprobe_cmd, stderr=subprocess.PIPE))
        mp3_duration = float(result.decode('utf-8').strip())
        #await send_telegram_message(chat_id, f"✅ (Log) Độ dài audio: `{mp3_duration}` giây.")

        # ... (phần xử lý tên file, font, và các filter text giữ nguyên y hệt)
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        output_filename = f"autogen_final_{timestamp}.mp4"
        full_output_path = os.path.join(MP4_SAVE_PATH, output_filename)
        escaped_font_path = FONT_FILE_PATH.replace('\\', '/')
        all_text_filters = []
        base_text_style = f"fontfile='{escaped_font_path}':fontcolor=yellow:fontsize=60:box=1:boxcolor=black@0.5:boxborderw=10"           
        line_spacing = 80
        
        if line1 and not pd.isna(line1):
            for i, word in enumerate(str(line1).split()):
                if word:
                    escaped_word = ffmpeg_escape_text(word)
                    all_text_filters.append(f"drawtext=text='{escaped_word}':x=100:y={220 + i*line_spacing}:{base_text_style}:enable='between(t,1,{mp3_duration-1})'")



        if line2 and not pd.isna(line2):
            for i, word in enumerate(str(line2).split()):
                if word:
                    escaped_word = ffmpeg_escape_text(word)
                    all_text_filters.append(f"drawtext=text='{escaped_word}':x=w-100-text_w:y={220 + i*line_spacing}:{base_text_style}:enable='between(t,1,{mp3_duration-1})'")
                    

  
        if karaoke_text:
            try:
                safe_karaoke_text = karaoke_text.replace('“', '"').replace('”', '"')
                word_timestamps = calculate_word_timestamps(safe_karaoke_text, mp3_duration)
                if not word_timestamps: raise ValueError("Không thể tạo bản đồ thời gian.")
                VIDEO_HEIGHT = 1920; ANIM_DURATION, FONT_SIZE, MAX_CHARS_PER_LINE = 0.4, 65, 38; Y_POS_1, Y_POS_2 = VIDEO_HEIGHT - 400, VIDEO_HEIGHT - 300
                        
                processed_text = karaoke_text.replace('.', '.|||').replace(',', ',|||').replace('?', '?|||').replace('!', '!|||')
                segments_raw = [seg.strip() for seg in processed_text.split('|||') if seg.strip()]
                
                final_lines = []
                for segment in segments_raw:
                    # 2. KIỂM TRA: Nếu phân đoạn dài hơn giới hạn, thì MỚI DÙNG textwrap
                    if len(segment) > MAX_CHARS_PER_LINE:
                        wrapped_lines = textwrap.wrap(segment, width=MAX_CHARS_PER_LINE, break_long_words=False, replace_whitespace=False)
                        final_lines.extend(wrapped_lines)
                    # 3. Nếu không, giữ nguyên phân đoạn gốc
                    else:
                        final_lines.append(segment)

                # 4. Nhóm các dòng cuối cùng (đã được xử lý) thành từng cặp để hiển thị
                display_groups, i = [], 0
                while i < len(final_lines):
                    if i + 1 < len(final_lines):
                        display_groups.append([final_lines[i], final_lines[i+1]])
                        i += 2
                    else:
                        display_groups.append([final_lines[i]])
                        i += 1
                        
                        
                        
                current_word_index = 0
                for group in display_groups:
                    group_word_count = len(" ".join(group).split())
                    if group_word_count == 0: continue
                    start_time = word_timestamps[current_word_index][1]
                    next_group_start_index = current_word_index + group_word_count
                    end_time = mp3_duration if next_group_start_index >= len(word_timestamps) else (word_timestamps[next_group_start_index][1] + ANIM_DURATION)
                    line1_raw, line2_raw = group[0], group[1] if len(group) > 1 else ""
                    line1_final, line2_final = line1_raw, line2_raw
                    if len(group) == 1 and len(line1_raw) > MAX_CHARS_PER_LINE:
                        mid_point = len(line1_raw) // 2; break_point = line1_raw.rfind(' ', 0, mid_point)
                        if break_point == -1: break_point = line1_raw.find(' ', mid_point)
                        if break_point != -1: line1_final, line2_final = line1_raw[:break_point], line1_raw[break_point+1:]
                    local_t_in = f"(t-{start_time})"; fade_out_start_time = end_time - ANIM_DURATION; local_t_out = f"(t-{fade_out_start_time})"
                    alpha_expr = f"'if(lt({local_t_in},{ANIM_DURATION}),{local_t_in}/{ANIM_DURATION},if(gt(t,{fade_out_start_time}),1-({local_t_out}/{ANIM_DURATION}),1))'"
                    base_style_karaoke = f"fontfile='{escaped_font_path}':fontcolor=white:borderw=3:bordercolor=black@0.9:shadowx=0:shadowy=0:shadowcolor=black@0.7:fontsize={FONT_SIZE}"
                                       
                    escaped_line1 = ffmpeg_escape_text(line1_final) # <--- SỬ DỤNG HÀM MỚI
                    filter1 = f"drawtext=text='{escaped_line1}':{base_style_karaoke}:x=(w-text_w)/2:y={Y_POS_1}:alpha={alpha_expr}:enable='between(t,{start_time},{end_time})'"
                    all_text_filters.append(filter1)
                    if line2_final:                       
                        escaped_line2 = ffmpeg_escape_text(line2_final) # <--- SỬ DỤNG HÀM MỚI
                        filter2 = f"drawtext=text='{escaped_line2}':{base_style_karaoke}:x=(w-text_w)/2:y={Y_POS_2}:alpha={alpha_expr}:enable='between(t,{start_time},{end_time})'"  
                        all_text_filters.append(filter2)
                    current_word_index += group_word_count
            except Exception as e: print(f"Lỗi khi tạo phụ đề karaoke động: {e}")

        # ... (phần lệnh FFmpeg giữ nguyên)
        ffmpeg_inputs = ['-i', image_path, '-i', mp3_path, '-stream_loop', '-1', '-i', BG_CHERRY_PATH]
        filter_complex_parts = [f"[0:v]loop=-1:size=1,setpts=PTS-STARTPTS,trim=duration={mp3_duration},scale=w=1080:h=1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1:1,fps=30[base_video];", f"[2:v]scale=1080:1920,format=rgba,colorchannelmixer=aa=0.3[effect_overlay];", f"[base_video][effect_overlay]overlay=x=0:y=0:shortest=1[video_with_bg];"]
        text_filter_chain = ",".join(all_text_filters)
        filter_complex_parts.append(f"[video_with_bg]{text_filter_chain},format=yuv420p[final_video]")
        full_filter_complex = "".join(filter_complex_parts)
        
        
        # [THÊM MỚI] Tạo một file script tạm thời để chứa chuỗi filter
        filter_script_path = os.path.join(TEMP_PATH, f"filter_script_{timestamp}.txt")
        try:
            with open(filter_script_path, 'w', encoding='utf-8') as f:
                f.write(full_filter_complex)

            # [THAY ĐỔI] Sử dụng -filter_complex_script thay vì -filter_complex
            ffmpeg_cmd = [
                'ffmpeg', '-y', *ffmpeg_inputs, 
                '-filter_complex_script', filter_script_path, # <-- Thay đổi quan trọng ở đây
                '-map', '[final_video]', '-map', '1:a', 
                '-c:v', 'libx264', '-preset', 'fast', '-crf', '23', 
                '-c:a', 'aac', '-b:a', '192k', 
                '-t', str(mp3_duration), '-s', '1080x1920', 
                '-pix_fmt', 'yuv420p', '-movflags', '+faststart', 
                full_output_path
            ]
            
            # [LOG 3] Gửi đi lệnh FFmpeg cuối cùng trước khi thực thi
            # Độ dài lệnh giờ đây sẽ luôn ngắn và an toàn.
            #await send_telegram_message(chat_id, f"--- ⚙️ (Log) Chuẩn bị thực thi lệnh FFmpeg qua script. Độ dài filter: {len(full_filter_complex)} ký tự.")

            process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            _, stderr = await process.communicate()
            if process.returncode != 0:
                # Nếu lệnh lỗi, ném ra exception để khối ngoài bắt được
                raise subprocess.CalledProcessError(process.returncode, ffmpeg_cmd, stderr=stderr)
            
            #await send_telegram_message(chat_id, f"✅ (Log) FFmpeg thực thi thành công. Đã tạo file video: `{full_output_path}`")
            return full_output_path
        finally:
            # [THÊM MỚI] Đảm bảo file script tạm thời luôn được xóa sau khi dùng xong
            if os.path.exists(filter_script_path):
                os.remove(filter_script_path)

    except Exception as e:
        # Gửi log lỗi chi tiết qua Telegram
        await send_video_error_log(str(e))
        return None

async def add_audio_to_video(video_path: str, mp3_path: str) -> str | None:
    output_filename = f"video_with_bgm_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
    output_path = os.path.join(TEMP_PATH, output_filename)
    ffmpeg_cmd = ['ffmpeg', '-y', '-i', video_path, '-stream_loop', '-1', '-i', mp3_path, '-filter_complex', "[0:a]volume=1.0[a0];[1:a]volume=0.3[a1];[a0][a1]amix=inputs=2:duration=first[aout]", '-map', '0:v', '-map', '[aout]', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-shortest', output_path]
    try:
        process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0: raise subprocess.CalledProcessError(process.returncode, ffmpeg_cmd, stderr=stderr)
        return output_path
    except Exception as e:
        print(f"❌ Lỗi FFmpeg khi ghép nhạc nền: {e}")
        if isinstance(e, subprocess.CalledProcessError): print(f"FFMPEG stderr: {e.stderr.decode('utf-8', errors='ignore')}")
        return None

async def generate_youtube_metadata(content: str, excel_row: int):
    try:
        prompt = (f"Dựa vào nội dung sau, hãy tạo Title (dưới 100 ký tự), Description (2-4 câu), và Tags (5-7 tags, cách nhau bởi dấu phẩy) cho video YouTube. Viết bằng tiếng Việt.\n\nNội dung: '{content}'\n\nChỉ trả về theo định dạng sau, không thêm bất kỳ giải thích nào:\nTITLE: [Tiêu đề ở đây]\nDESCRIPTION: [Mô tả ở đây]\nTAGS: [tag1, tag2, tag3]")
        response = await generate_with_gemini_auto_retry(prompt)
        yt_data = {}
        for line in response.text.strip().split('\n'):
            if line.startswith("TITLE:"): yt_data['title'] = line.replace("TITLE:", "").strip()
            elif line.startswith("DESCRIPTION:"): yt_data['description'] = line.replace("DESCRIPTION:", "").strip()
            elif line.startswith("TAGS:"): yt_data['tags'] = line.replace("TAGS:", "").strip()
        await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"J{excel_row}", yt_data.get('title', ''))
        await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"K{excel_row}", yt_data.get('description', ''))
        await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"L{excel_row}", yt_data.get('tags', ''))
    except Exception as e:
        print(f"⚠️ Không thể tạo metadata cho video hàng {excel_row}: {e}")

async def upload_to_youtube(mp3_content: str,account_number: int, video_path: str, image_path: str,  excel_row: int, chat_id: int):
    if not chat_id: return False
    if not os.path.exists(video_path):
        await send_telegram_message(chat_id, f"Lỗi upload: File video '{video_path}' không tồn tại.")
        return False

    try:
        # Bước 1: Lấy quyền truy cập Drive
        drive_credentials = await get_drive_credentials(chat_id)
        if not drive_credentials:
            raise Exception("Không thể lấy quyền truy cập Google Drive.")
        drive_service = build('drive', 'v3', credentials=drive_credentials)

        # Bước 2: Dùng quyền Drive để tải token của tài khoản YouTube cần upload
        yt_credentials = await get_youtube_credentials_from_drive(drive_service, account_number, chat_id)
        if not yt_credentials:
            raise Exception(f"Không thể lấy token cho tài khoản YouTube số {account_number}.")

        # Bước 3: Dùng đúng token của YouTube để upload
        await send_telegram_message(chat_id, f"✅ Bắt đầu upload video (Hàng {excel_row}) lên tài khoản {account_number}...")
        youtube = build('youtube', 'v3', credentials=yt_credentials)

        video_title = await read_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"J{excel_row}") or f"Video {excel_row - 1}"
        video_description = await read_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"K{excel_row}") or ""
        video_tags_str = await read_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"L{excel_row}") or ""
        video_tags = [tag.strip() for tag in video_tags_str.split(',') if tag.strip()]

        body = {
            'snippet': {'title': video_title, 'description': video_description, 'tags': video_tags, 'categoryId': '22'},
            'status': {'privacyStatus': 'public', 'selfDeclaredMadeForKids': False}
        }
        media = MediaFileUpload(video_path, chunksize=-1, resumable=True)
        request = youtube.videos().insert(part=",".join(body.keys()), body=body, media_body=media)

        response = None
        while response is None:
            status, response = await asyncio.to_thread(request.next_chunk)
            if status:
                print(f"Uploading... {int(status.progress() * 100)}%")

        video_id = response.get('id')
        # Gửi title video trong một tin nhắn riêng biệt để dễ copy
        await send_telegram_message(chat_id, video_title)
        
        # Gửi tin nhắn báo thành công kèm link
        await send_telegram_message(chat_id, f"🎉 Upload thành công! (Hàng {excel_row})\nLink: https://www.youtube.com/watch?v={video_id}")
        
        facebook_post_content = f"🙏 {video_title}\n\n{mp3_content}"
        if account_number == 3:
            await send_telegram_message(chat_id, f"ℹ️ Tài khoản {account_number} được chọn, bắt đầu quy trình đăng Facebook Page 1...")
            drive_video_id = await upload_video_to_drive_for_post(drive_service, video_path)
            if drive_video_id:
                # Dùng video title làm nội dung cho bài đăng Facebook
                await trigger_facebook_post(chat_id, facebook_post_content, drive_video_id)
            else:
                await send_telegram_message(chat_id, "❌ Không thể upload video lên Drive, đã hủy quy trình đăng Facebook.")

        if account_number == 10:
            await send_telegram_message(chat_id, f"ℹ️ Tài khoản {account_number} được chọn, bắt đầu quy trình đăng Facebook Page 2...")
            drive_video_id = await upload_video_to_drive_for_post(drive_service, video_path)
            if drive_video_id:
                # Dùng video title làm nội dung cho bài đăng Facebook
                await trigger_facebook_post2(chat_id, facebook_post_content, drive_video_id)
            else:
                await send_telegram_message(chat_id, "❌ Không thể upload video lên Drive, đã hủy quy trình đăng Facebook.")


        if account_number == 5 or account_number == 6:
            await send_telegram_message(chat_id, f"ℹ️ Tài khoản {account_number} được chọn, bắt đầu quy trình đăng IMAGE lên Facebook Page...")
            drive_image_id = await upload_image_to_drive_for_post(drive_service, image_path) # <-- THAY ĐỔI 2: Gọi hàm upload ảnh
            if drive_image_id:
                await trigger_facebook_post3(chat_id, facebook_post_content, drive_image_id) # <-- THAY ĐỔI 3: Truyền ID ảnh
            else:
                await send_telegram_message(chat_id, "❌ Không thể upload IMAGE lên Drive, đã hủy quy trình đăng Facebook.")

        if account_number == 2 or account_number == 9:
            await send_telegram_message(chat_id, f"ℹ️ Tài khoản {account_number} được chọn, bắt đầu quy trình đăng IMAGE lên Facebook Page...")
            drive_image_id = await upload_image_to_drive_for_post(drive_service, image_path) # <-- THAY ĐỔI 4: Gọi hàm upload ảnh
            if drive_image_id:
                await trigger_facebook_post4(chat_id, facebook_post_content, drive_image_id) # <-- THAY ĐỔI 5: Truyền ID ảnh
            else:
                await send_telegram_message(chat_id, "❌ Không thể upload IMAGE lên Drive, đã hủy quy trình đăng Facebook.")


        return True

    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi upload video hàng {excel_row} (TK {account_number}): {e}")
        return False

# --- QUY TRÌNH CHÍNH (XỬ LÝ HÀNG LOẠT) ---
async def batch_process_autogen_videos(chat_id: int, user_data: dict):
    print(f"\n--- [TRACE] Entering batch_process_autogen_videos for chat_id {chat_id} ---")
    credentials = await get_drive_credentials(chat_id)
    if not credentials:
        await send_telegram_message(chat_id, "Lỗi nghiêm trọng: Không thể lấy credentials để chạy batch.")
        return
    drive_service = build('drive', 'v3', credentials=credentials)

    num_videos = user_data.get('video_count', 0)
    should_upload = user_data.get('upload_yt', False)
    image_source = user_data.get('image_source', 'auto')
    if num_videos == 0: return

    # [LOGIC MỚI] Khởi tạo pool tài khoản để upload
    original_selected_accounts = user_data.get('selected_yt_accounts', [])
    upload_pool = list(original_selected_accounts)

    await send_telegram_message(chat_id, f"🚀 **Bắt đầu quy trình 1: Auto Gen Video (Image)** cho {num_videos} video...\nNguồn ảnh: {'Tự tạo' if image_source == 'auto' else 'Dùng sẵn'}\nUpload YouTube: {'Có' if should_upload else 'Không'}")
    
    try:
        df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
        autogen_vertexai_model = None
        image_ideas = []
        if image_source == 'auto':
            autogen_vertexai_model = ImageGenerationModel.from_pretrained(MODALNAME)
            image_ideas = df_input.iloc[1:, 14].dropna().astype(str).tolist()
            if not image_ideas: raise ValueError("Cột ý tưởng ảnh (O) trong sheet 'Input' bị trống.")
        mp3_themes = df_input.iloc[1:, 15].dropna().astype(str).tolist()
        mp3_topics = df_input.iloc[1:, 16].dropna().astype(str).tolist()
        if not all([mp3_themes, mp3_topics]): raise ValueError("Cột chủ đề MP3 (P, Q) bị trống.")
    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi đọc dữ liệu nguồn từ Excel: {e}")
        return

    available_images_from_drive = []
    if image_source == 'common':
        available_images_from_drive = await get_image_list_from_drive(drive_service)
        if not available_images_from_drive:
            await send_telegram_message(chat_id, f"❌ Lỗi: Thư mục ảnh trên Drive (ID: {DRIVE_IMAGE_FOLDER_ID}) rỗng hoặc không truy cập được.")
            return

    success_count, fail_count = 0, 0
    df_autogen = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='AutoGen', header=None)
    start_row = df_autogen.shape[0] + 1

    for i in range(num_videos):
        current_row = start_row + i
        video_info = f"Video {i + 1}/{num_videos} (Hàng {current_row})"
        image_id_to_delete = None
        image_path = ""
        try:
            print(f"--- Bắt đầu xử lý {video_info} ---")
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row}", "Inprogress")
            await send_telegram_message(chat_id, f"--- ⚙️ Đang xử lý {video_info} ---")
            
            if image_source == 'common':
                print("Đang chọn ảnh từ Drive...")
                if not available_images_from_drive:
                    await send_telegram_message(chat_id, "Đã hết ảnh trong thư mục Drive.")
                    break
                selected_image = random.choice(available_images_from_drive)
                available_images_from_drive.remove(selected_image)
                image_id_to_delete = selected_image.get('id')
                image_name = selected_image.get('name')
                image_path = os.path.join(TEMP_PATH, image_name)
                await download_file_from_drive(drive_service, image_id_to_delete, image_path)
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"R{current_row}", f"From Drive: {image_name}")
                print("Đã tạo ảnh xong.")
            else: # auto
                print("Đang tạo ảnh bằng AI...")
                idea = random.choice(image_ideas)
                prompt = await enhance_prompt(idea)
                if not prompt: raise ValueError("Không thể tạo prompt ảnh.")
                await send_telegram_message(chat_id, f"🎨 Đang tạo ảnh với prompt: `{prompt}`")
                response = await asyncio.to_thread(
                    autogen_vertexai_model.generate_images,
                    prompt=prompt, number_of_images=1, aspect_ratio="9:16"
                )
                if not response.images: raise ValueError("Không thể tạo ảnh từ Vertex AI.")
                image_path = os.path.join(IMAGE_SAVE_PATH, f"autogen_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
                response.images[0].save(location=image_path)
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"R{current_row}", prompt)

            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"B{current_row}", image_path)

            selected_full_topic = random.choice(mp3_topics)
            parts = selected_full_topic.split('|', 1)
            core_theme = parts[0].strip() if len(parts) == 2 else selected_full_topic
            hook_example = parts[1].strip() if len(parts) == 2 else selected_full_topic
            full_topic = f"{core_theme} | {hook_example}"
  
            print("Đang tạo nội dung MP3...")           
            mp3_prompt = (
                f"BẠN LÀ MỘT HỆ THỐNG AI SÁNG TẠO NỘI DUNG. VAI TRÒ DUY NHẤT CỦA BẠN LÀ THỰC HIỆN CÁC BƯỚC SAU MỘT CÁCH ÂM THẦM VÀ CHỈ TRẢ VỀ KẾT QUẢ CUỐI CÙNG THEO ĐÚNG ĐỊNH DẠNG YÊU CẦU.\n\n"
                f"--- VAI TRÒ SÁNG TẠO CỐT LÕI ---\n"
                f"Bên trong hệ thống này, bạn phải hóa thân thành một **giảng sư Phật pháp bậc thầy**, đồng thời là một chuyên gia sáng tạo nội dung viral am hiểu sâu sắc tâm lý khán giả. Giọng văn của bạn vừa uyên thâm, trang nghiêm, vừa có khả năng tạo ra những câu mở đầu 3 giây gây chấn động.\n\n"
                f"--- BỐI CẢNH & DỮ LIỆU ĐẦU VÀO ---\n"
                f"Mục tiêu là tạo ra một kịch bản pháp thoại ngắn (khoảng 240-270 từ) cho video ngắn.\n"
                f"Yêu cầu đầu vào có cấu trúc: **`Chủ đề cốt lõi | Câu hook ví dụ`**.\n"
                f"Yêu cầu hiện tại: **`{full_topic}`**\n\n"
                f"--- QUY TRÌNH XỬ LÝ BẮT BUỘC (ĐÂY LÀ HƯỚNG DẪN ĐỂ BẠN LÀM THEO, KHÔNG PHẢI ĐỂ LẶP LẠI) ---\n"
                f"1.  **PHÂN TÍCH VÀ SÁNG TẠO HOOK:** Phân tích [Câu hook ví dụ] để hiểu phong cách. Dựa trên [Chủ đề cốt lõi], sáng tạo ra một vài câu hook mới theo các kỹ thuật 'câu hỏi xoáy sâu', 'tuyên bố gây sốc', hoặc 'kịch bản quen thuộc'.\n"
                f"2.  **CHỌN LỌC:** Từ các hook đã sáng tạo, chọn ra một (1) câu hook mạnh mẽ và phù hợp nhất để bắt đầu bài pháp thoại.\n"
                f"3.  **SOẠN KỊCH BẢN:** Sử dụng câu hook đã chọn làm câu mở đầu, viết phần thân bài và kết bài theo các tiêu chí sau:\n"
                f"    * **Thân bài (Khai thị):** Hãy phân tích chủ đề một cách sâu sắc và đa dạng. Hãy linh hoạt và sáng tạo, tránh lặp lại một vài khái niệm hay câu chuyện quen thuộc. Sử dụng kết hợp các yếu tố sau:\n"
                f"       - **Phân tích Gốc rễ Nỗi khổ:** Dùng tuệ giác Phật pháp để soi chiếu vào nguyên nhân sâu xa. (Ví dụ: do Tam độc như **Tham, Sân, Si**; do **Ngã mạn** (cái tôi quá lớn); do sự **Chấp thủ, Ganh tỵ, Vọng tưởng**...).\n"
                f"       - **Dẫn lời Phật dạy & Khái niệm:** Đưa các giáo lý cốt lõi vào bài giảng một cách tự nhiên. (Ví dụ: **Tứ Diệu Đế, Bát Chánh Đạo, luật Nhân quả - Nghiệp báo, Duyên khởi, Vô thường, Vô ngã, Tứ Vô Lượng Tâm (Từ, Bi, Hỷ, Xả), Chánh niệm, Ngũ Uẩn, Thập Nhị Nhân Duyên, Lục Độ Ba La Mật (Bố thí, Trì giới, Nhẫn nhục, Tinh tấn, Thiền định, Trí tuệ), Tam Pháp Ấn (Vô Thường, Khổ, Vô Ngã), Tánh Không, Phật tính**...).\n"
                f"       - **Nêu gương & Kể chuyện:** Dùng các câu chuyện, tấm gương để bài giảng thêm sống động. (Ví dụ: tấm gương hiếu thảo của **Bồ tát Mục Kiền Liên**; lòng từ bi của **Bồ tát Quán Thế Âm**; hạnh nguyện cứu độ chúng sinh của **Bồ tát Địa Tạng**; trí tuệ của **Bồ tát Văn Thù Sư Lợi**; hạnh nguyện của **Bồ tát Phổ Hiền**; câu chuyện về **Tôn giả A Nan, Tôn giả Xá Lợi Phất, Tôn giả Phú Lâu Na**; **các câu chuyện ngụ ngôn Phật giáo** như **'Con hổ và quả dâu', 'Cá và sóng', 'Chuyện người chăn bò Nanda'**; hoặc tấm gương của các vị **Phật A Di Đà, Phật Dược Sư**...).\n"       
                f"       - **Đưa ra Giải pháp Chuyển hóa:** Hướng người nghe đến một hành động cụ thể, có thể thực hành được. (Ví dụ: thực hành **buông bỏ, hành thiền quán chiếu, thực hành sám hối, niệm Phật, bố thí, trì giới, phụng sự chúng sinh, khởi tâm từ bi**...).\n"
                f"    * **Kết bài (Hồi hướng):** Kết thúc bằng một lời kêu gọi gieo duyên lành (bình luận 'Nam Mô A Di Đà Phật', 'An Lành', chia sẻ, hoặc theo dõi kênh).\n\n"
                f"--- ĐỊNH DẠNG ĐẦU RA TUYỆT ĐỐI ---\n"
                f"**QUAN TRỌNG NHẤT:** TUYỆT ĐỐI KHÔNG được hiển thị các bước suy nghĩ, các lựa chọn hook, hay bất kỳ dòng nào có chứa chữ 'BƯỚC', 'HOOK', 'KỸ THUẬT', hoặc các dấu `*`. Đầu ra của bạn PHẢI bắt đầu trực tiếp bằng câu hook đã chọn và là một khối văn bản liền mạch.\n\n"
                f"BÀI PHÁP THOẠI HOÀN CHỈNH:"
            )
            mp3_response = await generate_with_gemini_auto_retry(mp3_prompt)
            mp3_content = mp3_response.text.strip()
            
            print("Đang chuyển đổi MP3...")
            wav_path, error_message = await convert_text_to_mp3(mp3_content, chat_id)
            if error_message:
                error_full_message = f"Không thể tạo file WAV: {error_message}"
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row}", f"Error: {error_full_message}")
                fail_count += 1
                continue
            
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"C{current_row}", mp3_content)
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"F{current_row}", wav_path)
            print("Đang tóm tắt nội dung...")
            summary_lines = await summarize_text_for_video(mp3_content, current_row)
            print("Đang tạo video...")
            final_video_path = await generate_video(image_path, wav_path, summary_lines[0], summary_lines[1], mp3_content, chat_id)
            
            if not final_video_path: raise ValueError("Không thể tạo file MP4.")
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"G{current_row}", final_video_path)
            await send_telegram_message(chat_id, f"✅ Tạo thành công {video_info}. Đang gửi file...")
            await send_telegram_video(chat_id, final_video_path, f"Video của bạn: {video_info}")
            
            if should_upload and original_selected_accounts:
                if not upload_pool:
                    print("--- Hồi phục danh sách tài khoản upload ---")
                    upload_pool = list(original_selected_accounts)
                
                account_to_use = upload_pool.pop(random.randrange(len(upload_pool)))
                
                await generate_youtube_metadata(mp3_content, current_row)
                video_with_bgm = await add_audio_to_video(final_video_path, YTB_MP3_BG_PATH)
                video_to_upload = video_with_bgm if video_with_bgm else final_video_path
                await upload_to_youtube(mp3_content,account_to_use, video_to_upload, image_path, current_row, chat_id)

            if image_source == 'common' and image_id_to_delete:
                print(f"Đang xóa ảnh {image_id_to_delete} khỏi Drive...")
                await delete_file_from_drive(drive_service, image_id_to_delete)
                if os.path.exists(image_path): os.remove(image_path)

            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row}", "Finished")
            success_count += 1
            print(f"--- Hoàn thành xử lý {video_info} ---")
        except Exception as e:
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row}", f"Error: {e}")
            fail_count += 1
            await send_telegram_message(chat_id, f"❌ Lỗi khi xử lý {video_info}: {e}")

    summary = f"📊 **BÁO CÁO HOÀN TẤT (Chức năng 1)**\n- ✅ Thành công: {success_count}\n- ❌ Thất bại: {fail_count}"
    await send_telegram_message(chat_id, summary)
    print("Đang upload file Excel đã cập nhật lên Drive...")
    await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)

# --- [THÊM MỚI] Chức năng 2: Chỉ tạo nội dung MP3 và lưu vào file GenMP3.xlsx ---
async def batch_process_autogen_mp3_content(chat_id: int, user_data: dict):
    print(f"\n--- [TRACE] Entering batch_process_autogen_mp3_content for chat_id {chat_id} ---")
    credentials = await get_drive_credentials(chat_id)
    if not credentials:
        await send_telegram_message(chat_id, "Lỗi nghiêm trọng: Không thể lấy credentials để chạy batch.")
        return
    drive_service = build('drive', 'v3', credentials=credentials)

    num_mp3s = user_data.get('mp3_count', 0)
    if num_mp3s == 0: return

    await send_telegram_message(chat_id, f"🚀 **Bắt đầu quy trình 2: Auto Get Contens MP3** cho {num_mp3s} nội dung...")
    
    try:
        # Đọc dữ liệu nguồn từ sheet Input
        df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
        mp3_themes = df_input.iloc[1:, 15].dropna().astype(str).tolist()
        mp3_topics = df_input.iloc[1:, 16].dropna().astype(str).tolist()
        if not all([mp3_themes, mp3_topics]):
            raise ValueError("Cột chủ đề MP3 (P, Q) trong sheet 'Input' bị trống.")
    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi đọc dữ liệu nguồn từ Excel: {e}")
        return

    success_count, fail_count = 0, 0
    # Đọc file GenMP3 để xác định dòng bắt đầu ghi
    df_gen_mp3 = pd.read_excel(MP3_CONTENT_EXCEL_PATH, sheet_name='GenMP3', header=None)
    start_row = df_gen_mp3.shape[0] + 1

    for i in range(num_mp3s):
        current_row = start_row + i
        mp3_info = f"Nội dung MP3 {i + 1}/{num_mp3s} (Hàng {current_row})"
        try:
            print(f"--- Bắt đầu xử lý {mp3_info} ---")
            await send_telegram_message(chat_id, f"--- ⚙️ Đang xử lý {mp3_info} ---")
            
            # Tạo chủ đề ngẫu nhiên
            selected_full_topic = random.choice(mp3_topics)

            # Tách chuỗi tại ký tự '|' do chính bạn quy định
            parts = selected_full_topic.split('|', 1)

            # Nếu bạn đã chuẩn bị đúng định dạng, code sẽ luôn chạy đúng
            if len(parts) == 2:
                core_theme = parts[0].strip()
                hook_example = parts[1].strip()
            else:
                # Cơ chế dự phòng nếu bạn quên đặt dấu '|'
                core_theme = selected_full_topic
                hook_example = selected_full_topic

            # Tạo full_topic để đưa vào prompt
            full_topic = f"{core_theme} | {hook_example}"
  
            print("Đang tạo nội dung MP3...")
            mp3_prompt = (
                f"BẠN LÀ MỘT HỆ THỐNG AI SÁNG TẠO NỘI DUNG. VAI TRÒ DUY NHẤT CỦA BẠN LÀ THỰC HIỆN CÁC BƯỚC SAU MỘT CÁCH ÂM THẦM VÀ CHỈ TRẢ VỀ KẾT QUẢ CUỐI CÙNG THEO ĐÚNG ĐỊNH DẠNG YÊU CẦU.\n\n"
                f"--- VAI TRÒ SÁNG TẠO CỐT LÕI ---\n"
                f"Bên trong hệ thống này, bạn phải hóa thân thành một **giảng sư Phật pháp bậc thầy**, đồng thời là một chuyên gia sáng tạo nội dung viral am hiểu sâu sắc tâm lý khán giả. Giọng văn của bạn vừa uyên thâm, trang nghiêm, vừa có khả năng tạo ra những câu mở đầu 3 giây gây chấn động.\n\n"
                f"--- BỐI CẢNH & DỮ LIỆU ĐẦU VÀO ---\n"
                f"Mục tiêu là tạo ra một kịch bản pháp thoại ngắn (khoảng 240-270 từ) cho video ngắn.\n"
                f"Yêu cầu đầu vào có cấu trúc: **`Chủ đề cốt lõi | Câu hook ví dụ`**.\n"
                f"Yêu cầu hiện tại: **`{full_topic}`**\n\n"
                f"--- QUY TRÌNH XỬ LÝ BẮT BUỘC (ĐÂY LÀ HƯỚNG DẪN ĐỂ BẠN LÀM THEO, KHÔNG PHẢI ĐỂ LẶP LẠI) ---\n"
                f"1.  **PHÂN TÍCH VÀ SÁNG TẠO HOOK:** Phân tích [Câu hook ví dụ] để hiểu phong cách. Dựa trên [Chủ đề cốt lõi], sáng tạo ra một vài câu hook mới theo các kỹ thuật 'câu hỏi xoáy sâu', 'tuyên bố gây sốc', hoặc 'kịch bản quen thuộc'.\n"
                f"2.  **CHỌN LỌC:** Từ các hook đã sáng tạo, chọn ra một (1) câu hook mạnh mẽ và phù hợp nhất để bắt đầu bài pháp thoại.\n"
                f"3.  **SOẠN KỊCH BẢN:** Sử dụng câu hook đã chọn làm câu mở đầu, viết phần thân bài và kết bài theo các tiêu chí sau:\n"
                f"    * **Thân bài (Khai thị):** Hãy phân tích chủ đề một cách sâu sắc và đa dạng. Hãy linh hoạt và sáng tạo, tránh lặp lại một vài khái niệm hay câu chuyện quen thuộc. Sử dụng kết hợp các yếu tố sau:\n"
                f"       - **Phân tích Gốc rễ Nỗi khổ:** Dùng tuệ giác Phật pháp để soi chiếu vào nguyên nhân sâu xa. (Ví dụ: do Tam độc như **Tham, Sân, Si**; do **Ngã mạn** (cái tôi quá lớn); do sự **Chấp thủ, Ganh tỵ, Vọng tưởng**...).\n"
                f"       - **Dẫn lời Phật dạy & Khái niệm:** Đưa các giáo lý cốt lõi vào bài giảng một cách tự nhiên. (Ví dụ: **Tứ Diệu Đế, Bát Chánh Đạo, luật Nhân quả - Nghiệp báo, Duyên khởi, Vô thường, Vô ngã, Tứ Vô Lượng Tâm (Từ, Bi, Hỷ, Xả), Chánh niệm, Ngũ Uẩn, Thập Nhị Nhân Duyên, Lục Độ Ba La Mật (Bố thí, Trì giới, Nhẫn nhục, Tinh tấn, Thiền định, Trí tuệ), Tam Pháp Ấn (Vô Thường, Khổ, Vô Ngã), Tánh Không, Phật tính**...).\n"
                f"       - **Nêu gương & Kể chuyện:** Dùng các câu chuyện, tấm gương để bài giảng thêm sống động. (Ví dụ: tấm gương hiếu thảo của **Bồ tát Mục Kiền Liên**; lòng từ bi của **Bồ tát Quán Thế Âm**; hạnh nguyện cứu độ chúng sinh của **Bồ tát Địa Tạng**; trí tuệ của **Bồ tát Văn Thù Sư Lợi**; hạnh nguyện của **Bồ tát Phổ Hiền**; câu chuyện về **Tôn giả A Nan, Tôn giả Xá Lợi Phất, Tôn giả Phú Lâu Na**; **các câu chuyện ngụ ngôn Phật giáo** như **'Con hổ và quả dâu', 'Cá và sóng', 'Chuyện người chăn bò Nanda'**; hoặc tấm gương của các vị **Phật A Di Đà, Phật Dược Sư**...).\n"       
                f"       - **Đưa ra Giải pháp Chuyển hóa:** Hướng người nghe đến một hành động cụ thể, có thể thực hành được. (Ví dụ: thực hành **buông bỏ, hành thiền quán chiếu, thực hành sám hối, niệm Phật, bố thí, trì giới, phụng sự chúng sinh, khởi tâm từ bi**...).\n"
                f"    * **Kết bài (Hồi hướng):** Kết thúc bằng một lời kêu gọi gieo duyên lành (bình luận 'Nam Mô A Di Đà Phật', 'An Lành', chia sẻ, hoặc theo dõi kênh).\n\n"
                f"--- ĐỊNH DẠNG ĐẦU RA TUYỆT ĐỐI ---\n"
                f"**QUAN TRỌNG NHẤT:** TUYỆT ĐỐI KHÔNG được hiển thị các bước suy nghĩ, các lựa chọn hook, hay bất kỳ dòng nào có chứa chữ 'BƯỚC', 'HOOK', 'KỸ THUẬT', hoặc các dấu `*`. Đầu ra của bạn PHẢI bắt đầu trực tiếp bằng câu hook đã chọn và là một khối văn bản liền mạch.\n\n"
                f"BÀI PHÁP THOẠI HOÀN CHỈNH:"
            )
            
            mp3_response = await generate_with_gemini_auto_retry(mp3_prompt)
            mp3_content = mp3_response.text.strip()
            
            
            # Tóm tắt nội dung mà không ghi vào file Excel nào
            summary_lines = await summarize_text_only(mp3_content)
            
            # Ghi kết quả vào file GenMP3.xlsx
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"A{current_row}", mp3_content)
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"B{current_row}", summary_lines[0])
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"C{current_row}", summary_lines[1])
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"E{current_row}", "NYS") # Trạng thái: Not Yet Started

            success_count += 1
            print(f"--- Hoàn thành xử lý {mp3_info} ---")
            await send_telegram_message(chat_id, f"✅ Đã tạo thành công {mp3_info}")

        except Exception as e:
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"A{current_row}", f"Error: {e}")
            fail_count += 1
            await send_telegram_message(chat_id, f"❌ Lỗi khi xử lý {mp3_info}: {e}")

    summary = f"📊 **BÁO CÁO HOÀN TẤT (Chức năng 2)**\n- ✅ Thành công: {success_count}\n- ❌ Thất bại: {fail_count}"
    await send_telegram_message(chat_id, summary)
    print("Đang upload file Excel GenMP3.xlsx đã cập nhật lên Drive...")
    await upload_file_to_drive(drive_service, MP3_CONTENT_EXCEL_PATH, DRIVE_MP3_CONTENT_FILE_ID)


# --- [THÊM MỚI] Chức năng 3: Tạo video từ ảnh và nội dung MP3 có sẵn ---
async def batch_process_from_premade_mp3(chat_id: int, user_data: dict):
    print(f"\n--- [TRACE] Entering batch_process_from_premade_mp3 for chat_id {chat_id} ---")
    credentials = await get_drive_credentials(chat_id)
    if not credentials:
        await send_telegram_message(chat_id, "Lỗi nghiêm trọng: Không thể lấy credentials để chạy batch.")
        return
    drive_service = build('drive', 'v3', credentials=credentials)

    num_videos = user_data.get('video_count', 0)
    should_upload = user_data.get('upload_yt', False)
    image_source = user_data.get('image_source', 'auto')
    if num_videos == 0: return
    
    # [LOGIC MỚI] Khởi tạo pool tài khoản để upload
    original_selected_accounts = user_data.get('selected_yt_accounts', [])
    upload_pool = list(original_selected_accounts)

    await send_telegram_message(chat_id, f"🚀 **Bắt đầu quy trình 3: Auto Gen Video (Image & MP3)** cho {num_videos} video...")

    try:
        df_mp3_content = pd.read_excel(MP3_CONTENT_EXCEL_PATH, sheet_name='GenMP3', header=None)
        available_content = df_mp3_content[(df_mp3_content.iloc[:, 4].isna()) | (df_mp3_content.iloc[:, 4].str.upper() == 'NYS')]

        if len(available_content) < num_videos:
            await send_telegram_message(chat_id, f"⚠️ **Cảnh báo:** Không đủ nội dung MP3 có sẵn (cần {num_videos}, có {len(available_content)}). Vui lòng chạy chức năng 2 trước.")
            return
        
        content_to_use = available_content.head(num_videos)
        
        df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
        autogen_vertexai_model = None
        image_ideas = []
        if image_source == 'auto':
            autogen_vertexai_model = ImageGenerationModel.from_pretrained(MODALNAME)
            image_ideas = df_input.iloc[1:, 14].dropna().astype(str).tolist()
            if not image_ideas: raise ValueError("Cột ý tưởng ảnh (O) trong sheet 'Input' bị trống.")

    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi đọc dữ liệu nguồn: {e}")
        return

    available_images_from_drive = []
    if image_source == 'common':
        available_images_from_drive = await get_image_list_from_drive(drive_service)
        if not available_images_from_drive:
            await send_telegram_message(chat_id, f"❌ Lỗi: Thư mục ảnh trên Drive rỗng hoặc không truy cập được.")
            return

    success_count, fail_count = 0, 0
    df_autogen = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='AutoGen', header=None)
    start_row_autogen = df_autogen.shape[0] + 1

    for i, (mp3_row_index, mp3_data) in enumerate(content_to_use.iterrows()):
        current_row_autogen = start_row_autogen + i
        current_row_genmp3 = mp3_row_index + 1 
        video_info = f"Video {i + 1}/{num_videos} (Hàng AutoGen {current_row_autogen} | Hàng GenMP3 {current_row_genmp3})"
        image_id_to_delete = None
        image_path = ""
        try:
            print(f"--- Bắt đầu xử lý {video_info} ---")
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row_autogen}", "Inprogress")
            await send_telegram_message(chat_id, f"--- ⚙️ Đang xử lý {video_info} ---")

            if image_source == 'common':
                if not available_images_from_drive:
                    await send_telegram_message(chat_id, "Đã hết ảnh trong thư mục Drive.")
                    break
                selected_image = random.choice(available_images_from_drive)
                available_images_from_drive.remove(selected_image)
                image_id_to_delete = selected_image.get('id')
                image_name = selected_image.get('name')
                image_path = os.path.join(TEMP_PATH, image_name)
                await download_file_from_drive(drive_service, image_id_to_delete, image_path)
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"R{current_row_autogen}", f"From Drive: {image_name}")
            else: # auto
                idea = random.choice(image_ideas)
                prompt = await enhance_prompt(idea)
                if not prompt: raise ValueError("Không thể tạo prompt ảnh.")
                await send_telegram_message(chat_id, f"🎨 Đang tạo ảnh với prompt: `{prompt}`")
                response = await asyncio.to_thread(
                    autogen_vertexai_model.generate_images,
                    prompt=prompt, number_of_images=1, aspect_ratio="9:16"
                )
                if not response.images: raise ValueError("Không thể tạo ảnh từ Vertex AI.")
                image_path = os.path.join(IMAGE_SAVE_PATH, f"autogen_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.png")
                response.images[0].save(location=image_path)
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"R{current_row_autogen}", prompt)
            
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"B{current_row_autogen}", image_path)

            mp3_content = str(mp3_data.iloc[0])
            summary_line1 = str(mp3_data.iloc[1])
            summary_line2 = str(mp3_data.iloc[2])

            print("Đang chuyển đổi text có sẵn sang MP3...")
            wav_path, error_message = await convert_text_to_mp3(mp3_content, chat_id)
            if error_message:
                error_full_message = f"Không thể tạo file WAV: {error_message}"
                await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row_autogen}", f"Error: {error_full_message}")
                fail_count += 1
                continue
                
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"C{current_row_autogen}", mp3_content)
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"D{current_row_autogen}", summary_line1)
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"E{current_row_autogen}", summary_line2)
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"F{current_row_autogen}", wav_path)
            
            print("Đang tạo video...")
            final_video_path = await generate_video(image_path, wav_path, summary_line1, summary_line2, mp3_content, chat_id)
            if not final_video_path: raise ValueError("Không thể tạo file MP4.")

            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"G{current_row_autogen}", final_video_path)
            await send_telegram_message(chat_id, f"✅ Tạo thành công {video_info}. Đang gửi file...")
            await send_telegram_video(chat_id, final_video_path, f"Video của bạn: {video_info}")
            
            if should_upload and original_selected_accounts:
                if not upload_pool:
                    print("--- Hồi phục danh sách tài khoản upload ---")
                    upload_pool = list(original_selected_accounts)
                
                account_to_use = upload_pool.pop(random.randrange(len(upload_pool)))
                
                await generate_youtube_metadata(mp3_content, current_row_autogen)
                video_with_bgm = await add_audio_to_video(final_video_path, YTB_MP3_BG_PATH)
                video_to_upload = video_with_bgm if video_with_bgm else final_video_path
                await upload_to_youtube(mp3_content,account_to_use, video_to_upload, image_path, current_row_autogen, chat_id)

            if image_source == 'common' and image_id_to_delete:
                await delete_file_from_drive(drive_service, image_id_to_delete)
                if os.path.exists(image_path): os.remove(image_path)

            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row_autogen}", "Finished")
            await update_excel_cell(MP3_CONTENT_EXCEL_PATH, "GenMP3", f"F{current_row_genmp3}", "Finished")
            success_count += 1
            print(f"--- Hoàn thành xử lý {video_info} ---")
        except Exception as e:
            await update_excel_cell(WORKING_EXCEL_PATH, "AutoGen", f"A{current_row_autogen}", f"Error: {e}")
            fail_count += 1
            await send_telegram_message(chat_id, f"❌ Lỗi khi xử lý {video_info}: {e}")

    summary = f"📊 **BÁO CÁO HOÀN TẤT (Chức năng 3)**\n- ✅ Thành công: {success_count}\n- ❌ Thất bại: {fail_count}"
    await send_telegram_message(chat_id, summary)
    print("Đang upload các file Excel đã cập nhật lên Drive...")
    await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
    await upload_file_to_drive(drive_service, MP3_CONTENT_EXCEL_PATH, DRIVE_MP3_CONTENT_FILE_ID)


# --- PHẦN API VÀ WEBHOOK ---
@asynccontextmanager
async def lifespan(app: FastAPI):
    print("🚀 Bắt đầu quá trình khởi tạo bot qua lifespan...")
    log_environment_variables()
    success = await setup_bot_async()
    if not success:
        print("❌ LỖI NGHIÊM TRỌNG: Quá trình setup thất bại.")
    else:
        print("✅ Bot đã sẵn sàng nhận yêu cầu.")
    yield
    print("🔌 Bot đang tắt...")

app = FastAPI(lifespan=lifespan)

class TelegramUpdate(BaseModel):
    update_id: int
    message: dict | None = None
    callback_query: dict | None = None

REPLY_KEYBOARD_MAIN = {
    "keyboard": [
        ["🎬 Gen Video", "📊 View Kênh YTB"],
        ["📥 Download Video"] # <--- THÊM DÒNG NÀY
    ],
    "resize_keyboard": True
}



# --- [CHỈNH SỬA] Cập nhật và thêm các menu mới ---
MAIN_MENU_KEYBOARD = { "inline_keyboard": [
    [{ "text": "1. Auto Gen Video (Image)", "callback_data": "start_flow_1" }],
    [{ "text": "2. Auto Get Contens MP3", "callback_data": "start_flow_2" }],
    [{ "text": "3. Auto Gen Video (Image & MP3)", "callback_data": "start_flow_3" }]
]}


DOWNLOAD_MUTE_KEYBOARD = { "inline_keyboard": [
    [{ "text": "✅ Có, tạo file tắt tiếng", "callback_data": "dl_mute_yes" }],
    [{ "text": "❌ Không, chỉ tải file gốc", "callback_data": "dl_mute_no" }]
]}


# Bàn phím dùng chung cho chức năng 1 và 3
AUTOGEN_VIDEO_COUNT_KEYBOARD = { "inline_keyboard": [
    [{ "text": s, "callback_data": f"vid_count_{s}"} for s in ["1", "2", "3", "5", "7"]],
    [{ "text": s, "callback_data": f"vid_count_{s}"} for s in ["10", "15", "20", "25", "30"]]
]}
AUTOGEN_IMAGE_SOURCE_KEYBOARD = { "inline_keyboard": [[{ "text": "🎨 Tự động tạo ảnh mới", "callback_data": "img_src_auto" }], [{ "text": "🖼️ Dùng ảnh có sẵn", "callback_data": "img_src_common" }]] }
AUTOGEN_YT_UPLOAD_CONFIRM_KEYBOARD = { "inline_keyboard": [[{ "text": "✅ Có, tự động upload", "callback_data": "yt_upload_yes" }], [{ "text": "❌ Không", "callback_data": "yt_upload_no" }]] }
#AUTOGEN_YT_ACCOUNT_COUNT_KEYBOARD = { "inline_keyboard": [
#    [{ "text": str(i), "callback_data": f"yt_acc_{i}"} for i in range(1, 6)],
#    [{ "text": str(i), "callback_data": f"yt_acc_{i}"} for i in range(6, 11)]
#]}

# [THÊM MỚI] Bàn phím riêng cho chức năng 2
AUTOGEN_MP3_COUNT_KEYBOARD = { "inline_keyboard": [
    [{ "text": s, "callback_data": f"mp3_count_{s}"} for s in ["1", "2", "4", "6", "8"]],
    [{ "text": s, "callback_data": f"mp3_count_{s}"} for s in ["10", "15", "20", "25", "30"]]
]}


def create_yt_account_keyboard(selected_accounts: list[int], max_accounts=10) -> dict:
    """Tạo bàn phím inline với checkbox cho việc chọn tài khoản."""
    keyboard = []
    # Giả sử bạn có tối đa 10 tài khoản, chia thành 2 hàng
    all_accounts = list(range(1, max_accounts + 1))

    # Chia thành các hàng, mỗi hàng 5 tài khoản
    rows = [all_accounts[i:i + 5] for i in range(0, len(all_accounts), 5)]

    for row in rows:
        button_row = []
        for acc_num in row:
            text = f"✅ {acc_num}" if acc_num in selected_accounts else f"🔲 {acc_num}"
            callback_data = f"yt_acc_toggle_{acc_num}"
            button_row.append({"text": text, "callback_data": callback_data})
        keyboard.append(button_row)

    # Thêm hàng nút chức năng
    keyboard.append([
        {"text": "🔄 Chọn All", "callback_data": "yt_acc_select_all"},
        {"text": "▶️ Xác nhận", "callback_data": "yt_acc_confirm"}
    ])

    return {"inline_keyboard": keyboard}
@app.post("/webhook")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
    try:
        raw_body = await request.body()
        update_json = json.loads(raw_body)
        update = TelegramUpdate.parse_obj(update_json)
        if update.update_id in processed_update_ids:
            print(f"Bỏ qua update lặp lại: {update.update_id}")
            return {"status": "ok, duplicate ignored"}
        processed_update_ids.append(update.update_id)
        print(f"Đã xử lý update mới: {update.update_id}")
    except Exception as e:
        print(f"!!! ❌ ERROR PARSING REQUEST BODY: {e}")
        return {"status": "error"}

    update_data = update.dict()
    chat_id = None
    user_id = None

    if update_data.get("message"):
        message = update_data["message"]
        chat_id = message["chat"]["id"]
        user_id = message["from"]["id"]
        text = message.get("text", "")

        user_data = user_sessions.get(user_id, {})
        current_state = user_data.get('state')
        if text == "/start":
            user_sessions[user_id] = {} # Reset session
            await send_telegram_message(
                chat_id,
                "👋 Chào mừng! Vui lòng chọn một chức năng từ bàn phím bên dưới:",
                REPLY_KEYBOARD_MAIN
            )
        elif text == "🎬 Gen Video":
            await send_telegram_message(
                chat_id,
                "Vui lòng chọn một quy trình tạo video:",
                MAIN_MENU_KEYBOARD
            )
        elif text == "📊 View Kênh YTB" or text == "/viewytb":
            await send_telegram_message(chat_id, "✅ Đã nhận lệnh. Bắt đầu quét các kênh YouTube, vui lòng chờ...")
            background_tasks.add_task(get_youtube_channel_stats, chat_id)


        elif text == "📥 Download Video":
            user_sessions[user_id] = {'state': 'ASK_DOWNLOAD_LINKS'}
            await send_telegram_message(chat_id, "Vui lòng gửi 1 hoặc nhiều link video (mỗi link 1 dòng) để tải xuống:")

        # --- [LOGIC MỚI] Xử lý khi user gửi link (khi state là ASK_DOWNLOAD_LINKS) ---
        elif current_state == 'ASK_DOWNLOAD_LINKS':
            # Lọc các link hợp lệ
            links = [line.strip() for line in text.split('\n') if line.strip().startswith(('http://', 'https://'))]

            if not links:
                await send_telegram_message(chat_id, "Không tìm thấy link hợp lệ. Vui lòng thử lại. Link phải bắt đầu bằng http:// hoặc https://.")
            else:
                # Lưu link và chuyển sang state hỏi về mute
                user_data['state'] = 'ASK_DOWNLOAD_MUTE'
                user_data['download_links'] = links
                user_sessions[user_id] = user_data
                await send_telegram_message(
                    chat_id,
                    f"Đã nhận {len(links)} link. Bạn có muốn tạo thêm 1 file video đã tắt tiếng (mute) không?",
                    DOWNLOAD_MUTE_KEYBOARD # <--- Sử dụng bàn phím mới
            )



    elif update_data.get("callback_query"):
        query = update_data["callback_query"]
        chat_id = query["message"]["chat"]["id"]
        user_id = query["from"]["id"]
        data = query["data"]
        message_id = query["message"]["message_id"]

        user_data = user_sessions.get(user_id, {})
        state = user_data.get('state', 'MAIN_MENU')

        if state == 'ASK_DOWNLOAD_MUTE' and data.startswith('dl_mute_'):
            should_mute = (data == 'dl_mute_yes')
            links_to_download = user_data.get('download_links', [])

            if not links_to_download:
                await edit_telegram_message_text(chat_id, message_id, "❌ Lỗi: Không tìm thấy link. Vui lòng bắt đầu lại bằng cách nhấn 'Download Video'.")
            else:
                # Chỉnh sửa tin nhắn xác nhận
                await edit_telegram_message_text(
                    chat_id, 
                    message_id, 
                    f"✅ Đã ghi nhận. Bắt đầu tải {len(links_to_download)} video...\n(Tắt tiếng: {'Có' if should_mute else 'Không'}).\n\nBạn sẽ nhận được thông báo khi hoàn tất."
                )
                # Thêm tác vụ download vào background
                background_tasks.add_task(downloader.run_download_process, chat_id, links_to_download, should_mute)

            user_sessions[user_id] = {} # Reset session sau khi hoàn tất
            await answer_telegram_callback_query(query['id'])
            return {"status": "ok"} # Quan trọng: Dừng xử lý tại đây
        # --- Kết thúc logic mới ---

        if data.startswith("start_flow_"):
            flow_number = data.split("_")[-1]
            user_data = {'flow': int(flow_number), 'state': 'ASK_VIDEO_COUNT' if flow_number in ["1", "3"] else 'ASK_MP3_COUNT'}
            text_map = {
                "1": "1️⃣ Bạn muốn tạo bao nhiêu video?",
                "2": "2️⃣ Bạn muốn tạo bao nhiêu nội dung MP3?",
                "3": "3️⃣ Bạn muốn tạo bao nhiêu video từ MP3 có sẵn?"
            }
            keyboard_map = {
                "1": AUTOGEN_VIDEO_COUNT_KEYBOARD,
                "2": AUTOGEN_MP3_COUNT_KEYBOARD,
                "3": AUTOGEN_VIDEO_COUNT_KEYBOARD
            }
            # Thay vì gửi tin mới, chúng ta sẽ chỉnh sửa tin nhắn menu cũ
            await edit_telegram_message_text(chat_id, message_id, text_map[flow_number], keyboard_map[flow_number])

        elif user_data.get('flow') == 2:
            if state == 'ASK_MP3_COUNT' and data.startswith('mp3_count_'):
                user_data['mp3_count'] = int(data.replace("mp3_count_", ""))
                user_data['state'] = 'COMPLETED'
                await edit_telegram_message_text(chat_id, message_id, f"✅ Đã ghi nhận. Bắt đầu tạo {user_data['mp3_count']} nội dung MP3.")
                background_tasks.add_task(batch_process_autogen_mp3_content, chat_id, user_data.copy())
                user_data = {}

        elif user_data.get('flow') in [1, 3]:
            if state == 'ASK_VIDEO_COUNT' and data.startswith('vid_count_'):
                user_data['video_count'] = int(data.replace("vid_count_", ""))
                user_data['state'] = 'ASK_IMAGE_SOURCE'
                await edit_telegram_message_text(chat_id, message_id, "Chọn nguồn ảnh để tạo video:", AUTOGEN_IMAGE_SOURCE_KEYBOARD)

            elif state == 'ASK_IMAGE_SOURCE' and data.startswith('img_src_'):
                user_data['image_source'] = data.replace("img_src_", "")
                user_data['state'] = 'ASK_YT_UPLOAD'
                await edit_telegram_message_text(chat_id, message_id, "Bạn có muốn tự động upload lên YouTube không?", AUTOGEN_YT_UPLOAD_CONFIRM_KEYBOARD)

            elif state == 'ASK_YT_UPLOAD' and data.startswith('yt_upload_'):
                user_data['upload_yt'] = (data == 'yt_upload_yes')
                if user_data['upload_yt']:
                    user_data['state'] = 'ASK_YT_ACCOUNT_SELECTION'
                    user_data['selected_yt_accounts'] = []
                    keyboard = create_yt_account_keyboard(user_data['selected_yt_accounts'])
                    await edit_telegram_message_text(chat_id, message_id, "Chọn các tài khoản YouTube sẽ dùng để upload (random):", keyboard)
                else:
                    user_data['state'] = 'COMPLETED'
                    await edit_telegram_message_text(chat_id, message_id, f"✅ Đã ghi nhận. Bắt đầu tạo {user_data.get('video_count', 0)} video.")
                    if user_data.get('flow') == 1:
                        background_tasks.add_task(batch_process_autogen_videos, chat_id, user_data.copy())
                    else:
                        background_tasks.add_task(batch_process_from_premade_mp3, chat_id, user_data.copy())
                    user_data = {}

            elif state == 'ASK_YT_ACCOUNT_SELECTION':
                selected_list = user_data.get('selected_yt_accounts', [])

                if data.startswith('yt_acc_toggle_'):
                    acc_num = int(data.replace('yt_acc_toggle_', ''))
                    if acc_num in selected_list:
                        selected_list.remove(acc_num)
                    else:
                        selected_list.append(acc_num)
                    user_data['selected_yt_accounts'] = sorted(selected_list)
                    keyboard = create_yt_account_keyboard(user_data['selected_yt_accounts'])
                    await edit_telegram_reply_markup(chat_id, message_id, keyboard)

                elif data == 'yt_acc_select_all':
                    user_data['selected_yt_accounts'] = list(range(1, 11))
                    keyboard = create_yt_account_keyboard(user_data['selected_yt_accounts'])
                    await edit_telegram_reply_markup(chat_id, message_id, keyboard)

                elif data == 'yt_acc_confirm':
                    if not user_data.get('selected_yt_accounts'):
                        await answer_telegram_callback_query(query['id'], text="Lỗi: Bạn chưa chọn tài khoản YouTube nào!", show_alert=True)
                    else:
                        user_data['state'] = 'COMPLETED'
                        selected_str = ", ".join(map(str, user_data['selected_yt_accounts']))
                        await edit_telegram_message_text(chat_id, message_id, f"✅ Đã ghi nhận. Bắt đầu tạo {user_data.get('video_count', 0)} video và upload ngẫu nhiên trên các tài khoản: {selected_str}.")
                        if user_data.get('flow') == 1:
                            background_tasks.add_task(batch_process_autogen_videos, chat_id, user_data.copy())
                        else:
                            background_tasks.add_task(batch_process_from_premade_mp3, chat_id, user_data.copy())
                        user_data = {}

        user_sessions[user_id] = user_data
        # Trả lời callback query để dấu tick loading biến mất (trừ khi là alert)
        is_alert_case = state == 'ASK_YT_ACCOUNT_SELECTION' and data == 'yt_acc_confirm' and not user_data.get('selected_yt_accounts')
        if not is_alert_case:
            await answer_telegram_callback_query(query['id'])

    return {"status": "ok"}

async def upload_video_to_drive_for_post(drive_service, video_path: str) -> str | None:
    """Tải một file video cục bộ lên thư mục chỉ định trên Drive và trả về ID."""
    try:
        file_metadata = {
            'name': os.path.basename(video_path),
            'parents': [DRIVE_FACEBOOK_VIDEO_FOLDER_ID]
        }
        media = MediaFileUpload(video_path, mimetype='video/mp4', resumable=True)
        file = drive_service.files().create(body=file_metadata,
                                            media_body=media,
                                            fields='id').execute()
        print(f"✅ Video đã được upload lên Drive cho Facebook, File ID: {file.get('id')}")
        return file.get('id')
    except Exception as e:
        print(f"❌ Lỗi khi upload video lên Drive cho Facebook: {e}")
        return None

async def upload_image_to_drive_for_post(drive_service, image_path: str) -> str | None:
    """Tải một file ảnh cục bộ lên thư mục chỉ định trên Drive và trả về ID."""
    try:
        # Xác định mimetype dựa trên đuôi file để linh hoạt hơn (png, jpg, jpeg)
        file_extension = os.path.splitext(image_path)[1].lower()
        mimetype = 'image/png' if file_extension == '.png' else 'image/jpeg'

        file_metadata = {
            'name': os.path.basename(image_path),
            'parents': [DRIVE_FACEBOOK_VIDEO_FOLDER_ID] # Có thể dùng chung thư mục hoặc tạo thư mục mới
        }
        media = MediaFileUpload(image_path, mimetype=mimetype, resumable=True)
        file = drive_service.files().create(body=file_metadata,
                                            media_body=media,
                                            fields='id').execute()
        print(f"✅ Image đã được upload lên Drive cho Facebook, File ID: {file.get('id')}")
        return file.get('id')
    except Exception as e:
        print(f"❌ Lỗi khi upload image lên Drive cho Facebook: {e}")
        return None
# <-- KẾT THÚC THÊM MỚI -->



async def trigger_facebook_post(chat_id: int, post_text: str, drive_video_id: str):
    """Gửi yêu cầu đến Cloudflare Worker để trigger kịch bản Make.com."""
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ Lỗi: CLOUDFLARE_WORKER_URL chưa được thiết lập.")
        await send_telegram_message(chat_id, "Lỗi hệ thống: CLOUDFLARE_WORKER_URL chưa được cấu hình.")
        return

    payload = {
        "action": "postToFacebook",
        "facebook_post_text": post_text,
        "google_drive_mp4_id": drive_video_id
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
            response.raise_for_status()
        print("✅ Đã gửi yêu cầu đăng Facebook thành công đến Worker.")
        await send_telegram_message(chat_id, f"✅ Đã gửi yêu cầu đăng video lên Facebook Page thành công!")
    except Exception as e:
        print(f"❌ Lỗi khi trigger Facebook post qua Worker: {e}")
        await send_telegram_message(chat_id, f"❌ Lỗi khi gửi yêu cầu đăng video lên Facebook Page: {e}")

async def trigger_facebook_post2(chat_id: int, post_text: str, drive_video_id: str):
    """Gửi yêu cầu đến Cloudflare Worker để trigger kịch bản Make.com."""
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ Lỗi: CLOUDFLARE_WORKER_URL chưa được thiết lập.")
        await send_telegram_message(chat_id, "Lỗi hệ thống: CLOUDFLARE_WORKER_URL chưa được cấu hình.")
        return

    payload = {
        "action": "postToFacebook2",
        "facebook_post_text2": post_text,
        "google_drive_mp4_id2": drive_video_id
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
            response.raise_for_status()
        print("✅ Đã gửi yêu cầu đăng Facebook thành công đến Worker.")
        await send_telegram_message(chat_id, f"✅ Đã gửi yêu cầu đăng video lên Facebook Page thành công!")
    except Exception as e:
        print(f"❌ Lỗi khi trigger Facebook post qua Worker: {e}")
        await send_telegram_message(chat_id, f"❌ Lỗi khi gửi yêu cầu đăng video lên Facebook Page: {e}")

async def trigger_facebook_post3(chat_id: int, post_text: str, drive_image_id: str):
    """Gửi yêu cầu đến Cloudflare Worker để trigger kịch bản Make.com."""
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ Lỗi: CLOUDFLARE_WORKER_URL chưa được thiết lập.")
        await send_telegram_message(chat_id, "Lỗi hệ thống: CLOUDFLARE_WORKER_URL chưa được cấu hình.")
        return

    payload = {
        "action": "postToFacebook3",
        "facebook_post_text": post_text,
        "google_drive_img_id": drive_image_id
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
            response.raise_for_status()
        print("✅ Đã gửi yêu cầu đăng Facebook thành công đến Worker.")
        await send_telegram_message(chat_id, f"✅ Đã gửi yêu cầu đăng image lên Facebook Page thành công!")
    except Exception as e:
        print(f"❌ Lỗi khi trigger Facebook post qua Worker: {e}")
        await send_telegram_message(chat_id, f"❌ Lỗi khi gửi yêu cầu đăng image lên Facebook Page: {e}")


async def trigger_facebook_post4(chat_id: int, post_text: str, drive_image_id: str):
    """Gửi yêu cầu đến Cloudflare Worker để trigger kịch bản Make.com."""
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ Lỗi: CLOUDFLARE_WORKER_URL chưa được thiết lập.")
        await send_telegram_message(chat_id, "Lỗi hệ thống: CLOUDFLARE_WORKER_URL chưa được cấu hình.")
        return

    payload = {
        "action": "postToFacebook4",
        "facebook_post_text2": post_text,
        "google_drive_img_id2": drive_image_id
    }
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
            response.raise_for_status()
        print("✅ Đã gửi yêu cầu đăng Facebook thành công đến Worker.")
        await send_telegram_message(chat_id, f"✅ Đã gửi yêu cầu đăng image lên Facebook Page thành công!")
    except Exception as e:
        print(f"❌ Lỗi khi trigger Facebook post qua Worker: {e}")
        await send_telegram_message(chat_id, f"❌ Lỗi khi gửi yêu cầu đăng image lên Facebook Page: {e}")

async def get_youtube_channel_stats(chat_id: int):
    """

    Đọc danh sách kênh YouTube từ file Excel, lấy thông tin thống kê qua API

    và gửi báo cáo chi tiết về Telegram cho TỪNG kênh ngay lập tức.

    """
    print("\n--- [TRACE] Entering get_youtube_channel_stats ---")
    await send_telegram_message(chat_id, "🔎 Bắt đầu lấy thông tin các kênh YouTube. Báo cáo sẽ được gửi cho từng kênh...")

    try:
        # 1. Lấy quyền truy cập và xây dựng dịch vụ YouTube
        credentials = await get_drive_credentials(chat_id)
        if not credentials:
            raise Exception("Không thể lấy quyền truy cập Google Drive/YouTube.")
        youtube_service = build('youtube', 'v3', credentials=credentials)

        # 2. Đọc danh sách kênh từ file Excel
        df_ytb = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='YTB', header=None)
        channel_urls = df_ytb.iloc[1:, 6].dropna().astype(str).tolist()

        if not channel_urls:
            await send_telegram_message(chat_id, "⚠️ Không tìm thấy URL kênh YouTube nào trong file Input.xlsx, sheet 'YTB', cột G.")
            return

        # [THAY ĐỔI] Không còn dùng list để gộp tin nhắn nữa
        # final_report = [] 
        
        # 3. Lặp qua từng kênh để lấy thông tin và gửi ngay lập tức
        for index, url in enumerate(channel_urls):
            try:
                channel_id = url.strip().split('/')[-1]
                if not channel_id:
                    channel_id = url.strip().split('/')[-2]

                # Bắt đầu định dạng tin nhắn cho kênh hiện tại
                channel_info_str = f"📊 **Báo cáo kênh {index + 1}/{len(channel_urls)}**\n"
                channel_info_str += f"URL: {url}\n\n"
                
                # API Call 1: Lấy thông tin cơ bản của kênh
                channel_request = youtube_service.channels().list(
                    part="snippet,statistics",
                    id=channel_id
                )
                channel_response = await asyncio.to_thread(channel_request.execute)
                
                if not channel_response.get("items"):
                    channel_info_str += "<i>Không tìm thấy kênh hoặc kênh bị lỗi.</i>"
                    # [THAY ĐỔI] Gửi tin nhắn lỗi của kênh này ngay lập tức
                    await send_telegram_message(chat_id, channel_info_str)
                    continue

                channel_data = channel_response["items"][0]
                stats = channel_data["statistics"]
                snippet = channel_data["snippet"]

                channel_info_str += f"🔹 Tên kênh: {snippet['title']}\n"
                channel_info_str += f"🔹 Tổng số video: {int(stats.get('videoCount', 0)):,}\n"
                channel_info_str += f"🔹 Tổng số view: {int(stats.get('viewCount', 0)):,}\n"
                channel_info_str += f"🔹 Tổng số sub: {int(stats.get('subscriberCount', 0)):,}\n"
                
                # API Call 2: Tìm 5 video mới nhất
                search_request = youtube_service.search().list(
                    part="id", channelId=channel_id, maxResults=5, order="date", type="video"
                )
                search_response = await asyncio.to_thread(search_request.execute)
                video_ids = [item['id']['videoId'] for item in search_response.get('items', [])]

                if not video_ids:
                    channel_info_str += "\n<i>Kênh chưa có video nào.</i>"
                else:
                    # API Call 3: Lấy chi tiết của 5 video
                    video_request = youtube_service.videos().list(
                        part="snippet,statistics", id=",".join(video_ids)
                    )
                    video_response = await asyncio.to_thread(video_request.execute)
                    
                    channel_info_str += "🔹 5 video gần nhất:\n"
                    for video in video_response.get("items", []):
                        vid_snippet = video['snippet']
                        vid_stats = video['statistics']
                        upload_date = datetime.datetime.fromisoformat(vid_snippet['publishedAt'].replace('Z', '+00:00')).strftime('%d/%m/%Y')
                        
                        channel_info_str += f"  - {vid_snippet['title']}\n"
                        channel_info_str += f"      +  Ngày upload: {upload_date}\n"
                        channel_info_str += f"      +  View: {int(vid_stats.get('viewCount', 0)):,}\n"
                        channel_info_str += f"      +  Like: {int(vid_stats.get('likeCount', 0)):,}\n"
                
                # [THAY ĐỔI] Gửi báo cáo cho kênh này ngay sau khi xử lý xong
                await send_telegram_message(chat_id, channel_info_str)
                await asyncio.sleep(1) # Thêm 1 giây nghỉ để tránh spam Telegram

            except Exception as e:
                error_message = f"📊 **Kênh {index + 1}/{len(channel_urls)}: {url}**\n<i>❌ Lỗi khi xử lý: {e}</i>"
                # [THAY ĐỔI] Gửi tin nhắn lỗi của kênh này ngay lập tức
                await send_telegram_message(chat_id, error_message)
        
        # [THAY ĐỔI] Gửi tin nhắn tổng kết sau khi vòng lặp kết thúc
        await send_telegram_message(chat_id, f"✅ Hoàn tất!\nĐã quét và gửi báo cáo cho tổng cộng {len(channel_urls)} kênh.")

    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi nghiêm trọng khi thực thi chức năng 'View All Channel YTB': {e}")
    finally:
        print("--- [TRACE] Exiting get_youtube_channel_stats ---")
        
@app.get("/")
def read_root():
    return {"message": "Bot is running."}