File size: 139,136 Bytes
1453635
 
 
 
 
 
 
 
 
 
0af0b1f
1453635
 
 
 
 
 
 
 
 
 
0af0b1f
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
 
 
 
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
 
1453635
 
 
af670d9
 
 
1453635
af670d9
 
 
 
 
 
 
 
1453635
 
af670d9
1453635
af670d9
 
 
1453635
4c20803
 
 
 
 
 
 
 
73b9e74
 
 
af670d9
 
 
 
 
73b9e74
1453635
 
af670d9
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39351bd
 
 
 
 
1453635
39351bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac9c53f
1453635
ac9c53f
 
1453635
 
ac9c53f
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac9c53f
 
1453635
ac9c53f
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac9c53f
 
1453635
 
 
 
 
 
 
ac9c53f
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac9c53f
1453635
 
 
 
 
 
 
 
ac9c53f
1453635
 
 
 
 
 
 
 
 
 
 
ac9c53f
1453635
0af0b1f
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
1453635
0af0b1f
 
 
 
 
 
 
 
 
 
1453635
 
 
 
 
 
0af0b1f
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720aa6d
636ca48
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
 
 
 
636ca48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1a9661
1453635
 
83a4de2
720aa6d
769db65
720aa6d
83a4de2
720aa6d
 
 
 
83a4de2
720aa6d
636ca48
720aa6d
 
cdbdee8
636ca48
769db65
 
83a4de2
 
 
769db65
cdbdee8
 
83a4de2
cdbdee8
83a4de2
 
 
 
 
 
 
720aa6d
83a4de2
720aa6d
83a4de2
720aa6d
 
b1a9661
636ca48
769db65
720aa6d
 
636ca48
 
720aa6d
cdbdee8
83a4de2
cdbdee8
83a4de2
 
cdbdee8
636ca48
83a4de2
cdbdee8
636ca48
 
83a4de2
cdbdee8
636ca48
 
 
 
 
 
 
 
 
 
720aa6d
 
 
 
83a4de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720aa6d
83a4de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720aa6d
 
 
 
cdbdee8
720aa6d
 
769db65
83a4de2
 
 
 
720aa6d
 
 
3b2e481
 
 
 
1453635
3b2e481
1453635
 
3b2e481
1453635
 
 
3b2e481
1453635
 
 
 
 
 
 
3b2e481
1453635
3b2e481
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
3b2e481
 
 
 
1453635
3b2e481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
3b2e481
 
 
 
 
 
 
 
 
ac9c53f
1453635
3b2e481
1453635
3b2e481
1453635
3b2e481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
 
3b2e481
1453635
3b2e481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
 
3b2e481
1453635
 
 
3b2e481
1453635
 
3b2e481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1453635
3b2e481
 
 
 
 
 
1453635
 
3b2e481
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
0af0b1f
 
 
 
 
 
1453635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af670d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
import nest_asyncio
nest_asyncio.apply()

import asyncio
import base64
import os
import re
import shutil
import subprocess
import pickle
import random
import traceback
import time
import tempfile
import json
import io
from collections import deque
import httpx
import socket
import aiodns
import edge_tts
from gradio_client import Client  # Import cho TTS HuggingFace (giọng Ngọc Huyền)

import pandas as pd
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook

# --- CÁC THƯ VIỆN FRAMEWORK ---
from fastapi import FastAPI, Request, BackgroundTasks
from contextlib import asynccontextmanager
from scrapers import get_scraper # <<< DÒNG MỚI

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


# --- BỘ ĐỆM CHỐNG LẶP REQUEST TỪ TELEGRAM ---
processed_update_ids = deque(maxlen=500)
# --- DICTIONARY LƯU TRẠNG THÁI NGƯỜI DÙNG ---
user_sessions = {}
from trace_handler import process_content_for_trace # <<< DÒNG MỚI: Import hàm logic từ file mới

# ==============================================================================
# --- PHẦN CẤU HÌNH CẦN THAY ĐỔI CHO MÔI TRƯỜNG HUGGING FACE ---
# ==============================================================================

# --- ĐƯỜNG DẪN TRÊN HỆ THỐNG TỆP TẠM THỜI CỦA HUGGING FACE ---
# Chúng ta sẽ sử dụng thư mục /tmp/ để lưu trữ file tạm thời.
BASE_DATA_DIR = "/tmp/audio_bot_data"
WORKING_EXCEL_PATH = os.path.join(BASE_DATA_DIR, "Input.xlsx")
AUDIO_TXT_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Input/")
AUDIO_MP3_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Sound/")
AUDIO_FINAL_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Final/")
AUDIO_VIDEO_FOLDER = os.path.join(BASE_DATA_DIR, "Audio/Video/")
YTB_TOKEN_SAVE_PATH = os.path.join(BASE_DATA_DIR, "YTB/Account/") # Thư mục chứa token sau khi tải từ Drive
TEMP_PATH = os.path.join(BASE_DATA_DIR, "Temp/")

# --- ID CỦA CÁC FILE VÀ THƯ MỤC TRÊN GOOGLE DRIVE ---
# ID file Excel chính
DRIVE_EXCEL_FILE_ID = "16a00UFwedILbo_ujvProGmgRlJZw6qDp"

# !!! QUAN TRỌNG: Bạn cần tạo các thư mục sau trên Google Drive và dán ID của chúng vào đây
DRIVE_YTB_ACCOUNT_FOLDER_ID = "1_Drudczqoaq03L5dbkVJoA1FWgJ6R2MO" # Thư mục chứa các file token .pickle của YouTube
DRIVE_AUDIO_VIDEO_FOLDER_ID = "1uIbjogmCT-xySHleVPR3senWD7IMUE71" # <-- THAY ID NÀY: Thư mục để lưu video .mp4 cuối cùng
# --- THÊM CÁC ID MỚI CHO CÁC THƯ MỤC TRUNG GIAN ---
DRIVE_AUDIO_TXT_FOLDER_ID = "1Sg9_1XcABwTtIflqBPpGjsk5Epkz-QFe"        # <-- THAY ID NÀY
DRIVE_AUDIO_MP3_FOLDER_ID = "1_eE1ZRjKPZChzlDjcUKsg0s5Rnkt6B4Y" # <-- THAY ID NÀY
DRIVE_AUDIO_FINAL_FOLDER_ID = "16L1UKQuWRGdpq5sIZ5q0rea7Q5_GidPF"   # <-- THAY ID NÀY


# --- LẤY BIẾN MÔI TRƯỜNG TỪ HUGGING FACE SECRETS ---
GOOGLE_APP_SCRIPT_URL = os.getenv("GOOGLE_APP_SCRIPT_URL") # URL của Google Apps Script Web App
GOOGLE_APP_SCRIPT_KEY = os.getenv("GOOGLE_APP_SCRIPT_KEY") # Khóa dùng chung với Google Apps Script

# Biến toàn cục cho Google TTS API Key, sẽ được đọc từ Excel khi khởi động
GOOGLE_TTS_API_KEY = ""

# ==============================================================================
# --- ĐỊNH NGHĨA CÁC TRẠNG THÁI & KEYBOARD (ĐÃ CHUYỂN SANG ĐỊNH DẠNG JSON) ---
# ==============================================================================
# Logic trạng thái được giữ nguyên
AUDIO_MENU_STATE = 100
AWAITING_EPISODE_COUNT_STATE = 101
AWAITING_URL_FOR_SCRAPING_STATE = 102
AWAITING_ADD_MORE_URL_CONFIRMATION_STATE = 103
AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE = 104
AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE = 105
AWAITING_PAGE_COUNT_STATE = 106
AWAITING_ONE_CLICK_YT_CONFIRM_STATE = 107
AWAITING_ONE_CLICK_YT_ACCOUNT_STATE = 108
# <<< MỚI: Thêm các trạng thái chọn giọng đọc
AWAITING_GEN_MP3_VOICE_CHOICE_STATE = 109
AWAITING_ONE_CLICK_VOICE_CHOICE_STATE = 110
AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE = 111 
# <<< BLOCK CODE MỚI BẮT ĐẦU: Thêm các trạng thái cho chức năng Truy Vết
AWAITING_TRACE_PAGE_COUNT_STATE = 201
AWAITING_TRACE_URL_STATE = 202
# <<< BLOCK CODE MỚI KẾT THÚC

# Bàn phím được chuyển thành JSON để gửi qua Google Apps Script
AUDIO_MENU_KEYBOARD = { "inline_keyboard": [
    [{"text": "1. Get Link", "callback_data": "audio_get_link"}, {"text": "2. Get File", "callback_data": "audio_get_file"}],
    [{"text": "3. Gen MP3", "callback_data": "audio_gen_mp3"}, {"text": "4. Gen MP4", "callback_data": "audio_gen_mp4"}],
    [{"text": "5. Merge File", "callback_data": "audio_merge_file"}, {"text": "6. One Click", "callback_data": "audio_one_click"}],
    [{"text": "🔎 Truy Vết", "callback_data": "audio_trace"}], # <<< DÒNG MỚI
    [{"text": "🚀 Upload Youtube (Recover)", "callback_data": "audio_recovery_upload"}], # <<< DÒNG MỚI
    [{"text": "⬅️ Quay lại Menu chính", "callback_data": "back_to_main_menu"}],
]}

RECOVERY_YT_ACCOUNT_KEYBOARD = { "inline_keyboard": [
    [{"text": f"{i}", "callback_data": f"recovery_yt_acc_{i}"} for i in range(1, 6)],
    [{"text": f"{i}", "callback_data": f"recovery_yt_acc_{i}"} for i in range(6, 11)],
]}

VOICE_CHOICE_KEYBOARD_GEN_MP3 = { "inline_keyboard": [
    [{"text": "👨 Giọng Nam (Edge TTS)", "callback_data": "gen_mp3_voice_male"},
     {"text": "👩 Giọng Nữ (Google TTS)", "callback_data": "gen_mp3_voice_female"}],
    [{"text": "🌸 Ngọc Huyền (HuggingFace)", "callback_data": "gen_mp3_voice_ngochuyen"}]
]}
VOICE_CHOICE_KEYBOARD_ONE_CLICK = { "inline_keyboard": [
    [{"text": "👨 Giọng Nam", "callback_data": "one_click_voice_male"},
     {"text": "👩 Giọng Nữ", "callback_data": "one_click_voice_female"}],
    [{"text": "🌸 Ngọc Huyền", "callback_data": "one_click_voice_ngochuyen"}]
]}



YOUTUBE_UPLOAD_CONFIRM_KEYBOARD = { "inline_keyboard": [[{"text": "✅ Có, upload ngay", "callback_data": "yt_upload_yes"}, {"text": "❌ Không, cảm ơn", "callback_data": "yt_upload_no"}]]}
YOUTUBE_ACCOUNT_KEYBOARD_AUDIO = { "inline_keyboard": [
    [{"text": f"{i}", "callback_data": f"yt_account_{i}"} for i in range(1, 6)],
    [{"text": f"{i}", "callback_data": f"yt_account_{i}"} for i in range(6, 11)],
]}
EPISODE_COUNT_KEYBOARD = { "inline_keyboard": [
    [{"text": "1", "callback_data": "ep_count_1"}, {"text": "2", "callback_data": "ep_count_2"}, {"text": "5", "callback_data": "ep_count_5"}],
    [{"text": "10", "callback_data": "ep_count_10"}, {"text": "15", "callback_data": "ep_count_15"}, {"text": "20", "callback_data": "ep_count_20"}],
]}
ADD_MORE_KEYBOARD = {"inline_keyboard": [[{"text": "✅ Có", "callback_data": "add_more_yes"}, {"text": "❌ Không", "callback_data": "add_more_no"}]]}
PAGE_COUNT_KEYBOARD = { "inline_keyboard": [
    [{"text": "1 Trang", "callback_data": "page_count_1"}, {"text": "2 Trang", "callback_data": "page_count_2"}, {"text": "4 Trang", "callback_data": "page_count_4"}],
    [{"text": "6 Trang", "callback_data": "page_count_6"}, {"text": "10 Trang", "callback_data": "page_count_10"}, {"text": "20 Trang", "callback_data": "page_count_20"}],
]}
ONE_CLICK_YT_CONFIRM_KEYBOARD = { "inline_keyboard": [[{"text": "✅ Có, tự động upload", "callback_data": "one_click_yt_yes"}, {"text": "❌ Không, chỉ tạo video", "callback_data": "one_click_yt_no"}]]}
ONE_CLICK_YT_ACCOUNT_KEYBOARD = { "inline_keyboard": [
    [{"text": f"{i}", "callback_data": f"one_click_account_{i}"} for i in range(71, 76)],
    [{"text": f"{i}", "callback_data": f"one_click_account_{i}"} for i in range(76, 81)],
]}

# <<< BLOCK CODE MỚI BẮT ĐẦU: Bàn phím chọn số trang cho chức năng Truy Vết
TRACE_PAGE_COUNT_KEYBOARD = { "inline_keyboard": [
    [{"text": "1 Trang", "callback_data": "trace_page_count_1"}, {"text": "2 Trang", "callback_data": "trace_page_count_2"}, {"text": "4 Trang", "callback_data": "trace_page_count_4"}],
    [{"text": "6 Trang", "callback_data": "trace_page_count_6"}, {"text": "10 Trang", "callback_data": "trace_page_count_10"}, {"text": "20 Trang", "callback_data": "trace_page_count_20"}],
]}


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
# --- KẾT THÚC PHẦN DNS FIX ---



# ==============================================================================
# --- CÁC HÀM GIAO TIẾP VÀ TƯƠNG TÁC VỚI HẠ TẦNG (GOOGLE APPS SCRIPT, DRIVE) ---
# ==============================================================================
async def _append_trace_results_to_excel(results: list[dict]) -> bool:
    """Hàm mới để ghi kết quả truy vết vào các cột R, S của sheet 'Audio'."""
    def append_data(book):
        if "Audio" not in book.sheetnames:
            ws = book.create_sheet("Audio")
        else:
            ws = book["Audio"]
        
        # --- LOGIC ĐÃ SỬA LỖI ---
        # Kiểm tra xem header đã tồn tại ở dòng 1 chưa
        header_exists = ws.cell(row=1, column=18).value == "Full Sentence"

        if not header_exists:
            # Nếu chưa có header, ghi vào dòng 1
            ws.cell(row=1, column=18, value="Full Sentence") # Cột R
            ws.cell(row=1, column=19, value="Masked Words")  # Cột S
            # Dữ liệu sẽ bắt đầu từ dòng 2
            start_row = 2
        else:
            # Nếu đã có header, tìm dòng trống tiếp theo
            start_row = ws.max_row + 1

        # Ghi dữ liệu kết quả vào các dòng tiếp theo
        for i, item in enumerate(results):
            current_row = start_row + i
            ws.cell(row=current_row, column=18, value=item.get("sentence"))
            ws.cell(row=current_row, column=19, value=item.get("masked_words"))
            
        print(f"✅ Đã chuẩn bị ghi {len(results)} kết quả truy vết vào Excel.")

    return await modify_excel_sheet(append_data)

async def run_trace_workflow(chat_id: int, start_url: str, max_pages: int):
    """

    Tác vụ nền cho chức năng 'Truy Vết'.

    Hàm này điều phối toàn bộ quy trình: cào link, cào nội dung, xử lý và lưu Excel.

    *** PHIÊN BẢN SỬA LỖI: Chỉ ghi vào Excel những dòng còn lỗi SAU KHI thay thế. ***

    """
    await send_telegram_message(chat_id, f"🔎 Bắt đầu quy trình Truy Vết cho {max_pages} trang từ URL của bạn...")

    # 1. Đọc bản đồ thay thế từ Excel (cột O và P)
    replacement_map = await _read_replacement_map_from_excel()
    
    # 2. Lấy danh sách các chương cần quét
    chapter_list_result = await scrape_website_chapter_list(start_url, max_pages)
    if 'error' in chapter_list_result:
        await send_telegram_message(chat_id, f"❌ Lỗi khi lấy danh sách chương: {chapter_list_result['error']}", reply_markup=AUDIO_MENU_KEYBOARD)
        return
    chapter_links_data = chapter_list_result.get('data', [])
    if not chapter_links_data:
        await send_telegram_message(chat_id, "Không tìm thấy chương nào từ URL đã cho.", reply_markup=AUDIO_MENU_KEYBOARD)
        return
    await send_telegram_message(chat_id, f"✅ Tìm thấy {len(chapter_links_data)} chương. Bắt đầu quét nội dung, áp dụng thay thế và lọc kết quả...")

    # 3. Quét, thay thế và lọc kết quả
    final_results_to_report = []
    config = await read_audio_config_from_excel()
    
    for i, chapter_data in enumerate(chapter_links_data):
        if (i + 1) % 20 == 0: # Gửi thông báo tiến độ sau mỗi 20 chương
            await send_telegram_message(chat_id, f"⏳ Đang xử lý chương {i + 1}/{len(chapter_links_data)}...")

        scrape_result = await scrape_website_chapter_content(chapter_data['link'], config["replacements"])
        
        if scrape_result:
            _, content, _ = scrape_result
            # Lấy kết quả truy vết ban đầu
            initial_trace_results = process_content_for_trace(content)
            
            # Chỉ xử lý nếu có lỗi ban đầu
            if initial_trace_results:
                for result in initial_trace_results:
                    # Áp dụng thay thế cho câu bị lỗi
                    cleaned_sentence = _apply_replacements(result['sentence'], replacement_map)
                    
                    # KIỂM TRA LẠI: Chạy lại truy vết trên câu ĐÃ ĐƯỢC LÀM SẠCH
                    re_traced_errors = process_content_for_trace(cleaned_sentence)
                    
                    # CHỈ THÊM VÀO BÁO CÁO NẾU VẪN CÒN LỖI SAU KHI THAY THẾ
                    if re_traced_errors:
                        # Lấy từ khóa lỗi còn lại để báo cáo cho chính xác
                        remaining_keywords = re_traced_errors[0]['masked_words']
                        final_results_to_report.append({
                            "sentence": cleaned_sentence,
                            "masked_words": remaining_keywords
                        })

    # 4. Báo cáo kết quả cuối cùng
    if not final_results_to_report:
        await send_telegram_message(chat_id, "✅ **TRUY VẾT THÀNH CÔNG** 🎉\nSau khi áp dụng các quy tắc thay thế, không còn tìm thấy nội dung nào cần xử lý.", reply_markup=AUDIO_MENU_KEYBOARD)
        return

    # Chỉ ghi những kết quả thực sự còn lỗi vào Excel
    await send_telegram_message(chat_id, f"⚠️ Tìm thấy {len(final_results_to_report)} câu vẫn còn lỗi sau khi thay thế. Đang ghi vào file Excel để bạn xem lại...")
    
    if await _append_trace_results_to_excel(final_results_to_report):
        drive_creds = await get_drive_credentials(chat_id)
        if drive_creds:
            drive_service = build('drive', 'v3', credentials=drive_creds)
            await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
            await send_telegram_message(chat_id, "🎉 **TRUY VẾT HOÀN TẤT** 🎉\nĐã cập nhật các lỗi còn lại vào file Input.xlsx và upload lên Google Drive.", reply_markup=AUDIO_MENU_KEYBOARD)
        else:
            await send_telegram_message(chat_id, "⚠️ Ghi vào Excel cục bộ thành công, nhưng không thể upload lên Drive (lỗi xác thực).", reply_markup=AUDIO_MENU_KEYBOARD)
    else:
        await send_telegram_message(chat_id, "❌ Lỗi khi ghi kết quả vào file Excel.", reply_markup=AUDIO_MENU_KEYBOARD)



async def _read_replacement_map_from_excel() -> dict:
    """

    Đọc bản đồ thay thế tùy chỉnh từ cột O (tìm) và P (thay thế) của sheet 'Audio'.

    *** PHIÊN BẢN SỬA LỖI: Chấp nhận ô P trống để thay thế bằng blank. ***

    """
    replacements = {}
    try:
        df = pd.read_excel(
            WORKING_EXCEL_PATH,
            sheet_name="Audio",
            header=None,
            usecols=[14, 15], # Cột O và P
            engine="openpyxl"
        )
        
        # BƯỚC 1: Chỉ xóa những dòng mà cột O (index 14) bị trống.
        # Các dòng có cột P trống nhưng cột O có dữ liệu sẽ được giữ lại.
        df.dropna(subset=[14], inplace=True)
        
        # BƯỚC 2: Với những dòng đã được giữ lại, hãy điền vào các ô trống (NaN)
        # ở cột P (index 15) bằng một chuỗi rỗng "" (blank).
        df[15] = df[15].fillna('')

        # Bây giờ, vòng lặp sẽ hoạt động chính xác
        for index, row in df.iterrows():
            find_str = str(row[14])
            replace_str = str(row[15])
            # if find_str: # Điều kiện này không còn quá cần thiết nhưng giữ lại cho an toàn
            replacements[find_str] = replace_str

        print(f"✅ Đã đọc {len(replacements)} quy tắc thay thế từ cột O và P (bao gồm cả thay thế bằng blank).")
    except Exception as e:
        print(f"⚠️ Lỗi khi đọc bản đồ thay thế từ Excel: {e}")
    return replacements

def _apply_replacements(text: str, replacement_map: dict) -> str:
    """

    Áp dụng một loạt các thao tác tìm và thay thế cho một chuỗi văn bản.

    """
    for find_str, replace_str in replacement_map.items():
        text = text.replace(find_str, replace_str)
    return text
# <<< BLOCK CODE MỚI KẾT THÚC >>>


async def send_telegram_message(chat_id, text, reply_markup=None, parse_mode=None):
    """Gửi tin nhắn văn bản qua Google Apps Script tới Telegram."""
    if not GOOGLE_APP_SCRIPT_URL:
        print("❌ LỖI NGHIÊM TRỌNG: GOOGLE_APP_SCRIPT_URL chưa được thiết lập.")
        return False
    if not GOOGLE_APP_SCRIPT_KEY:
        print("❌ LỖI NGHIÊM TRỌNG: GOOGLE_APP_SCRIPT_KEY chưa được thiết lập.")
        return False
    print(f"--> Đang gửi tin nhắn tới chat_id: {chat_id}")
    payload = {
        "action": "sendMessage",
        "proxy_key": GOOGLE_APP_SCRIPT_KEY,
        "chat_id": chat_id,
        "text": text,
    }
    if parse_mode:
        payload["parse_mode"] = parse_mode
    if reply_markup:
        payload["reply_markup"] = json.dumps(reply_markup) # Đảm bảo reply_markup là chuỗi JSON
    response = None
    try:
        # GAS ContentService có thể trả redirect; theo redirect để log được phản hồi cuối.
        async with httpx.AsyncClient(follow_redirects=True) as client:
            response = await client.post(GOOGLE_APP_SCRIPT_URL, json=payload, timeout=30.0)
            response.raise_for_status()
        try:
            result = response.json()
        except ValueError as json_error:
            final_url = f"{response.url.scheme}://{response.url.host}{response.url.path}"
            content_type = response.headers.get("content-type", "unknown")
            raise RuntimeError(
                f"GAS không trả JSON (Content-Type={content_type}, URL cuối={final_url})"
            ) from json_error
        if not isinstance(result, dict) or not (
            result.get("ok") is True or result.get("success") is True
        ):
            if isinstance(result, dict):
                details = result.get("description") or result.get("error") or result
            else:
                details = response.text[:500]
            raise RuntimeError(f"Google Apps Script/Telegram trả lỗi: {details}")
        print(f"--> GAS xác nhận gửi thành công tới chat_id {chat_id}")
        return True
    except Exception as e:
        status = f", HTTP {response.status_code}" if response is not None else ""
        body = f", body={response.text[:500]!r}" if response is not None else ""
        print(f"❌ Lỗi khi gọi Google Apps Script gửi tin nhắn ({type(e).__name__}{status}): {e!r}{body}")
        return False

async def scrape_website_chapter_list(url: str, max_pages: int) -> dict:
    """

    Hàm chung để cào danh sách chương. Tự động chọn scraper phù hợp.

    """
    scraper = get_scraper(url)
    if not scraper:
        return {"error": "URL không được hỗ trợ", "details": f"Không tìm thấy scraper cho trang: {url}"}

    # Tất cả các scraper bây giờ đều là hàm đồng bộ (blocking)
    return await asyncio.to_thread(scraper.scrape_chapter_list, url, max_pages)


async def scrape_website_chapter_content(url: str, replacements: list[str]) -> tuple[str, str, str] | None:
    """

    Hàm chung để cào nội dung chương. Tự động chọn scraper phù hợp.

    """
    scraper = get_scraper(url)
    if not scraper:
        print(f"URL không được hỗ trợ: {url}")
        return None

    # Tất cả các scraper bây giờ đều là hàm đồng bộ (blocking)
    return await asyncio.to_thread(scraper.scrape_chapter_content, url, replacements)


async def get_drive_credentials(chat_id: int) -> Credentials | None:
    """Xác thực và trả về credentials cho Google Drive."""
    # Trong môi trường HF, token được đọc từ secret và ghi vào file tạm
    working_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, "driver_main.pickle")
    if not os.path.exists(working_token_path):
        await send_telegram_message(chat_id, "❌ Lỗi: 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)

    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 làm mới token Drive: {e}")
                return None
        else:
            return None
    return credentials

async def download_file_from_drive(drive_service, file_id: str, save_path: str):
    """Tải một file từ Google Drive về đường dẫn cục bộ."""
    try:
        print(f"[*] Đang tải file Drive ID '{file_id}' về '{save_path}'...")
        os.makedirs(os.path.dirname(save_path), exist_ok=True)
        request = drive_service.files().get_media(fileId=file_id)
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while not done:
            status, done = await asyncio.to_thread(downloader.next_chunk)
            if status:
                print(f"   -> Đã tải {int(status.progress() * 100)}%.")
        with open(save_path, 'wb') as f:
            f.write(fh.getvalue())
        print(f"✅ Tải file thành công.")
        return True
    except Exception as e:
        print(f"❌ Lỗi khi tải file từ Drive: {e}")
        return False

async def upload_file_to_drive(drive_service, local_path: str, file_id_to_update: str):
    """Cập nhật một file đã có trên Drive bằng file cục bộ."""
    try:
        print(f"[*] Đang upload file '{local_path}' để cập nhật Drive ID '{file_id_to_update}'...")
        media = MediaFileUpload(local_path)
        await asyncio.to_thread(
            drive_service.files().update(fileId=file_id_to_update, media_body=media).execute
        )
        print(f"✅ Upload file Excel thành công.")
        return True
    except Exception as e:
        print(f"❌ Lỗi khi upload file Excel lên Drive: {e}")
        return False

async def upload_video_to_drive_audio(drive_service, local_video_path: str, chat_id: int):
    """

    (CHỨC NĂNG MỚI) Upload video đã tạo lên thư mục Video trên Drive.

    """
    try:
        if "DRIVE_FOLDER_ID_FOR_FINAL_VIDEOS" in DRIVE_AUDIO_VIDEO_FOLDER_ID:
             await send_telegram_message(chat_id, "⚠️ CẢNH BÁO: DRIVE_AUDIO_VIDEO_FOLDER_ID chưa được cấu hình. Bỏ qua upload video lên Drive.")
             return None

        file_metadata = {
            'name': os.path.basename(local_video_path),
            'parents': [DRIVE_AUDIO_VIDEO_FOLDER_ID]
        }
        media = MediaFileUpload(local_video_path, mimetype='video/mp4', resumable=True)
        
        print(f"[*] Bắt đầu upload video '{os.path.basename(local_video_path)}' lên Google Drive...")
        
        request = drive_service.files().create(body=file_metadata, media_body=media, fields='id')
        
        response = None
        while response is None:
            status, response = await asyncio.to_thread(request.next_chunk)
            if status:
                progress = int(status.progress() * 100)
                # Chỉ gửi thông báo tiến độ cho các mốc quan trọng để tránh spam
                if progress % 25 == 0 and progress > 0:
                     await send_telegram_message(chat_id, f"⏳ Đang upload video lên Drive... {progress}%")

        file_id = response.get('id')
        print(f"✅ Upload video lên Drive thành công! File ID: {file_id}")
        await send_telegram_message(chat_id, f"✅ Đã upload video lên Google Drive thành công.")
        return file_id
    except Exception as e:
        print(f"❌ Lỗi khi upload video lên Drive: {e}")
        await send_telegram_message(chat_id, f"❌ Lỗi khi upload video lên Google Drive: {e}")
        return None

async def list_files_in_drive_folder(drive_service, folder_id: str) -> list:
    """

    Liệt kê TẤT CẢ các file trong một thư mục trên Drive, xử lý giới hạn 100 file/trang.

    """
    all_files = []
    page_token = None
    try:
        while True:
            query = f"'{folder_id}' in parents and trashed=false"
            # Thêm pageSize=1000 để tối ưu, và pageToken để lấy trang tiếp theo
            response = await asyncio.to_thread(
                drive_service.files().list(
                    q=query,
                    spaces='drive',
                    fields='nextPageToken, files(id, name)', # Lấy thêm nextPageToken
                    pageSize=1000, # Yêu cầu tối đa 1000 file mỗi lần
                    pageToken=page_token
                ).execute
            )
            
            # Thêm các file từ trang hiện tại vào danh sách tổng
            all_files.extend(response.get('files', []))
            
            # Lấy token của trang tiếp theo
            page_token = response.get('nextPageToken', None)
            
            # Nếu không còn trang tiếp theo, thoát khỏi vòng lặp
            if page_token is None:
                break
                
        print(f"✅ Đã lấy thành công {len(all_files)} file từ thư mục ID: {folder_id}")
        return all_files
        
    except Exception as e:
        print(f"❌ Lỗi khi liệt kê file trong thư mục Drive '{folder_id}': {e}")
        return []
async def upload_file_to_drive_folder(drive_service, local_file_path: str, drive_folder_id: str) -> str | None:
    """Upload một file cục bộ lên một thư mục cụ thể trên Drive."""
    try:
        file_metadata = {
            'name': os.path.basename(local_file_path),
            'parents': [drive_folder_id]
        }
        media = MediaFileUpload(local_file_path, resumable=True)
        
        request = drive_service.files().create(body=file_metadata, media_body=media, fields='id')
        
        response = None
        while response is None:
            status, response = await asyncio.to_thread(request.next_chunk)
            if status:
                print(f"   -> Đang upload '{os.path.basename(local_file_path)}' lên Drive... {int(status.progress() * 100)}%")
        
        file_id = response.get('id')
        print(f"✅ Upload file lên Drive thành công! File ID: {file_id}")
        return file_id
    except Exception as e:
        print(f"❌ Lỗi khi upload file '{os.path.basename(local_file_path)}' lên Drive: {e}")
        return None

async def delete_files_in_drive_folder(drive_service, folder_id: str, chat_id: int):
    """Xóa tất cả các file trong một thư mục trên Drive."""
    await send_telegram_message(chat_id, f"🗑️ Bắt đầu dọn dẹp thư mục trung gian trên Drive...")
    files_to_delete = await list_files_in_drive_folder(drive_service, folder_id)
    if not files_to_delete:
        print(f"✅ Không có file nào để dọn dẹp trong thư mục ID: {folder_id}")
        return
        
    for file in files_to_delete:
        try:
            await asyncio.to_thread(drive_service.files().delete(fileId=file.get('id')).execute)
            print(f"   -> Đã xóa file: {file.get('name')}")
        except Exception as e:
            print(f"❌ Lỗi khi xóa file '{file.get('name')}': {e}")
    await send_telegram_message(chat_id, f"✅ Đã dọn dẹp xong các file trung gian.")





# ==============================================================================
# --- CÁC HÀM XỬ LÝ LÕI (CORE FUNCTIONS) - SAO CHÉP TỪ FILE GỐC VÀ TINH CHỈNH ---
# ==============================================================================
# Ghi chú: Logic bên trong các hàm này gần như được giữ nguyên.
# Chỉ thay đổi nhỏ liên quan đến đường dẫn file và cách đọc cấu hình.


def split_text_into_chunks(text: str, max_bytes: int = 4500) -> list[str]:
    """Tách văn bản thành các đoạn nhỏ hơn để phù hợp với API TTS."""
    # --- LOGIC CŨ GIỮ NGUYÊN ---
    sentences = re.split(r"(?<=\.)\s*", text)
    chunks = []
    current_chunk = ""
    for sentence in sentences:
        if not sentence.strip():
            continue
        separator = " " if current_chunk else ""
        if len((current_chunk + separator + sentence).encode("utf-8")) > max_bytes:
            if current_chunk:
                chunks.append(current_chunk)
            current_chunk = sentence
        else:
            current_chunk += separator + sentence
    if current_chunk:
        chunks.append(current_chunk.strip())
    return chunks

async def merge_mp3_files_ffmpeg(segment_paths: list[str], final_output_path: str) -> bool:
    """Nối nhiều file MP3 thành một bằng ffmpeg."""
    # --- LOGIC CŨ GIỮ NGUYÊN ---
    # Đảm bảo thư mục đích tồn tại
    os.makedirs(os.path.dirname(final_output_path), exist_ok=True)
    list_file_path = os.path.join(TEMP_PATH, f"{os.path.basename(final_output_path)}.list.txt")
    with open(list_file_path, "w", encoding="utf-8") as f:
        for path in segment_paths:
            f.write(f"file '{os.path.abspath(path)}'\n")
    ffmpeg_cmd = ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", final_output_path]
    try:
        process = await asyncio.create_subprocess_exec(*ffmpeg_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0:
            print(f"Lỗi FFmpeg khi nối file: {stderr.decode()}"); return False
        return True
    except FileNotFoundError:
        print("Lỗi: Lệnh 'ffmpeg' không được tìm thấy."); return False
    finally:
        if os.path.exists(list_file_path):
            os.remove(list_file_path)

async def convert_text_to_mp3_edge(text: str, output_path: str) -> bool:
    """Chuyển văn bản thành file mp3 bằng Microsoft Edge TTS."""
    try:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        communicate = edge_tts.Communicate(text, voice="vi-VN-NamMinhNeural", rate="+10%")
        await communicate.save(output_path)
        return True
    except Exception as e:
        print(f"Lỗi khi gọi Edge TTS API cho {os.path.basename(output_path)}: {e}")
        return False


# ==============================================================================
# --- HÀM TTS HUGGINGFACE (GIỌNG NGỌC HUYỀN) ---
# ==============================================================================

def _split_sentences_for_hf(text: str) -> list[str]:
    """Tách văn bản thành các câu riêng biệt để gửi cho HuggingFace TTS."""
    text = re.sub(r'\s+', ' ', text).strip()
    if not text: return []
    sentences = re.split(r'(?<=[.?!…])\s+', text)
    return [s.strip() for s in sentences if s.strip()]

async def convert_text_to_mp3_hf_ngochuyen(text: str, output_path: str, chat_id: int = None) -> bool:
    """

    Chuyển văn bản thành file MP3 bằng HuggingFace Spaces TTS (giọng Ngọc Huyền).

    Sử dụng cơ chế 88 Space song song với Queue & Retry tương tự DanTri.

    """
    # 1. Cấu hình danh sách 88 Space
    HF_SPACES = []
    for i in range(1, 9): HF_SPACES.append(f"ktvoice/kt{i:03d}")
    for g in range(0, 10):
        prefix = f"ktvoice{g}"
        for i in range(1, 9): HF_SPACES.append(f"{prefix}/kt{i:03d}")
    
    VOICE_NAME = "Ngọc Huyền"
    PAUSE_MODE = "Trung bình"
    SPEED = 1.0
    SILENCE_BETWEEN_SENTENCES = 0.8
    MAX_RETRIES = 3

    sentences = _split_sentences_for_hf(text)
    if not sentences:
        print("Lỗi: Văn bản đầu vào không chứa câu hợp lệ.")
        return False

    print(f"🎙️ [TTS HF] Bắt đầu xử lý: {len(sentences)} câu | Giọng: {VOICE_NAME}")
    if chat_id:
        await send_telegram_message(chat_id, f"🎙️ Đang tạo giọng đọc '{VOICE_NAME}' (HuggingFace)...\n- Tổng: {len(sentences)} câu")

    # 2. Khởi tạo Clients (Preload song song)
    active_clients = {}
    
    def preload_client(space_name):
        try:
            return space_name, Client(space_name)
        except Exception as e:
            print(f"❌ Space chết: {space_name} ({e}) -> Bỏ qua.")
            return space_name, None

    loop = asyncio.get_event_loop()
    print(f"🔌 Đang kiểm tra kết nối đến {len(HF_SPACES)} Spaces...")
    preload_tasks = [loop.run_in_executor(None, preload_client, space) for space in HF_SPACES]
    results = await asyncio.gather(*preload_tasks)
    
    for space_name, client_obj in results:
        if client_obj:
            active_clients[space_name] = client_obj
            
    available_spaces = list(active_clients.keys())
    if not available_spaces:
        print("❌ Toàn bộ Spaces đều không kết nối được!")
        return False
    
    print(f"✅ Đã kết nối: {len(available_spaces)}/{len(HF_SPACES)} Spaces hoạt động.")
    if chat_id:
        await send_telegram_message(chat_id, f"✅ Kết nối: {len(available_spaces)}/{len(HF_SPACES)} Spaces.")

    # Phân tải thông minh: Mỗi account chỉ dùng 1 space/batch
    def get_account_prefix(space_name):
        return space_name.split('/')[0]
    
    def select_balanced_spaces(all_spaces, count):
        random.shuffle(all_spaces)
        used_accounts = set()
        selected = []
        remaining = []
        for sp in all_spaces:
            acc = get_account_prefix(sp)
            if acc not in used_accounts:
                selected.append(sp)
                used_accounts.add(acc)
            else:
                remaining.append(sp)
            if len(selected) >= count:
                break
        if len(selected) < count:
            random.shuffle(remaining)
            selected.extend(remaining[:count - len(selected)])
        return selected[:count]

    temp_wav_files_map = {}
    tasks_queue = list(enumerate(sentences))
    sentence_retry_count = {i: 0 for i in range(len(sentences))}

    # 3. Worker function
    def call_gradio_tts_sync(space_name, sentence_text, index):
        try:
            client = active_clients.get(space_name)
            if not client: raise ValueError("Client mất kết nối")
            result = client.predict(
                sentence_text, VOICE_NAME, None, "", "preset", PAUSE_MODE, SPEED, api_name="/tts"
            )
            print(f"[TTS HF] Space: {space_name} | Result type: {type(result)} | Index: {index}")
            
            audio_origin_path = None
            if isinstance(result, (list, tuple)):
                for item in result:
                    if isinstance(item, str) and (item.endswith('.wav') or item.endswith('.mp3') or os.path.exists(str(item))):
                        audio_origin_path = item
                        break
                if not audio_origin_path and len(result) > 0 and result[0] is not None:
                    audio_origin_path = result[0]
            elif isinstance(result, str):
                audio_origin_path = result
            elif isinstance(result, dict):
                audio_origin_path = result.get('audio') or result.get('path') or result.get('name')
            
            if not audio_origin_path or not os.path.exists(str(audio_origin_path)):
                raise ValueError(f"API trả về không chứa file audio hợp lệ. Result: {result}")
            
            dest_filename = f"part_{index}_{random.randint(10000,99999)}.wav"
            dest_path = os.path.join(TEMP_PATH, dest_filename)
            shutil.copy(str(audio_origin_path), dest_path)
            return index, dest_path, None
        except Exception as e:
            return index, None, f"Lỗi tại {space_name}: {str(e)}"

    # 4. Queue processing
    while tasks_queue:
        num_tasks_to_run = min(len(tasks_queue), len(available_spaces))
        current_batch = tasks_queue[:num_tasks_to_run]
        tasks_queue = tasks_queue[num_tasks_to_run:]
        spaces_for_batch = select_balanced_spaces(available_spaces, num_tasks_to_run)
        
        print(f"--- ⚡ Batch: {len(current_batch)} câu (Còn lại: {len(tasks_queue)}) ---")
        
        batch_futures = []
        for i, (sent_idx, sent_text) in enumerate(current_batch):
            space = spaces_for_batch[i]
            batch_futures.append(
                loop.run_in_executor(None, call_gradio_tts_sync, space, sent_text, sent_idx)
            )
        
        results = await asyncio.gather(*batch_futures)
        
        for res_idx, res_path, res_error in results:
            if res_path:
                temp_wav_files_map[res_idx] = res_path
            else:
                retry_times = sentence_retry_count[res_idx]
                if retry_times < MAX_RETRIES:
                    sentence_retry_count[res_idx] += 1
                    print(f"⚠️ Câu {res_idx+1} lỗi: {res_error} | Thử lại lần {sentence_retry_count[res_idx]}")
                    tasks_queue.append((res_idx, sentences[res_idx]))
                else:
                    print(f"❌ Câu {res_idx+1} thất bại hoàn toàn sau {MAX_RETRIES} lần thử.")

    # 5. Ghép file
    sorted_indices = sorted(temp_wav_files_map.keys())
    if not sorted_indices:
        print("❌ Không tạo được file audio nào.")
        return False
        
    if len(sorted_indices) < len(sentences):
        print(f"⚠️ Cảnh báo: Chỉ tạo được {len(sorted_indices)}/{len(sentences)} câu.")

    concat_list_path = os.path.join(TEMP_PATH, f"concat_hf_{os.path.basename(output_path)}.txt")
    try:
        print("⏳ Đang ghép nối file...")
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        # Tạo file silence
        silence_wav_path = os.path.join(TEMP_PATH, "silence_hf_gap.wav")
        ffmpeg_create_silence = ['ffmpeg', '-y', '-f', 'lavfi', '-i', f'anullsrc=r=24000:cl=mono', '-t', str(SILENCE_BETWEEN_SENTENCES), silence_wav_path]
        process = await asyncio.create_subprocess_exec(*ffmpeg_create_silence, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        await process.communicate()
        
        # Tạo concat list
        with open(concat_list_path, "w") as f:
            for idx in sorted_indices:
                wav_file = temp_wav_files_map[idx]
                f.write(f"file '{os.path.abspath(wav_file)}'\n")
                if idx < sorted_indices[-1]:
                    f.write(f"file '{os.path.abspath(silence_wav_path)}'\n")

        # Ghép thành WAV rồi convert sang MP3
        temp_wav_output = output_path.replace('.mp3', '_temp.wav')
        ffmpeg_concat = ['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', temp_wav_output]
        process = await asyncio.create_subprocess_exec(*ffmpeg_concat, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0:
            raise subprocess.CalledProcessError(process.returncode, ffmpeg_concat, stderr=stderr)
        
        # Convert WAV -> MP3
        ffmpeg_to_mp3 = ['ffmpeg', '-y', '-i', temp_wav_output, '-codec:a', 'libmp3lame', '-b:a', '128k', output_path]
        process = await asyncio.create_subprocess_exec(*ffmpeg_to_mp3, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        _, stderr = await process.communicate()
        if process.returncode != 0:
            raise subprocess.CalledProcessError(process.returncode, ffmpeg_to_mp3, stderr=stderr)
        
        # Dọn file WAV tạm
        if os.path.exists(temp_wav_output): os.remove(temp_wav_output)
        if os.path.exists(silence_wav_path): os.remove(silence_wav_path)
        
        print(f"✅ Hoàn tất TTS HuggingFace: {output_path}")
        if chat_id:
            await send_telegram_message(chat_id, f"✅ Hoàn tất giọng đọc ({len(sorted_indices)}/{len(sentences)} câu).")
        return True

    except Exception as e:
        print(f"❌ Lỗi ghép file TTS HuggingFace: {e}")
        return False
    finally:
        for path in temp_wav_files_map.values():
            if os.path.exists(path): os.remove(path)
        if os.path.exists(concat_list_path): os.remove(concat_list_path)


async def convert_text_to_mp3_google(text: str, output_path: str) -> bool:
    """Chuyển văn bản thành file mp3 bằng Google TTS API."""
    # --- SỬA ĐỔI ---
    # Sử dụng biến GOOGLE_TTS_API_KEY toàn cục đã được đọc lúc khởi động.
    if not GOOGLE_TTS_API_KEY:
        print("Lỗi: GOOGLE_TTS_API_KEY chưa được cấu hình.")
        return False

    url = f"https://texttospeech.googleapis.com/v1/text:synthesize?key={GOOGLE_TTS_API_KEY}"
    body = {
        "input": {"text": text},
        "voice": {"languageCode": "vi-VN", "name": "vi-VN-Standard-A", "ssmlGender": "FEMALE"},
        "audioConfig": {"audioEncoding": "MP3", "speakingRate": 1.15, "pitch": 0.0, "volumeGainDb": 0.0}
    }
    try:
        # Đảm bảo thư mục đích tồn tại
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        response = await asyncio.to_thread(requests.post, url, json=body, timeout=180)
        response.raise_for_status()
        audio_content = response.json().get("audioContent")
        if audio_content:
            with open(output_path, "wb") as f:
                f.write(base64.b64decode(audio_content))
            return True
        return False
    except Exception as e:
        print(f"Lỗi khi gọi Google TTS API cho {os.path.basename(output_path)}: {e}")
        return False

async def read_audio_config_from_excel() -> dict:
    """

    Đọc cấu hình từ file Excel.

    THAY ĐỔI: Hàm này giờ sẽ đọc Google Drive File ID cho ảnh và font.

    """
    config = {
        "top": "", "end": "", "replacements": [], 
        "story_name": "Audio Book", "title_suffix": "Audio",
        # Các key cho đường dẫn cục bộ sau khi tải về
        "image_path": None, "title_font_path": None, "chap_font_path": None,
        # Các key mới để lưu File ID từ Google Drive
        "image_file_id": None, "title_font_file_id": None, "chap_font_file_id": None,
        "title_font_size": 150, "chap_font_size": 130,
        "description": "", "tags": [] # Thêm key mới
    }
    try:
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl")
        
        # Đọc các cấu hình văn bản như cũ
        if df.shape[0] > 1 and df.shape[1] > 3 and pd.notna(df.iloc[1, 3]): config["top"] = str(df.iloc[1, 3])
        if df.shape[0] > 2 and df.shape[1] > 3 and pd.notna(df.iloc[2, 3]): config["end"] = str(df.iloc[2, 3])
        if df.shape[1] > 4: config["replacements"] = df.iloc[1:10, 4].dropna().astype(str).tolist()
        if df.shape[0] > 3 and df.shape[1] > 6 and pd.notna(df.iloc[3, 6]): config["story_name"] = str(df.iloc[3, 6])
        if df.shape[0] > 0 and df.shape[1] > 10 and pd.notna(df.iloc[0, 10]): config["title_suffix"] = str(df.iloc[0, 10])

        # === THAY ĐỔI QUAN TRỌNG: Đọc Google Drive File ID thay vì đường dẫn tĩnh ===
        # Ô F2 (index 1, 5) -> image_file_id
        if df.shape[0] > 1 and df.shape[1] > 5 and pd.notna(df.iloc[1, 5]): config["image_file_id"] = str(df.iloc[1, 5])
        # Ô G2 (index 1, 6) -> title_font_file_id
        if df.shape[0] > 1 and df.shape[1] > 6 and pd.notna(df.iloc[1, 6]): config["title_font_file_id"] = str(df.iloc[1, 6])
        # Ô H2 (index 1, 7) -> chap_font_file_id
        if df.shape[0] > 1 and df.shape[1] > 7 and pd.notna(df.iloc[1, 7]): config["chap_font_file_id"] = str(df.iloc[1, 7])

        # Đọc kích thước font
        if df.shape[0] > 2 and df.shape[1] > 6 and pd.notna(df.iloc[2, 6]): config["title_font_size"] = int(df.iloc[2, 6])
        if df.shape[0] > 2 and df.shape[1] > 7 and pd.notna(df.iloc[2, 7]): config["chap_font_size"] = int(df.iloc[2, 7])
        
        # <<< BLOCK CODE MỚI BẮT ĐẦU
        # Đọc Description từ ô L1 (index 0, 11)
        if df.shape[1] > 11 and pd.notna(df.iloc[0, 11]): 
            config["description"] = str(df.iloc[0, 11])

        # Đọc Tags từ ô M1 (index 0, 12), tách chuỗi thành list
        if df.shape[1] > 12 and pd.notna(df.iloc[0, 12]):
            tags_str = str(df.iloc[0, 12])
            config["tags"] = [tag.strip() for tag in tags_str.split(',') if tag.strip()]
        # <<< BLOCK CODE MỚI KẾT THÚC
        
    except Exception as e:
        print(f"Lỗi khi đọc cấu hình từ Excel: {e}")
    return config

async def scrape_chapter_content(url: str, replacements: list[str]) -> tuple[str, str, str] | None:
    """Bóc tách nội dung của một chương truyện."""
    # --- LOGIC CŨ GIỮ NGUYÊN ---
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}
    try:
        response = await asyncio.to_thread(requests.get, url, headers=headers, timeout=20)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, "html.parser")
        title_tag = soup.select_one("a.chapter-title")
        raw_title = title_tag.get_text(strip=True) if title_tag else "Không tìm thấy tiêu đề"
        match = re.search(r"Chương\s*(\d+)", raw_title, re.IGNORECASE)
        chapter_number_str = f"unk_{pd.Timestamp.now().strftime('%H%M%S')}"
        if match:
            chapter_number_str = match.group(1).zfill(4)
        final_title = raw_title
        if not final_title.endswith('.'): final_title += '.'
        content_div = soup.select_one("div#chapter-c")
        if not content_div: return None
        for ad_element in content_div.select("div, script, ins, style, [class*='ads']"):
            ad_element.decompose()
        content = content_div.get_text("\n", strip=True)
        for unwanted_str in replacements:
            content = content.replace(unwanted_str, "")
        content = "\n".join(line for line in content.split('\n') if line.strip())
        return final_title, content, chapter_number_str
    except Exception as e:
        print(f"Lỗi khi bóc tách nội dung từ {url}: {e}"); return None

async def read_links_from_excel() -> list[str]:
    """Đọc danh sách link từ file Excel cục bộ."""
    # --- LOGIC CŨ GIỮ NGUYÊN ---
    try:
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl")
        if 1 in df.columns:
            return df.loc[1:, 1].dropna().astype(str).tolist()
    except FileNotFoundError:
        print(f"Lỗi: Không tìm thấy file Excel tại {WORKING_EXCEL_PATH}")
        return []
    except Exception as e:
        print(f"Lỗi khi đọc link từ Excel: {e}")
        return []
    return []

def escape_ffmpeg_text(text):
    """Thoát các ký tự đặc biệt cho bộ lọc drawtext của ffmpeg."""
    # --- LOGIC CŨ GIỮ NGUYÊN ---
    return text.replace('\\', '\\\\').replace("'", r"\'").replace(':', r'\:').replace('%', r'\%').replace(',', r'\,')

async def generate_single_mp4_with_effect(mp3_path: str, config: dict, chat_id: int) -> str | None:
    """Tạo video từ file MP3 và ảnh nền (đã tối ưu hóa tốc độ)."""
    required_paths = [mp3_path, config.get("image_path"), config.get("title_font_path"), config.get("chap_font_path")]
    for path in required_paths:
        if not path or not os.path.exists(path): # Kiểm tra cả None và sự tồn tại
            error_msg = f"❌ Lỗi Gen MP4: Không tìm thấy file hoặc đường dẫn tài nguyên: {path}"
            print(error_msg)
            await send_telegram_message(chat_id, error_msg)
            return None

    base_name = os.path.splitext(os.path.basename(mp3_path))[0]
    output_path = os.path.join(AUDIO_VIDEO_FOLDER, f"{base_name}.mp4")
    temp_video_path = os.path.join(TEMP_PATH, f"temp_{base_name}.mp4")
    try:
        story_name_text = escape_ffmpeg_text(config.get("story_name", ""))
        chap_text_final = f"Tập {base_name}"
        chap_nums = base_name.split('_')
        if len(chap_nums) == 2:
            try:
                start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1])
                chap_text_final = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
            except ValueError:
                chap_text_final = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
        chap_text = escape_ffmpeg_text(chap_text_final)
        title_font = str(config.get("title_font_path")).replace('\\', '/')
        
        print(f"[*] Bước 1/2: Đang tạo video mẫu 3 giây cho '{base_name}'...")
        drawtext_filter = (
            f"drawtext=fontfile='{title_font}':text='{story_name_text}':fontsize={config.get('title_font_size', 150)}:fontcolor=Red:x=100:y=50:shadowcolor=black@0.7:shadowx=2:shadowy=2,"
            f"drawtext=fontfile='{title_font}':text='{chap_text}':fontsize={config.get('chap_font_size', 130)}:fontcolor=Red:x=100:y=320:shadowcolor=black@0.7:shadowx=2:shadowy=2"
        )
        ffmpeg_cmd_step1 = [
            'ffmpeg', '-y', '-loop', '1', '-i', str(config.get("image_path")),
            '-vf', drawtext_filter, '-t', '3', '-pix_fmt', 'yuv420p',
            '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '28', temp_video_path
        ]
        process1 = await asyncio.create_subprocess_exec(*ffmpeg_cmd_step1, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        _, stderr1 = await process1.communicate()
        if process1.returncode != 0:
            print(f"❌ LỖI FFMPEG (Bước 1): {stderr1.decode()}"); return None

        print(f"[*] Bước 2/2: Đang ghép video và audio cho '{base_name}'...")
        ffmpeg_cmd_step2 = [
            'ffmpeg', '-y', '-stream_loop', '-1', '-i', temp_video_path,
            '-i', mp3_path, '-map', '0:v:0', '-map', '1:a:0',
            '-c:v', 'copy', '-af', 'volume=1.3','-c:a', 'aac', '-b:a', '128k', '-shortest', output_path
        ]
        process2 = await asyncio.create_subprocess_exec(*ffmpeg_cmd_step2, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
        _, stderr2 = await process2.communicate()
        if process2.returncode != 0:
            print(f"❌ LỖI FFMPEG (Bước 2): {stderr2.decode()}"); return None

        print(f"✅ Tạo MP4 thành công (tối ưu): {output_path}")
        return output_path
    except Exception as e:
        print(f"❌ Lỗi không xác định khi tạo MP4 cho '{base_name}': {e}"); return None
    finally:
        if os.path.exists(temp_video_path):
            os.remove(temp_video_path)

async def modify_excel_sheet(modifications: callable):
    """Hàm lõi an toàn để sửa đổi file Excel cục bộ."""
    # --- LOGIC CŨ GIỮ NGUYÊN, BỎ KHÓA ASYNCIO VÌ ĐANG CHẠY TRONG 1 LUỒNG ---
    try:
        book = load_workbook(WORKING_EXCEL_PATH)
        modifications(book)
        book.save(WORKING_EXCEL_PATH)
        return True
    except Exception as e:
        print(f"Lỗi nghiêm trọng khi sửa đổi file Excel: {e}")
        return False

async def clear_excel_audio_links():
    """Xóa dữ liệu ở cột B và C của sheet 'Audio'."""
    def clear_data(book):
        if "Audio" not in book.sheetnames: return
        ws = book["Audio"]
        for row in ws.iter_rows(min_row=2, min_col=2, max_col=3):
            for cell in row:
                cell.value = None
        print("✅ Đã xóa dữ liệu link trong sheet 'Audio'.")
    return await modify_excel_sheet(clear_data)

async def update_audio_sheet(data: list[dict], is_first_scrape: bool) -> bool:
    """Cập nhật SỐ CHƯƠNG CHUẨN, link và tiêu đề vào sheet 'Audio'."""
    new_chap_nums = [item.get("chapter_number") for item in data]
    new_links = [item["link"] for item in data]
    new_titles = [item["title"] for item in data]

    def update_data(book):
        ws = book["Audio"]
        if ws.cell(row=1, column=1).value is None: # Kiểm tra header cột A
            ws.cell(row=1, column=1, value="Chapter Number")
            ws.cell(row=1, column=2, value="Link")
            ws.cell(row=1, column=3, value="Title")
        
        start_row = 2 if is_first_scrape else ws.max_row + 1
        for i, (chap_num, link, title) in enumerate(zip(new_chap_nums, new_links, new_titles)):
            # Ghi dữ liệu vào đúng cột: A, B, C
            if chap_num is not None:
                ws.cell(row=start_row + i, column=1, value=chap_num) # <<< Cột A
            ws.cell(row=start_row + i, column=2, value=link)     # <<< Cột B
            ws.cell(row=start_row + i, column=3, value=title)    # <<< Cột C
        print(f"✅ Đã cập nhật {len(new_links)} link mới (vào cột A, B, C) trong sheet 'Audio'.")
    return await modify_excel_sheet(update_data)

async def update_excel_for_youtube(video_data: list[dict]) -> bool:
    """Cập nhật đường dẫn video và tiêu đề cho YouTube."""
    def update_yt_data(book):
        if "Audio" not in book.sheetnames: return
        ws = book["Audio"]
        paths = [item['path'] for item in video_data]
        titles = [item['title'] for item in video_data]
        for i, (path, title) in enumerate(zip(paths, titles)):
            ws.cell(row=i + 2, column=9, value=path)
            ws.cell(row=i + 2, column=10, value=title)
        print(f"✅ Đã cập nhật {len(paths)} video vào Excel cho YouTube.")
    return await modify_excel_sheet(update_yt_data)

async def rewrite_excel_links(links_to_keep: list[dict]):
    """Xóa và ghi lại các cột số chương/link/tiêu đề trong sheet 'Audio'."""
    def modify_links(book):
        if "Audio" not in book.sheetnames: return
        ws = book["Audio"]
        # Xóa dữ liệu từ cột A đến C (index 1-3)
        for row in ws.iter_rows(min_row=2, min_col=1, max_col=3):
            for cell in row:
                cell.value = None
        # Ghi lại dữ liệu mới
        for i, item in enumerate(links_to_keep):
            if item.get('chapter_number') is not None:
                ws.cell(row=i + 2, column=1, value=item.get('chapter_number')) # Cột A
            ws.cell(row=i + 2, column=2, value=item.get('link'))             # Cột B
            ws.cell(row=i + 2, column=3, value=item.get('title'))            # Cột C
        print(f"✅ Đã ghi lại {len(links_to_keep)} link chưa xử lý vào Excel.")
    return await modify_excel_sheet(modify_links)

async def upload_single_video_to_youtube_audio(account_number: int, video_path: str, video_title: str, chat_id: int, config: dict) -> bool:
    """Upload một video lên YouTube, đã tích hợp quy trình xác thực mới."""
    try:
        # 1. Lấy credentials chính của Drive
        drive_creds = await get_drive_credentials(chat_id)
        if not drive_creds:
            raise Exception("Không thể lấy credentials của Drive.")
        drive_service = build('drive', 'v3', credentials=drive_creds)

        # 2. Tìm và tải file token của tài khoản YouTube từ Drive
        token_filename = f'token_youtube_account_{account_number}.pickle'
        print(f"[*] Đang tìm kiếm '{token_filename}' trong thư mục Drive '{DRIVE_YTB_ACCOUNT_FOLDER_ID}'...")
        query = f"name='{token_filename}' and '{DRIVE_YTB_ACCOUNT_FOLDER_ID}' in parents and trashed=false"
        response = await asyncio.to_thread(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 cho tài khoản {account_number} trên Drive.")
            return False

        file_id = files[0].get('id')
        local_yt_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, token_filename)
        await download_file_from_drive(drive_service, file_id, local_yt_token_path)

        # 3. Load credentials YouTube và thực hiện upload
        with open(local_yt_token_path, 'rb') as token:
            yt_creds = pickle.load(token)

        if not yt_creds or not yt_creds.valid:
             if yt_creds and yt_creds.expired and yt_creds.refresh_token:
                 print(f"[*] Token YouTube cho tài khoản {account_number} đã hết hạn, đang làm mới...")
                 yt_creds.refresh(GoogleAuthRequest())
                 # Lưu lại file token mới vào thư mục tạm
                 with open(local_yt_token_path, 'wb') as token: 
                     pickle.dump(yt_creds, token)
                 print(f"[*] Làm mới token thành công. Đang upload token mới lên Google Drive...")
                 # === PHẦN SỬA ĐỔI QUAN TRỌNG ===
                 # Tìm file token cũ trên Drive để lấy ID và ghi đè
                 token_file_on_drive = files[0] # files là kết quả từ drive_service.files().list()
                 media = MediaFileUpload(local_yt_token_path)
                 await asyncio.to_thread(
                     drive_service.files().update(fileId=token_file_on_drive.get('id'), media_body=media).execute
                 )
                 print(f"[*] Upload token mới thành công.")
                 # === KẾT THÚC SỬA ĐỔI ===
             else:
                 raise Exception(f"Token cho tài khoản {account_number} không hợp lệ hoặc đã hết hạn.")



        youtube = build('youtube', 'v3', credentials=yt_creds)
        body = {
            'snippet': {
                'title': video_title, 
                'description': config.get("description", ""), # <<< DÒNG THAY ĐỔI
                'tags': config.get("tags", []), # <<< DÒNG THAY ĐỔI
                '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 to YouTube... {int(status.progress() * 100)}%")

        # === PHẦN SỬA ĐỔI QUAN TRỌNG ===
        if response and 'id' in response:
            video_id = response.get('id')
            await send_telegram_message(chat_id, f"✅ Upload YouTube thành công: `{video_title}`\n🔗 Link: https://www.youtube.com/watch?v={video_id}")
            return True
        else:
            # Nếu không có 'id', upload đã thất bại. Gửi thông báo lỗi chi tiết.
            error_details = str(response) if response else "Không nhận được phản hồi từ YouTube API."
            print(f"❌ Lỗi Upload YouTube: {error_details}")
            await send_telegram_message(chat_id, f"❌ Lỗi khi upload video `{video_title}` lên YouTube.\n<b>Chi tiết:</b> <pre>{error_details}</pre>", parse_mode="HTML")
            return False


    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi upload video `{video_title}`: {e}")
        return False

async def process_and_generate_text_files(chat_id: int):
    """Quy trình cho nút 'Get File', chạy dưới dạng tác vụ nền."""
    await send_telegram_message(chat_id=chat_id, text="🔍 Bắt đầu quy trình Get File...")
    
    replacement_map = await _read_replacement_map_from_excel()
    drive_creds = await get_drive_credentials(chat_id)
    if not drive_creds:
        await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive."); return
    drive_service = build('drive', 'v3', credentials=drive_creds)

    try:
        # Sửa: Đọc đúng các cột A, B, C (index 0, 1, 2)
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1, 2])
        all_links_data = []
        for index, row in df.loc[1:].iterrows():
            chap_num = int(row.get(0)) if pd.notna(row.get(0)) else None # Đọc cột A
            link = str(row.get(1)) if pd.notna(row.get(1)) else None      # Đọc cột B
            title = str(row.get(2)) if pd.notna(row.get(2)) else ""       # Đọc cột C
            if link: 
                all_links_data.append({'link': link, 'title': title, 'chapter_number': chap_num})
    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi khi đọc file Excel: {e}"); return
    
    if not all_links_data:
        await send_telegram_message(chat_id, "Không tìm thấy link nào trong sheet 'Audio'."); return

    await send_telegram_message(chat_id, f"✅ Tìm thấy {len(all_links_data)} link. Bắt đầu xử lý...")
    config = await read_audio_config_from_excel()
    os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
    
    new_count, skipped_count, error_links_data = 0, 0, []
    created_local_files = []
    existing_txt_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)}

    for i, link_data in enumerate(all_links_data):
        try:
            chapter_number_from_excel = link_data.get('chapter_number')
            
            if chapter_number_from_excel is None:
                # Sửa thông báo cho đúng
                print(f"⚠️ Bỏ qua link {link_data['link']} vì không có số chương ở cột A.")
                error_links_data.append(link_data)
                continue

            filename = f"{str(chapter_number_from_excel).zfill(4)}.txt"

            if filename in existing_txt_on_drive:
                skipped_count += 1
                continue

            result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
            
            if result:
                title, body, _ = result 
                filepath = os.path.join(AUDIO_TXT_FOLDER, filename)
                
                file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
                final_content = _apply_replacements(file_content, replacement_map)
                with open(filepath, 'w', encoding='utf-8') as f: f.write(final_content)
                new_count += 1
                created_local_files.append(filepath)
            else:
                error_links_data.append(link_data)
        except Exception as e:
            print(f"Lỗi xử lý link {link_data['link']}: {e}")
            error_links_data.append(link_data)

    if created_local_files:
        await send_telegram_message(chat_id, f"Đang upload {len(created_local_files)} file .txt lên Google Drive...")
        for local_path in created_local_files:
            await upload_file_to_drive_folder(drive_service, local_path, DRIVE_AUDIO_TXT_FOLDER_ID)

    await send_telegram_message(chat_id, "...Đang cập nhật lại file Excel...")
    await rewrite_excel_links(error_links_data)
    await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)

    final_message = (f"🎉 **GET FILE HOÀN TẤT** 🎉\n\n"
                     f"- Tạo mới và upload: **{new_count}** file .txt\n"
                     f"- Bỏ qua (đã có trên Drive): **{skipped_count}** file\n"
                     f"- Lỗi: **{len(error_links_data)}** link (được giữ lại trong Excel)\n\n"
                     f"✅ Các file .txt đã sẵn sàng trên Google Drive.")
    await send_telegram_message(chat_id, final_message, reply_markup=AUDIO_MENU_KEYBOARD)




async def run_full_mp3_generation_process(chat_id: int, user_data: dict):
    voice_choice = user_data.get("voice_choice", "female")
    voice_names = {"male": "Nam", "female": "Nữ", "ngochuyen": "Ngọc Huyền"}
    voice_name = voice_names.get(voice_choice, "Nữ")
   
    await send_telegram_message(chat_id=chat_id, text="🚀 Bắt đầu quy trình tạo MP3 (có khả năng phục hồi)...")
    
    drive_creds = await get_drive_credentials(chat_id)
    if not drive_creds:
        await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
        return
    drive_service = build('drive', 'v3', credentials=drive_creds)

    # --- GIAI ĐOẠN 1: TẠO MP3 TỪNG CHƯƠNG ---
    await send_telegram_message(chat_id, "➡️ GĐ 1/2: Tạo MP3 chương...")
    
    # Tải các file txt từ Drive về
    txt_files_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)
    if not txt_files_on_drive:
        await send_telegram_message(chat_id, "Không tìm thấy file .txt nào trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD); return
    
    os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
    await send_telegram_message(chat_id, f"Đang tải {len(txt_files_on_drive)} file .txt từ Drive...")
    for file in txt_files_on_drive:
        await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_TXT_FOLDER, file['name']))
        
    # Lấy danh sách chapter MP3 đã có trên Drive để bỏ qua
    existing_mp3s_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)}
    
    local_txt_files = sorted(os.listdir(AUDIO_TXT_FOLDER))
    for i, filename in enumerate(local_txt_files):
        base_name = os.path.splitext(filename)[0]
        mp3_filename = f"{base_name}.mp3"

        if mp3_filename in existing_mp3s_on_drive:
            print(f"Bỏ qua {mp3_filename}, đã có trên Drive.")
            continue

        #await send_telegram_message(chat_id, f"⚙️ 1/2: Đang xử lý `{filename}` ({i + 1}/{len(local_txt_files)})...")
        temp_dir = os.path.join(TEMP_PATH, f"temp_{base_name}"); os.makedirs(temp_dir, exist_ok=True)
        is_ok, segments, chapter_mp3_path = True, [], os.path.join(AUDIO_MP3_FOLDER, mp3_filename)
        #try:
        #    with open(os.path.join(AUDIO_TXT_FOLDER, filename), "r", encoding="utf-8") as f: text = f.read()
        #    chunks = split_text_into_chunks(text)
        #    for j, chunk in enumerate(chunks):
        #        seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
        #        if voice_choice == 'male':
        #            if not await convert_text_to_mp3_edge(chunk, seg_path): is_ok = False; break
        #        else: # Mặc định hoặc 'female'
        #            if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
        #        #segments.append(seg_path)
        #        
        #        #if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
        #        segments.append(seg_path)
        #    if is_ok and segments and not await merge_mp3_files_ffmpeg(segments, chapter_mp3_path): is_ok = False
        #finally: shutil.rmtree(temp_dir)
        
        #if is_ok:
        #    await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)


        try:
            with open(os.path.join(AUDIO_TXT_FOLDER, filename), "r", encoding="utf-8") as f:
                text = f.read()
            chunks = split_text_into_chunks(text)

            if voice_choice == 'ngochuyen':
                # Giọng Ngọc Huyền: gửi toàn bộ text cho HuggingFace xử lý theo câu
                if not await convert_text_to_mp3_hf_ngochuyen(text, chapter_mp3_path, chat_id):
                    is_ok = False
                else:
                    # HF đã tạo file MP3 xong, không cần merge nữa
                    segments = []  # Clear để skip merge step
            else:
                for j, chunk in enumerate(chunks):
                    seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
                    if voice_choice == 'male':
                        if not await convert_text_to_mp3_edge(chunk, seg_path): is_ok = False; break
                    else:
                        if not await convert_text_to_mp3_google(chunk, seg_path): is_ok = False; break
                    segments.append(seg_path)

            # Chỉ merge và upload khi các bước trước thành công
            if is_ok and segments:
                if await merge_mp3_files_ffmpeg(segments, chapter_mp3_path):
                    await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
                else:
                    is_ok = False
            elif is_ok and voice_choice == 'ngochuyen' and os.path.exists(chapter_mp3_path):
                # HF đã tạo file trực tiếp, chỉ cần upload
                await upload_file_to_drive_folder(drive_service, chapter_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
        
        except Exception as e:
            print(f"Lỗi khi xử lý file {filename}: {e}")
            is_ok = False
        finally:
            # Luôn dọn dẹp thư mục tạm sau khi tất cả đã xong
            shutil.rmtree(temp_dir)
    # --- GIAI ĐOẠN 2: NỐI CÁC FILE MP3 ---
    await send_telegram_message(chat_id, f"➡️ GĐ 2/2: Nối các file MP3 chương...")
    try:
        df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
        group_size = int(df_audio.iloc[0, 3])
    except: group_size = 20 # Giá trị mặc định

    all_chapter_mp3s = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)
    if not all_chapter_mp3s:
        await send_telegram_message(chat_id, "Lỗi: Không tìm thấy file MP3 chương nào trên Drive để nối."); return

    # Tải tất cả MP3 chương về để nối
    os.makedirs(AUDIO_MP3_FOLDER, exist_ok=True)
    for file in all_chapter_mp3s:
        await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_MP3_FOLDER, file['name']))

    local_mp3_paths = sorted([os.path.join(AUDIO_MP3_FOLDER, f) for f in os.listdir(AUDIO_MP3_FOLDER)])
    file_groups = [local_mp3_paths[i : i + group_size] for i in range(0, len(local_mp3_paths), group_size)]
    existing_final_mp3s_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)}

    for i, group in enumerate(file_groups):
        if not group: continue
        first, last = os.path.splitext(os.path.basename(group[0]))[0], os.path.splitext(os.path.basename(group[-1]))[0]
        final_name = f"{first}_{last}.mp3"

        if final_name in existing_final_mp3s_on_drive:
            print(f"Bỏ qua nối file {final_name}, đã có trên Drive.")
            continue
            
        #await send_telegram_message(chat_id, f"⚙️ 2/2: Nối nhóm {i + 1}/{len(file_groups)} -> `{final_name}`...")
        final_output_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)
        if await merge_mp3_files_ffmpeg(group, final_output_path):
            await upload_file_to_drive_folder(drive_service, final_output_path, DRIVE_AUDIO_FINAL_FOLDER_ID)

    await send_telegram_message(chat_id, "🎉 **QUY TRÌNH MP3 HOÀN TẤT** 🎉\nCác file MP3 đã nối đã sẵn sàng trên Google Drive.", reply_markup=AUDIO_MENU_KEYBOARD)


async def process_and_generate_mp4_files(chat_id: int, user_data: dict):
    await send_telegram_message(chat_id=chat_id, text="🔍 Bắt đầu quy trình tạo Video cuối cùng...")
    
    drive_creds = await get_drive_credentials(chat_id)
    if not drive_creds:
        await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
        return
    drive_service = build('drive', 'v3', credentials=drive_creds)

    # --- TẢI TÀI NGUYÊN (FONT, ẢNH NỀN) TỪ DRIVE ---
    await send_telegram_message(chat_id, "➡️ Bước 1/4: Tải tài nguyên (font, ảnh nền)...")
    config = await read_audio_config_from_excel()
    try:
        # Lấy File ID từ config
        image_file_id = config.get("image_file_id")
        title_font_id = config.get("title_font_file_id")
        chap_font_id = config.get("chap_font_file_id")

        if not all([image_file_id, title_font_id, chap_font_id]):
            await send_telegram_message(chat_id, "❌ Lỗi cấu hình: Vui lòng cung cấp đủ File ID cho ảnh nền, font tiêu đề và font chương trong file Excel (ô F2, G2, H2).")
            return
            
        # Đường dẫn lưu file cục bộ trên Hugging Face
        local_image_path = os.path.join(TEMP_PATH, "background_image.jpg")
        local_title_font_path = os.path.join(TEMP_PATH, "title_font.ttf")
        local_chap_font_path = os.path.join(TEMP_PATH, "chap_font.ttf")

        # Tải file từ Drive
        await send_telegram_message(chat_id, "...Đang tải ảnh nền...")
        await download_file_from_drive(drive_service, image_file_id, local_image_path)
        
        await send_telegram_message(chat_id, "...Đang tải font chữ...")
        await download_file_from_drive(drive_service, title_font_id, local_title_font_path)
        await download_file_from_drive(drive_service, chap_font_id, local_chap_font_path)
        
        config["image_path"] = local_image_path
        config["title_font_path"] = local_title_font_path
        config["chap_font_path"] = local_chap_font_path
        
    except Exception as e:
        await send_telegram_message(chat_id, f"❌ Lỗi nghiêm trọng khi tải file tài nguyên từ Drive: {e}\nHãy kiểm tra lại File ID trong Excel và quyền truy cập file.")
        return


    # --- TẢI CÁC FILE MP3 ĐÃ NỐI ---
    await send_telegram_message(chat_id, "➡️ Bước 2/4: Tải các file MP3 đã nối...")
    final_mp3s_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)
    if not final_mp3s_on_drive:
        await send_telegram_message(chat_id, "Không tìm thấy file MP3 đã nối nào trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD); return
    
    os.makedirs(AUDIO_FINAL_FOLDER, exist_ok=True)
    for file in final_mp3s_on_drive:
        await download_file_from_drive(drive_service, file['id'], os.path.join(AUDIO_FINAL_FOLDER, file['name']))

    # --- TẠO VIDEO ---
    await send_telegram_message(chat_id, f"✅ Sẵn sàng tạo video. Bước 3/4: Bắt đầu xử lý...")
    existing_videos_on_drive = {f['name'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}

    successful_videos, new_count, success_count, skipped_count = [], 0, 0, 0
    local_mp3_files = sorted(os.listdir(AUDIO_FINAL_FOLDER))

    for i, mp3_filename in enumerate(local_mp3_files):
        #await send_telegram_message(chat_id, f"⚙️ 3/4: Đang tạo video cho `{mp3_filename}` ({i + 1}/{len(local_mp3_files)})...")
        base_name = os.path.splitext(mp3_filename)[0]
        mp4_filename = f"{base_name}.mp4"
        if mp4_filename in existing_videos_on_drive:
            print(f"[*] Bỏ qua '{mp4_filename}', đã tồn tại trên Drive.")
            skipped_count += 1
            # Thêm vào danh sách để vẫn có thể upload lên Youtube nếu cần
            successful_videos.append({"path": os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename), "base_name": base_name})
            continue
        
        source_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
        generated_path = await generate_single_mp4_with_effect(source_mp3_path, config, chat_id)
        
        if generated_path:
            success_count += 1
            #base_name = os.path.splitext(mp3_filename)[0]
            successful_videos.append({"path": generated_path, "base_name": base_name})
            await upload_video_to_drive_audio(drive_service, generated_path, chat_id)

    if not successful_videos:
        await send_telegram_message(chat_id, "❌ Không tạo được video nào.", reply_markup=AUDIO_MENU_KEYBOARD); return
        
    final_message = f"✅ **Tạo Video hoàn tất!**\n- Tạo thành công: **{success_count}** video.\n- Bỏ qua (đã có): **{skipped_count}** video."
    await send_telegram_message(chat_id, final_message)
    
    video_data_for_excel = []
    for video in successful_videos:
        # ... (logic tạo title video giữ nguyên)
        chap_range = f"Tập {video['base_name']}"; chap_nums = video["base_name"].split("_")
        if len(chap_nums) == 2:
            try:
                start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1]); chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
            except ValueError: chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
        title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
        video_data_for_excel.append({"path": video["path"], "title": title})

    # Upload video cuối cùng lên thư mục video trên Drive
    for video_data in video_data_for_excel:
        await upload_video_to_drive_audio(drive_service, video_data["path"], chat_id)

    # --- BƯỚC DỌN DẸP CUỐI CÙNG ---
    await send_telegram_message(chat_id, f"➡️ Bước 4/4: Dọn dẹp các file trung gian trên Drive...")
    await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)
    await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
    await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)

    # --- HỎI UPLOAD YOUTUBE ---
    if await update_excel_for_youtube(video_data_for_excel):
        user_data["videos_to_upload"] = video_data_for_excel
        user_data["config"] = config 
        
        # SỬA LỖI: Thêm 2 dòng này để cập nhật trạng thái người dùng
        user_data["state"] = AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE
        user_sessions[str(chat_id)] = user_data # Cập nhật vào session chung

        await send_telegram_message(chat_id, "Đã cập nhật Excel. Bạn có muốn upload lên YouTube không?", reply_markup=YOUTUBE_UPLOAD_CONFIRM_KEYBOARD)
    else:
        await send_telegram_message(chat_id, "Tạo video thành công nhưng lỗi cập nhật Excel.", reply_markup=AUDIO_MENU_KEYBOARD)

async def run_bulk_youtube_upload(chat_id: int, user_data: dict, account_number: int, config: dict) -> tuple[int, int]:
    videos_to_upload = user_data.get("videos_to_upload", [])
    if not videos_to_upload:
        await send_telegram_message(chat_id, "Không tìm thấy danh sách video để upload.")
        return 0, 0

    await send_telegram_message(chat_id, f"Bắt đầu upload {len(videos_to_upload)} video lên tài khoản YouTube {account_number}...")
    success_count, error_count = 0, 0
    successful_uploads = [] # <-- Thêm dòng này
    for i, video_data in enumerate(videos_to_upload):
        await send_telegram_message(chat_id, f"Đang upload video {i + 1}/{len(videos_to_upload)}: `{video_data['title']}`...")

        # === PHẦN SỬA ĐỔI QUAN TRỌNG ===
        success = await upload_single_video_to_youtube_audio(
            account_number=account_number, 
            video_path=video_data["path"], 
            video_title=video_data["title"], 
            chat_id=chat_id, 
            config=config
        )
        if success:
            success_count += 1
            successful_uploads.append(video_data) # <-- Thêm dòng này
        else:
            error_count += 1
        # === KẾT THÚC SỬA ĐỔI ===

    final_message = f"🎉 UPLOAD HOÀN TẤT 🎉\n\n- Thành công: {success_count} video.\n- Thất bại: {error_count} video."
    await send_telegram_message(chat_id, final_message, reply_markup=AUDIO_MENU_KEYBOARD)
    return successful_uploads # <-- Thay đổi ở đây


async def create_chapter_mp3(local_txt_path: str, output_mp3_path: str, voice: str) -> bool:
    """Tách logic tạo một file MP3 của chương ra hàm riêng."""
    base_name = os.path.splitext(os.path.basename(local_txt_path))[0]
    temp_dir = os.path.join(TEMP_PATH, f"temp_{base_name}")
    os.makedirs(temp_dir, exist_ok=True)
    is_ok, segments = True, []
    try:
        with open(local_txt_path, "r", encoding="utf-8") as f:
            text = f.read()
        if voice == 'ngochuyen':
            # Giọng Ngọc Huyền: gửi toàn bộ text cho HuggingFace
            if not await convert_text_to_mp3_hf_ngochuyen(text, output_mp3_path):
                is_ok = False
            # HF đã tạo file MP3 xong -> return luôn, không cần merge
            return is_ok
        
        chunks = split_text_into_chunks(text)
        for j, chunk in enumerate(chunks):
            seg_path = os.path.join(temp_dir, f"s_{j:03d}.mp3")
            if voice == 'male':
                if not await convert_text_to_mp3_edge(chunk, seg_path):
                    is_ok = False
                    break
            else:
                if not await convert_text_to_mp3_google(chunk, seg_path):
                    is_ok = False
                    break
            segments.append(seg_path)

        if is_ok and segments:
            if not await merge_mp3_files_ffmpeg(segments, output_mp3_path):
                is_ok = False
    except Exception as e:
        print(f"Lỗi trong quá trình tạo MP3 cho {base_name}: {e}")
        is_ok = False
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)
    return is_ok

async def run_one_click_workflow(chat_id: int, user_data: dict):
    """

    PHIÊN BẢN DEBUG: Thêm các lệnh print để tìm ra tại sao logic kiểm tra file lại sai.

    """
    drive_service = None
    try:
        await send_telegram_message(chat_id, "🚀 **Bắt đầu Quy trình One Click (PHIÊN BẢN DEBUG)**\n\n`➡️ GĐ 0: Khởi tạo...`")
        
        voice_choice = user_data.get("voice_choice", "female")
        config = await read_audio_config_from_excel()
        replacement_map = await _read_replacement_map_from_excel()
        
        drive_creds = await get_drive_credentials(chat_id)
        if not drive_creds: raise Exception("Không thể xác thực với Google Drive.")
        drive_service = build('drive', 'v3', credentials=drive_creds)

        await send_telegram_message(chat_id, "🔎 Đang lấy danh sách file trên Google Drive...")
        
        drive_files_map = {
            "txt": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)},
            "mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)},
            "final_mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)},
            "video": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}
        }
        
        # ==============================================================================
        # === DÒNG DEBUG ĐẦU TIÊN: IN RA TOÀN BỘ DANH SÁCH FILE TXT ĐÃ TÌM THẤY =======
        # ==============================================================================
        print("\n" + "="*80)
        print("DEBUG: DANH SÁCH FILE .TXT TÌM THẤY TRÊN DRIVE (KEYS CỦA DICTIONARY):")
        print(drive_files_map["txt"].keys())
        print(f"Tổng số file: {len(drive_files_map['txt'])}")
        print("="*80 + "\n")
        await send_telegram_message(chat_id, f"✅ Đã lấy được {len(drive_files_map['txt'])} file TXT từ Drive. Bắt đầu kiểm tra...")

        # ==============================================================================
        # === GIAI ĐOẠN 1: XỬ LÝ FILE TEXT (.txt) VỚI DEBUG ===========================
        # ==============================================================================
        await send_telegram_message(chat_id, "`➡️ GĐ 1/4: Xử lý file Text (.txt)...`")
        
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1])
        all_links_data = [{'link': str(row[1]), 'chapter_number': int(row[0])} for _, row in df.loc[1:].iterrows() if pd.notna(row[1]) and pd.notna(row[0])]
        
        links_to_keep_in_excel = []
        
        for link_data in all_links_data:
            expected_filename = f"{str(link_data['chapter_number']).zfill(4)}.txt"
            local_filepath = os.path.join(AUDIO_TXT_FOLDER, expected_filename)

            # ==============================================================================
            # === DÒNG DEBUG THỨ HAI: IN RA TÊN FILE DỰ ĐỊNH NGAY TRƯỚC KHI SO SÁNH =====
            # ==============================================================================
            print(f"\n--- Đang kiểm tra chương {link_data['chapter_number']} ---")
            print(f"DEBUG: Tên file dự định được tạo ra là: '{expected_filename}' (Kiểu dữ liệu: {type(expected_filename)})")

            if expected_filename in drive_files_map["txt"]:
                print(f"DEBUG >>> KẾT QUẢ: TÌM THẤY. File '{expected_filename}' đã có trong danh sách. Sẽ bỏ qua.")
                if not os.path.exists(local_filepath):
                     await download_file_from_drive(drive_service, drive_files_map["txt"][expected_filename], local_filepath)
            else:
                print(f"DEBUG >>> KẾT QUẢ: KHÔNG TÌM THẤY. File '{expected_filename}' không có trong danh sách. Sẽ tiến hành cào dữ liệu.")
                
                result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
                if result:
                    title, body, _ = result
                    file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
                    final_content = _apply_replacements(file_content, replacement_map)
                    with open(local_filepath, 'w', encoding='utf-8') as f: f.write(final_content)
                    file_id = await upload_file_to_drive_folder(drive_service, local_filepath, DRIVE_AUDIO_TXT_FOLDER_ID)
                    if file_id: drive_files_map["txt"][expected_filename] = file_id
                else:
                    links_to_keep_in_excel.append(link_data)
        
        await rewrite_excel_links(links_to_keep_in_excel)
        await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)

        # ==============================================================================
        # === GIAI ĐOẠN 2, 3, 4: Code đầy đủ, tuân thủ logic kiểm tra và download ========
        # ==============================================================================
        
        # --- Giai đoạn 2: Xử lý MP3 ---
        await send_telegram_message(chat_id, "`✅ GĐ 1`\n`➡️ GĐ 2/4: Tạo file Âm thanh (.mp3)...`")
        for txt_filename in sorted(drive_files_map["txt"].keys()):
            mp3_filename = f"{os.path.splitext(txt_filename)[0]}.mp3"
            local_mp3_path = os.path.join(AUDIO_MP3_FOLDER, mp3_filename)

            if mp3_filename in drive_files_map["mp3"]:
                if not os.path.exists(local_mp3_path):
                    await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_filename], local_mp3_path)
            else:
                local_txt_path = os.path.join(AUDIO_TXT_FOLDER, txt_filename)
                if not os.path.exists(local_txt_path):
                    await download_file_from_drive(drive_service, drive_files_map["txt"][txt_filename], local_txt_path)
                
                is_ok = await create_chapter_mp3(local_txt_path, local_mp3_path, voice_choice)
                if is_ok:
                    file_id = await upload_file_to_drive_folder(drive_service, local_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
                    if file_id: drive_files_map["mp3"][mp3_filename] = file_id
                else:
                    raise Exception(f"Lỗi tạo MP3 cho {mp3_filename}")

        df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
        group_size = int(df_audio.iloc[0, 3])
        all_chapter_mp3s = sorted(drive_files_map["mp3"].keys())
        file_groups = [all_chapter_mp3s[i:i+group_size] for i in range(0, len(all_chapter_mp3s), group_size)]
        
        for group in file_groups:
            if not group: continue
            final_name = f"{os.path.splitext(group[0])[0]}_{os.path.splitext(group[-1])[0]}.mp3"
            local_final_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)

            if final_name in drive_files_map["final_mp3"]:
                if not os.path.exists(local_final_path):
                    await download_file_from_drive(drive_service, drive_files_map["final_mp3"][final_name], local_final_path)
            else:
                local_group_paths = []
                for mp3_name in group:
                    local_path = os.path.join(AUDIO_MP3_FOLDER, mp3_name)
                    if not os.path.exists(local_path):
                        await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_name], local_path)
                    local_group_paths.append(local_path)
                
                if await merge_mp3_files_ffmpeg(local_group_paths, local_final_path):
                    file_id = await upload_file_to_drive_folder(drive_service, local_final_path, DRIVE_AUDIO_FINAL_FOLDER_ID)
                    if file_id: drive_files_map["final_mp3"][final_name] = file_id
        
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)

        # --- Giai đoạn 3: Xử lý Video ---
        await send_telegram_message(chat_id, "`✅ GĐ 1, 2`\n`➡️ GĐ 3/4: Tạo file Video (.mp4)...`")
        
        image_file_id, title_font_id, chap_font_id = config.get("image_file_id"), config.get("title_font_file_id"), config.get("chap_font_file_id")
        if not all([image_file_id, title_font_id, chap_font_id]): raise Exception("Lỗi cấu hình: Thiếu File ID cho ảnh/font.")
        config["image_path"] = os.path.join(TEMP_PATH, "background_image.jpg"); config["title_font_path"] = os.path.join(TEMP_PATH, "title_font.ttf"); config["chap_font_path"] = os.path.join(TEMP_PATH, "chap_font.ttf")
        await download_file_from_drive(drive_service, image_file_id, config["image_path"]); await download_file_from_drive(drive_service, title_font_id, config["title_font_path"]); await download_file_from_drive(drive_service, chap_font_id, config["chap_font_path"])

        successful_videos = []
        for mp3_filename in sorted(drive_files_map["final_mp3"].keys()):
            mp4_filename = f"{os.path.splitext(mp3_filename)[0]}.mp4"
            local_video_path = os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename)

            if mp4_filename in drive_files_map["video"]:
                if not os.path.exists(local_video_path):
                    await download_file_from_drive(drive_service, drive_files_map["video"][mp4_filename], local_video_path)
            else:
                local_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
                if not os.path.exists(local_mp3_path):
                    await download_file_from_drive(drive_service, drive_files_map["final_mp3"][mp3_filename], local_mp3_path)
                
                generated_path = await generate_single_mp4_with_effect(local_mp3_path, config, chat_id)
                if generated_path:
                    file_id = await upload_video_to_drive_audio(drive_service, generated_path, chat_id)
                    if file_id: drive_files_map["video"][mp4_filename] = file_id
            
            successful_videos.append({"path": local_video_path, "base_name": os.path.splitext(mp4_filename)[0]})

        if not successful_videos: raise Exception("Không tạo/tìm thấy được video nào trong GĐ 3.")
        
        video_data_for_excel = []
        for video in successful_videos:
            chap_range = f"Tập {video['base_name']}"; chap_nums = video["base_name"].split("_")
            if len(chap_nums) == 2:
                try: start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1]); chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
                except ValueError: chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
            title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
            video_data_for_excel.append({"path": video["path"], "title": title})
        await update_excel_for_youtube(video_data_for_excel)
        await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
        user_data["videos_to_upload"] = video_data_for_excel
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)

        # --- Giai đoạn 4: Upload YouTube ---
        upload_decision = user_data.get('one_click_upload_decision', False)
        if upload_decision:
            account_to_upload = user_data.get('one_click_account_number')
            await send_telegram_message(chat_id, f"`✅ GĐ 1, 2, 3`\n`➡️ GĐ 4/4: Upload lên YouTube tài khoản {account_to_upload}...`")
            
            for video_data in video_data_for_excel:
                if not os.path.exists(video_data['path']):
                    video_filename = os.path.basename(video_data['path'])
                    video_id = drive_files_map["video"].get(video_filename)
                    if video_id: await download_file_from_drive(drive_service, video_id, video_data['path'])
            
            successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_to_upload, config)
            if successfully_uploaded_videos:
                 await send_telegram_message(chat_id, f"🗑️ Dọn dẹp {len(successfully_uploaded_videos)} video đã upload thành công trên Drive...")
                 for uploaded_video in successfully_uploaded_videos:
                     filename = os.path.basename(uploaded_video['path'])
                     if filename in drive_files_map["video"]: await delete_file_from_drive(drive_service, drive_files_map["video"][filename])
        else:
            await send_telegram_message(chat_id, "🎉 **QUY TRÌNH HOÀN TẤT!**\n\nĐã tạo video thành công. Không thực hiện upload YouTube theo yêu cầu.", reply_markup=AUDIO_MENU_KEYBOARD)

    except Exception as e:
        error_traceback = traceback.format_exc()
        print(f"❌ LỖI NGHIÊM TRỌNG trong One Click:\n{error_traceback}")
        await send_telegram_message(chat_id, f"❌ **Đã xảy ra lỗi nghiêm trọng:**\n\n<pre>{e}</pre>", reply_markup=AUDIO_MENU_KEYBOARD)

    finally:
        await send_telegram_message(chat_id, "⚙️ Dọn dẹp file tạm cục bộ trên server...")
        for path in [AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, TEMP_PATH]:
            shutil.rmtree(path, ignore_errors=True)
            os.makedirs(path, exist_ok=True)
        await send_telegram_message(chat_id, "✅ Dọn dẹp cục bộ hoàn tất.")

async def run_one_click_workflow2(chat_id: int, user_data: dict):
    """

    Quy trình One Click AN TOÀN & CÓ KHẢ NĂNG PHỤC HỒI.

    - Trước khi tạo mỗi file (TXT/MP3/MP4), kiểm tra xem đã có trên Drive chưa → skip nếu có.

    - Nếu bị lỗi giữa chừng, chỉ cần xóa file lỗi cuối cùng rồi chạy lại.

    - Hệ thống sẽ tự động skip các file đã hoàn thành và tiếp tục từ file bị lỗi.

    """
    drive_service = None

    try:
        # --- KHỞI TẠO ---
        voice_choice = user_data.get("voice_choice", "female")
        config = await read_audio_config_from_excel()
        replacement_map = await _read_replacement_map_from_excel()

        drive_creds = await get_drive_credentials(chat_id)
        if not drive_creds:
            await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive. Dừng quy trình.")
            return
        drive_service = build('drive', 'v3', credentials=drive_creds)

        # ==============================================================================
        # === BƯỚC 0: QUÉT TOÀN BỘ TRẠNG THÁI FILE TRÊN DRIVE (1 LẦN DUY NHẤT) ========
        # ==============================================================================
        await send_telegram_message(chat_id, "🔎 Đang quét trạng thái file trên Google Drive...")
        drive_files_map = {
            "txt": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID)},
            "mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID)},
            "final_mp3": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID)},
            "video": {f['name']: f['id'] for f in await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)}
        }
        await send_telegram_message(chat_id,
            f"📊 **Trạng thái hiện tại trên Drive:**\n"
            f"- TXT: **{len(drive_files_map['txt'])}** file\n"
            f"- MP3 chương: **{len(drive_files_map['mp3'])}** file\n"
            f"- MP3 nối: **{len(drive_files_map['final_mp3'])}** file\n"
            f"- Video: **{len(drive_files_map['video'])}** file"
        )

        # ==============================================================================
        # === GIAI ĐOẠN 1: GET FILE (.txt) - SKIP NẾU ĐÃ CÓ TRÊN DRIVE ===============
        # ==============================================================================
        await send_telegram_message(chat_id, "🚀 **Quy trình One Click (Có phục hồi)**\n\n`➡️ Bước 1/4: Get File...`")

        # Đọc link từ Excel
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None, engine="openpyxl", usecols=[0, 1])
        all_links_data = []
        for _, row in df.loc[1:].iterrows():
            chap_num = int(row.get(0)) if pd.notna(row.get(0)) else None
            link = str(row.get(1)) if pd.notna(row.get(1)) else None
            if link and chap_num is not None:
                all_links_data.append({'link': link, 'chapter_number': chap_num})

        # Nếu không có link trong Excel VÀ cũng không có TXT trên Drive → không có gì để làm
        if not all_links_data and not drive_files_map["txt"]:
            await send_telegram_message(chat_id, "❌ Không tìm thấy link trong Excel và không có file TXT trên Drive.", reply_markup=AUDIO_MENU_KEYBOARD)
            return

        os.makedirs(AUDIO_TXT_FOLDER, exist_ok=True)
        txt_new, txt_skip, links_error = 0, 0, []

        for link_data in all_links_data:
            expected_filename = f"{str(link_data['chapter_number']).zfill(4)}.txt"
            local_filepath = os.path.join(AUDIO_TXT_FOLDER, expected_filename)

            # ✅ KIỂM TRA: File TXT đã có trên Drive chưa?
            if expected_filename in drive_files_map["txt"]:
                txt_skip += 1
                # Download về local nếu cần cho bước sau
                if not os.path.exists(local_filepath):
                    await download_file_from_drive(drive_service, drive_files_map["txt"][expected_filename], local_filepath)
                continue

            # Chưa có → cào dữ liệu và tạo file
            result = await scrape_website_chapter_content(link_data['link'], config["replacements"])
            if result:
                title, body, _ = result
                file_content = "\n\n".join(filter(None, [config.get("top"), title, body, config.get("end")]))
                final_content = _apply_replacements(file_content, replacement_map)
                with open(local_filepath, 'w', encoding='utf-8') as f:
                    f.write(final_content)
                file_id = await upload_file_to_drive_folder(drive_service, local_filepath, DRIVE_AUDIO_TXT_FOLDER_ID)
                if file_id:
                    drive_files_map["txt"][expected_filename] = file_id
                txt_new += 1
            else:
                links_error.append(link_data)

        # Cập nhật Excel: chỉ giữ lại các link lỗi
        await rewrite_excel_links(links_error)
        await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)

        if links_error:
            await send_telegram_message(chat_id, f"⚠️ Có {len(links_error)} link lỗi (đã lưu lại trong Excel).")

        await send_telegram_message(chat_id,
            f"✅ **GĐ 1 hoàn tất:** Mới: **{txt_new}** | Skip: **{txt_skip}** | Lỗi: **{len(links_error)}**")

        # ==============================================================================
        # === GIAI ĐOẠN 2: GEN MP3 - SKIP NẾU ĐÃ CÓ TRÊN DRIVE =======================
        # ==============================================================================
        await send_telegram_message(chat_id, "`➡️ Bước 2/4: Tạo MP3...`")

        os.makedirs(AUDIO_MP3_FOLDER, exist_ok=True)
        mp3_new, mp3_skip = 0, 0

        for txt_filename in sorted(drive_files_map["txt"].keys()):
            base_name = os.path.splitext(txt_filename)[0]
            mp3_filename = f"{base_name}.mp3"
            local_mp3_path = os.path.join(AUDIO_MP3_FOLDER, mp3_filename)

            # ✅ KIỂM TRA: File MP3 chương đã có trên Drive chưa?
            if mp3_filename in drive_files_map["mp3"]:
                mp3_skip += 1
                if not os.path.exists(local_mp3_path):
                    await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_filename], local_mp3_path)
                continue

            # Chưa có → tạo mới
            local_txt_path = os.path.join(AUDIO_TXT_FOLDER, txt_filename)
            if not os.path.exists(local_txt_path):
                await download_file_from_drive(drive_service, drive_files_map["txt"][txt_filename], local_txt_path)

            is_ok = await create_chapter_mp3(local_txt_path, local_mp3_path, voice_choice)
            if is_ok:
                file_id = await upload_file_to_drive_folder(drive_service, local_mp3_path, DRIVE_AUDIO_MP3_FOLDER_ID)
                if file_id:
                    drive_files_map["mp3"][mp3_filename] = file_id
                mp3_new += 1
            else:
                await send_telegram_message(chat_id,
                    f"❌ Lỗi tạo MP3 cho `{mp3_filename}`. Dừng quy trình.\n"
                    f"💡 **Để tiếp tục:** Xóa file lỗi trên Drive (nếu có) rồi chạy lại One Click.",
                    reply_markup=AUDIO_MENU_KEYBOARD)
                return

        await send_telegram_message(chat_id,
            f"✅ **MP3 chương:** Mới: **{mp3_new}** | Skip: **{mp3_skip}**")

        # --- Nối MP3 chương thành các file MP3 lớn ---
        df_audio = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
        group_size = int(df_audio.iloc[0, 3])
        all_chapter_mp3s = sorted(drive_files_map["mp3"].keys())
        file_groups = [all_chapter_mp3s[i:i+group_size] for i in range(0, len(all_chapter_mp3s), group_size)]

        os.makedirs(AUDIO_FINAL_FOLDER, exist_ok=True)
        final_new, final_skip = 0, 0

        for group in file_groups:
            if not group: continue
            final_name = f"{os.path.splitext(group[0])[0]}_{os.path.splitext(group[-1])[0]}.mp3"
            local_final_path = os.path.join(AUDIO_FINAL_FOLDER, final_name)

            # ✅ KIỂM TRA: File MP3 nối đã có trên Drive chưa?
            if final_name in drive_files_map["final_mp3"]:
                final_skip += 1
                if not os.path.exists(local_final_path):
                    await download_file_from_drive(drive_service, drive_files_map["final_mp3"][final_name], local_final_path)
                continue

            # Chưa có → nối
            local_group_paths = []
            for mp3_name in group:
                local_path = os.path.join(AUDIO_MP3_FOLDER, mp3_name)
                if not os.path.exists(local_path):
                    await download_file_from_drive(drive_service, drive_files_map["mp3"][mp3_name], local_path)
                local_group_paths.append(local_path)

            if await merge_mp3_files_ffmpeg(local_group_paths, local_final_path):
                file_id = await upload_file_to_drive_folder(drive_service, local_final_path, DRIVE_AUDIO_FINAL_FOLDER_ID)
                if file_id:
                    drive_files_map["final_mp3"][final_name] = file_id
                final_new += 1

        await send_telegram_message(chat_id,
            f"✅ **MP3 nối:** Mới: **{final_new}** | Skip: **{final_skip}**")

        # Dọn TXT trên Drive (đã xong, không cần nữa)
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_TXT_FOLDER_ID, chat_id)

        # ==============================================================================
        # === GIAI ĐOẠN 3: GEN MP4 - SKIP NẾU ĐÃ CÓ TRÊN DRIVE =======================
        # ==============================================================================
        await send_telegram_message(chat_id, "`✅ GĐ 1, 2`\n`➡️ Bước 3/4: Tạo Video (.mp4)...`")

        # Tải tài nguyên (ảnh nền, font chữ) từ Drive
        image_file_id = config.get("image_file_id")
        title_font_id = config.get("title_font_file_id")
        chap_font_id = config.get("chap_font_file_id")
        if not all([image_file_id, title_font_id, chap_font_id]):
            await send_telegram_message(chat_id, "❌ Lỗi cấu hình: Thiếu File ID cho ảnh/font trong Excel.", reply_markup=AUDIO_MENU_KEYBOARD)
            return
        config["image_path"] = os.path.join(TEMP_PATH, "background_image.jpg")
        config["title_font_path"] = os.path.join(TEMP_PATH, "title_font.ttf")
        config["chap_font_path"] = os.path.join(TEMP_PATH, "chap_font.ttf")
        await download_file_from_drive(drive_service, image_file_id, config["image_path"])
        await download_file_from_drive(drive_service, title_font_id, config["title_font_path"])
        await download_file_from_drive(drive_service, chap_font_id, config["chap_font_path"])

        successful_videos = []
        video_new, video_skip = 0, 0

        for mp3_filename in sorted(drive_files_map["final_mp3"].keys()):
            mp4_filename = f"{os.path.splitext(mp3_filename)[0]}.mp4"
            local_video_path = os.path.join(AUDIO_VIDEO_FOLDER, mp4_filename)

            # ✅ KIỂM TRA: File video đã có trên Drive chưa?
            if mp4_filename in drive_files_map["video"]:
                video_skip += 1
                if not os.path.exists(local_video_path):
                    await download_file_from_drive(drive_service, drive_files_map["video"][mp4_filename], local_video_path)
            else:
                # Chưa có → tạo mới
                local_mp3_path = os.path.join(AUDIO_FINAL_FOLDER, mp3_filename)
                if not os.path.exists(local_mp3_path):
                    await download_file_from_drive(drive_service, drive_files_map["final_mp3"][mp3_filename], local_mp3_path)

                generated_path = await generate_single_mp4_with_effect(local_mp3_path, config, chat_id)
                if generated_path:
                    file_id = await upload_video_to_drive_audio(drive_service, generated_path, chat_id)
                    if file_id:
                        drive_files_map["video"][mp4_filename] = file_id
                    video_new += 1

            successful_videos.append({"path": local_video_path, "base_name": os.path.splitext(mp4_filename)[0]})

        await send_telegram_message(chat_id,
            f"✅ **Video:** Mới: **{video_new}** | Skip: **{video_skip}**")

        if not successful_videos:
            await send_telegram_message(chat_id, "❌ Không tạo/tìm thấy được video nào.", reply_markup=AUDIO_MENU_KEYBOARD)
            return

        # Chuẩn bị dữ liệu cho Excel & YouTube
        video_data_for_excel = []
        for video in successful_videos:
            chap_range = f"Tập {video['base_name']}"
            chap_nums = video["base_name"].split("_")
            if len(chap_nums) == 2:
                try:
                    start_chap, end_chap = int(chap_nums[0]), int(chap_nums[1])
                    chap_range = f"Chương {start_chap}" if start_chap == end_chap else f"Chương {start_chap}~{end_chap}"
                except ValueError:
                    chap_range = f"Chương {chap_nums[0]}~{chap_nums[-1]}"
            title = f"{config.get('story_name')} | {chap_range} | {config.get('title_suffix')}"
            video_data_for_excel.append({"path": video["path"], "title": title})

        await update_excel_for_youtube(video_data_for_excel)
        user_data["videos_to_upload"] = video_data_for_excel

        # Dọn MP3 trên Drive (đã có video rồi, không cần nữa)
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_MP3_FOLDER_ID, chat_id)
        await delete_files_in_drive_folder(drive_service, DRIVE_AUDIO_FINAL_FOLDER_ID, chat_id)

        # ==============================================================================
        # === GIAI ĐOẠN 4: UPLOAD YOUTUBE & DỌN DẸP VIDEO TRÊN DRIVE ===================
        # ==============================================================================
        await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
        upload_decision = user_data.get('one_click_upload_decision', False)

        if upload_decision:
            account_to_upload = user_data.get('one_click_account_number')
            await send_telegram_message(chat_id, f"`✅ GĐ 1, 2, 3`\n`➡️ Bước 4/4: Upload lên YouTube tài khoản {account_to_upload}...`")

            # Đảm bảo video tồn tại trên local trước khi upload
            for video_data in video_data_for_excel:
                if not os.path.exists(video_data['path']):
                    video_filename = os.path.basename(video_data['path'])
                    video_id = drive_files_map["video"].get(video_filename)
                    if video_id:
                        await download_file_from_drive(drive_service, video_id, video_data['path'])

            successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_to_upload, config)

            if successfully_uploaded_videos:
                await send_telegram_message(chat_id, f"🗑️ Dọn dẹp {len(successfully_uploaded_videos)} video đã upload trên Drive...")
                for uploaded_video in successfully_uploaded_videos:
                    filename = os.path.basename(uploaded_video['path'])
                    if filename in drive_files_map["video"]:
                        await delete_file_from_drive(drive_service, drive_files_map["video"][filename])
        else:
            await send_telegram_message(chat_id, "🎉 **QUY TRÌNH HOÀN TẤT!**\n\nĐã tạo video thành công. Không upload YouTube theo yêu cầu.", reply_markup=AUDIO_MENU_KEYBOARD)

    except Exception as e:
        error_traceback = traceback.format_exc()
        print(f"❌ LỖI NGHIÊM TRỌNG trong One Click 2:\n{error_traceback}")
        await send_telegram_message(chat_id, f"❌ **Đã xảy ra lỗi nghiêm trọng:**\n\n`{e}`\n\n💡 **Để tiếp tục:** Xóa file lỗi (nếu có) trên Drive rồi chạy lại One Click.", reply_markup=AUDIO_MENU_KEYBOARD)

    finally:
        await send_telegram_message(chat_id, "⚙️ Dọn dẹp file tạm cục bộ...")
        for path in [AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, TEMP_PATH]:
            shutil.rmtree(path, ignore_errors=True)
            os.makedirs(path, exist_ok=True)
        await send_telegram_message(chat_id, "✅ Dọn dẹp cục bộ hoàn tất.")

async def start_recovery_upload_process(chat_id: int, user_data: dict, account_number: int):
    """

    Tải video từ Drive về, đọc Excel để lấy tiêu đề, và bắt đầu upload hàng loạt.

    """
    video_files_to_recover = user_data.get("recovery_video_files", [])
    if not video_files_to_recover:
        await send_telegram_message(chat_id, "Lỗi: Không tìm thấy danh sách video cần phục hồi.")
        return

    drive_creds = await get_drive_credentials(chat_id)
    if not drive_creds: return
    drive_service = build('drive', 'v3', credentials=drive_creds)

    try:
        # 1. Tải các video từ Drive về thư mục tạm cục bộ
        await send_telegram_message(chat_id, f"Bắt đầu tải {len(video_files_to_recover)} video từ Drive về server...")
        os.makedirs(AUDIO_VIDEO_FOLDER, exist_ok=True)
        local_video_paths = []
        for file_info in video_files_to_recover:
            local_path = os.path.join(AUDIO_VIDEO_FOLDER, file_info['name'])
            await download_file_from_drive(drive_service, file_info['id'], local_path)
            local_video_paths.append(local_path)

        # 2. Đọc file Excel để lấy tiêu đề (logic này giữ nguyên)
        await send_telegram_message(chat_id, "Đang đọc file Excel để lấy tiêu đề video...")
        df = pd.read_excel(WORKING_EXCEL_PATH, sheet_name="Audio", header=None)
        path_to_title_map = {}
        for index, row in df.iterrows():
            if index == 0: continue
            path_cell, title_cell = row.get(8), row.get(9)
            if pd.notna(path_cell) and pd.notna(title_cell):
                path_to_title_map[os.path.basename(str(path_cell))] = str(title_cell)

        # 3. Xây dựng lại danh sách và gọi hàm upload (logic này giữ nguyên)
        videos_to_upload = []
        for full_path in local_video_paths:
            filename = os.path.basename(full_path)
            title = path_to_title_map.get(filename, os.path.splitext(filename)[0])
            videos_to_upload.append({"path": full_path, "title": title})

        config = await read_audio_config_from_excel()
        user_data['videos_to_upload'] = videos_to_upload      
        
        # Tạo một bản đồ tra cứu từ tên file -> ID trên Drive
        name_to_id_map = {file_info['name']: file_info['id'] for file_info in video_files_to_recover}

        # Gọi hàm upload và nhận lại danh sách các video đã thành công
        successfully_uploaded_videos = await run_bulk_youtube_upload(chat_id, user_data, account_number, config)

        # === PHẦN THÊM MỚI: DỌN DẸP FILE TRÊN DRIVE ===
        if successfully_uploaded_videos:
            await send_telegram_message(chat_id, f"🗑️ Bắt đầu dọn dẹp {len(successfully_uploaded_videos)} file MP4 đã upload thành công trên Google Drive...")
            deleted_count = 0
            for video_info in successfully_uploaded_videos:
                filename = os.path.basename(video_info['path'])
                file_id_to_delete = name_to_id_map.get(filename)
                if file_id_to_delete:
                    # Cần một hàm delete_file_from_drive, hãy đảm bảo bạn có nó
                    if await delete_file_from_drive(drive_service, file_id_to_delete):
                        deleted_count += 1
            await send_telegram_message(chat_id, f"✅ Đã dọn dẹp xong {deleted_count} file.")
        # === KẾT THÚC PHẦN THÊM MỚI ===
        

    except Exception as e:
        print(f"Lỗi nghiêm trọng trong quá trình upload phục hồi: {e}")
        await send_telegram_message(chat_id, f"❌ Đã xảy ra lỗi nghiêm trọng: {e}")

async def delete_file_from_drive(drive_service, file_id: str) -> bool:
    """Xóa một file trên Drive bằng ID."""
    try:
        await asyncio.to_thread(drive_service.files().delete(fileId=file_id).execute)
        print(f"   -> Đã xóa file trên Drive: {file_id}")
        return True
    except Exception as e:
        print(f"❌ Lỗi khi xóa file trên Drive '{file_id}': {e}")
        return False



# ==============================================================================
# --- PHẦN KHỞI ĐỘNG VÀ XỬ LÝ WEBHOOK CỦA FASTAPI ---
# ==============================================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Hàm chạy một lần khi bot khởi động."""
    print("🚀 Bắt đầu quá trình khởi tạo bot qua lifespan...")
    global GOOGLE_TTS_API_KEY
    # 1. Tạo các thư mục làm việc cục bộ
    for path in [BASE_DATA_DIR, AUDIO_TXT_FOLDER, AUDIO_MP3_FOLDER, AUDIO_FINAL_FOLDER, AUDIO_VIDEO_FOLDER, YTB_TOKEN_SAVE_PATH, TEMP_PATH]:
        os.makedirs(path, exist_ok=True)
    print("✅ Đã tạo các thư mục làm việc cục bộ.")

    # 2. Giải mã và lưu token chính của Drive từ Secret
    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.")
        yield; return # Thoát sớm
    try:
        pickle_binary_data = base64.b64decode(base64_pickle_string)
        working_token_path = os.path.join(YTB_TOKEN_SAVE_PATH, "driver_main.pickle")
        with open(working_token_path, "wb") as f: f.write(pickle_binary_data)
        print(f"✅ Đã tạo file token chính của Drive 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}")
        yield; return
    
    # 3. Tải file Excel và đọc các cấu hình cần thiết
    try:
        ADMIN_CHAT_ID = 6685326330 # ID admin để gửi thông báo lỗi nếu cần
        credentials = await get_drive_credentials(ADMIN_CHAT_ID)
        if not credentials: raise Exception("Không thể lấy credentials của Drive.")
        
        drive_service = build('drive', 'v3', credentials=credentials)
        print("✅ Đã kết nối thành công với Google Drive API.")
        
        await download_file_from_drive(drive_service, DRIVE_EXCEL_FILE_ID, WORKING_EXCEL_PATH)

        # Đọc Google TTS API Key từ Excel (ô D2 sheet Input)
        df_input = pd.read_excel(WORKING_EXCEL_PATH, sheet_name='Input', header=None)
        key_value = df_input.iloc[1, 3]
        if pd.notna(key_value) and str(key_value).strip():
            GOOGLE_TTS_API_KEY = str(key_value).strip()
            print("✅ Đã đọc thành công Google TTS API Key.")
        else:
            print("❌ CẢNH BÁO: Google TTS API Key (ô D2, sheet 'Input') bị trống.")
    except Exception as e:
        print(f"❌ LỖI nghiêm trọng trong quá trình khởi tạo: {e}")

    print("✅ Bot đã sẵn sàng nhận yêu cầu.")
    yield
    print("🔌 Bot đang tắt...")

app = FastAPI(lifespan=lifespan)

@app.post("/webhook")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
    """Xử lý Telegram updates được Google Apps Script chuyển tiếp."""
    try:
        update_json = await request.json()
        update_id = update_json.get("update_id")
        if update_id in processed_update_ids:
            return {"status": "ok, duplicate ignored"}
        processed_update_ids.append(update_id)
    except Exception as e:
        print(f"!!! Lỗi parsing request: {e}")
        return {"status": "error"}

    chat_id, user_id, data, text = None, None, None, None
    user_data = {}

    if "callback_query" in update_json:
        query = update_json["callback_query"]
        chat_id = query["message"]["chat"]["id"]
        user_id = query["from"]["id"]
        data = query["data"]
        user_data = user_sessions.get(str(user_id), {}) # Lấy state hiện tại của user
        state = user_data.get("state")
        
        # --- LUỒNG XỬ LÝ NÚT BẤM ---
        if data == "audio_get_link":
            user_data["is_first_scrape"] = True
            user_data["state"] = AWAITING_EPISODE_COUNT_STATE
            await send_telegram_message(chat_id, "Bước 1: Bạn muốn **nối** bao nhiêu chương MP3 thành 1 file?", EPISODE_COUNT_KEYBOARD)
        
        # <<< BLOCK CODE MỚI BẮT ĐẦU: Xử lý luồng cho nút "Truy Vết"
        elif data == "audio_trace":
            user_data["state"] = AWAITING_TRACE_PAGE_COUNT_STATE
            await send_telegram_message(chat_id, "Bạn muốn **truy vết** dữ liệu từ bao nhiêu trang?", TRACE_PAGE_COUNT_KEYBOARD)

        elif state == AWAITING_TRACE_PAGE_COUNT_STATE and data.startswith("trace_page_count_"):
            user_data["pages_to_trace"] = int(data.replace("trace_page_count_", ""))
            user_data["state"] = AWAITING_TRACE_URL_STATE
            await send_telegram_message(chat_id, f"Ok, sẽ truy vết từ {user_data['pages_to_trace']} trang.\n\nVui lòng gửi đường dẫn trang truyện (trang đầu tiên):")
        # <<< BLOCK CODE MỚI KẾT THÚC
        
        
        elif state == AWAITING_EPISODE_COUNT_STATE and data.startswith("ep_count_"):
            user_data["merge_count"] = int(data.replace("ep_count_", ""))
            user_data["state"] = AWAITING_PAGE_COUNT_STATE
            await send_telegram_message(chat_id, f"Đã lưu số lượng nối file là {user_data['merge_count']}.\n\nBước 2: Bạn muốn **lấy dữ liệu** từ bao nhiêu trang?", PAGE_COUNT_KEYBOARD)

        elif state == AWAITING_PAGE_COUNT_STATE and data.startswith("page_count_"):
            user_data["pages_to_scrape"] = int(data.replace("page_count_", ""))
            user_data["state"] = AWAITING_URL_FOR_SCRAPING_STATE
            await send_telegram_message(chat_id, f"Ok, sẽ lấy dữ liệu từ {user_data['pages_to_scrape']} trang.\n\nBước 3: Vui lòng gửi đường dẫn trang truyện (trang đầu tiên):")

        elif data == "audio_get_file":
            background_tasks.add_task(process_and_generate_text_files, chat_id)
            await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Get File'. Quy trình đang chạy trong nền...")

        # <<< CHỈNH SỬA: Thêm bước hỏi giọng đọc cho Gen MP3
        elif data == "audio_gen_mp3":
            user_data["state"] = AWAITING_GEN_MP3_VOICE_CHOICE_STATE
            await send_telegram_message(chat_id, "Bạn muốn dùng giọng đọc nào?", reply_markup=VOICE_CHOICE_KEYBOARD_GEN_MP3)

        # <<< MỚI: Xử lý lựa chọn giọng đọc cho Gen MP3
        elif state == AWAITING_GEN_MP3_VOICE_CHOICE_STATE:
            if data == "gen_mp3_voice_male":
                user_data["voice_choice"] = "male"
            elif data == "gen_mp3_voice_ngochuyen":
                user_data["voice_choice"] = "ngochuyen"
            else:
                user_data["voice_choice"] = "female"
            user_data["state"] = AUDIO_MENU_STATE # Reset state
            background_tasks.add_task(run_full_mp3_generation_process, chat_id, user_data)
            await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Gen MP3'. Quy trình đang chạy trong nền...")

        elif data == "audio_gen_mp4":
            background_tasks.add_task(process_and_generate_mp4_files, chat_id, user_data)
            await send_telegram_message(chat_id, "Đã nhận yêu cầu 'Gen MP4'. Quy trình đang chạy trong nền...")
            
        elif data == "audio_one_click":
            user_data["state"] = AWAITING_ONE_CLICK_VOICE_CHOICE_STATE
            await send_telegram_message(chat_id, "Bạn muốn dùng giọng đọc nào cho quy trình One Click?", reply_markup=VOICE_CHOICE_KEYBOARD_ONE_CLICK)

        # <<< MỚI: Xử lý lựa chọn giọng đọc cho One Click và chuyển sang bước tiếp theo
        elif state == AWAITING_ONE_CLICK_VOICE_CHOICE_STATE:
            if data == "one_click_voice_male":
                user_data["voice_choice"] = "male"
            elif data == "one_click_voice_ngochuyen":
                user_data["voice_choice"] = "ngochuyen"
            else:
                user_data["voice_choice"] = "female"
            user_data["state"] = AWAITING_ONE_CLICK_YT_CONFIRM_STATE
            await send_telegram_message(chat_id, "Tiếp theo, sau khi quy trình hoàn tất, bạn có muốn tự động upload video lên YouTube không?", ONE_CLICK_YT_CONFIRM_KEYBOARD)

        elif state == AWAITING_ONE_CLICK_YT_CONFIRM_STATE:
            if data == "one_click_yt_yes":
                user_data['one_click_upload_decision'] = True
                user_data["state"] = AWAITING_ONE_CLICK_YT_ACCOUNT_STATE
                await send_telegram_message(chat_id, "Vui lòng chọn tài khoản YouTube sẽ dùng để upload:", ONE_CLICK_YT_ACCOUNT_KEYBOARD)
            else: # one_click_yt_no
                user_data['one_click_upload_decision'] = False
                await send_telegram_message(chat_id, "Đã hiểu. Bắt đầu quy trình tạo video mà không upload...")
                background_tasks.add_task(run_one_click_workflow, chat_id, user_data)
        elif state == AWAITING_ONE_CLICK_YT_ACCOUNT_STATE and data.startswith("one_click_account_"):
            account_num = int(data.replace("one_click_account_", ""))
            user_data['one_click_account_number'] = account_num
            # Đặt lại trạng thái NGAY LẬP TỨC để tránh bị gọi lại
            user_data["state"] = AUDIO_MENU_STATE 
            await send_telegram_message(chat_id, f"Ok. Sẽ tự động upload lên tài khoản {account_num} sau khi xong. Bắt đầu quy trình...")
            background_tasks.add_task(run_one_click_workflow, chat_id, user_data)
            
        elif state == AWAITING_ADD_MORE_URL_CONFIRMATION_STATE:
            if data == "add_more_yes":
                user_data["state"] = AWAITING_URL_FOR_SCRAPING_STATE
                await send_telegram_message(chat_id, "Ok, vui lòng gửi đường dẫn trang truyện tiếp theo:")
            else:
                user_data["state"] = AUDIO_MENU_STATE
                await send_telegram_message(chat_id, "✅ Đã lấy link xong. Trở về menu Audio.", AUDIO_MENU_KEYBOARD)
        
        elif state == AWAITING_YOUTUBE_UPLOAD_CONFIRM_STATE:
            if data == "yt_upload_yes":
                user_data["state"] = AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE
                await send_telegram_message(chat_id, "Vui lòng chọn tài khoản YouTube để upload:", YOUTUBE_ACCOUNT_KEYBOARD_AUDIO)
            else:
                user_data["state"] = AUDIO_MENU_STATE
                await send_telegram_message(chat_id, "Đã hiểu. Trở về menu Audio.", AUDIO_MENU_KEYBOARD)
       
        elif state == AWAITING_YOUTUBE_ACCOUNT_CHOICE_STATE and data.startswith("yt_account_"):
            account_num = int(data.replace("yt_account_", ""))
            config = user_data.get("config") # Lấy config đã lưu
            
            # Kiểm tra xem config có tồn tại không
            if not config:
                await send_telegram_message(chat_id, "Lỗi: Mất phiên làm việc. Vui lòng thử lại từ bước Gen MP4.")
            else:
                user_data["state"] = AUDIO_MENU_STATE # Reset state sau khi đã nhận lệnh
                await send_telegram_message(chat_id, f"Đã chọn tài khoản {account_num}. Bắt đầu upload hàng loạt...")
                background_tasks.add_task(run_bulk_youtube_upload, chat_id, user_data, account_num, config)
        
        elif data == "audio_recovery_upload":
            await send_telegram_message(chat_id, "🔎 Đang kiểm tra video trên Google Drive...")
            drive_creds = await get_drive_credentials(chat_id)
            if not drive_creds:
                await send_telegram_message(chat_id, "❌ Lỗi: Không thể xác thực với Google Drive.")
                return

            drive_service = build('drive', 'v3', credentials=drive_creds)
            # Lấy danh sách video từ thư mục output trên Drive
            video_files_on_drive = await list_files_in_drive_folder(drive_service, DRIVE_AUDIO_VIDEO_FOLDER_ID)

            if not video_files_on_drive:
                await send_telegram_message(chat_id, "✅ Không có video nào trên Google Drive cần upload.")
                user_data["state"] = AUDIO_MENU_STATE
            else:
                # Lưu lại danh sách file tìm thấy để dùng ở bước sau
                user_data["recovery_video_files"] = video_files_on_drive
                await send_telegram_message(chat_id, f"🔍 Tìm thấy {len(video_files_on_drive)} video. Bạn muốn upload lên tài khoản YouTube nào?", reply_markup=RECOVERY_YT_ACCOUNT_KEYBOARD)
                user_data["state"] = AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE

        elif state == AWAITING_RECOVERY_YT_ACCOUNT_CHOICE_STATE and data.startswith("recovery_yt_acc_"):
            # Khi người dùng chọn một tài khoản để upload phục hồi
            account_num = int(data.replace("recovery_yt_acc_", ""))
            user_data["state"] = AUDIO_MENU_STATE # Reset state

            await send_telegram_message(chat_id, f"✅ Đã nhận lệnh. Bắt đầu quá trình upload phục hồi cho tài khoản {account_num}...")
            background_tasks.add_task(start_recovery_upload_process, chat_id, user_data, account_num)
        # === BLOCK CODE MỚI KẾT THÚC ===
        
        
        
        # Lưu lại trạng thái của người dùng sau mỗi lần tương tác
        if user_id:
            user_data = user_sessions.get(str(user_id), {})

    elif "message" in update_json:
        message = update_json["message"]
        chat_id = message["chat"]["id"]
        user_id = message["from"]["id"]
        text = message.get("text", "").strip()
        user_data = user_sessions.get(str(user_id), {})
        state = user_data.get("state")
        
        if text == "/audio": # Lệnh để mở menu audio
            user_data["state"] = AUDIO_MENU_STATE
            await send_telegram_message(chat_id, "🎧 Chức năng Gen Audio. Vui lòng chọn:", AUDIO_MENU_KEYBOARD)
        
        elif state == AWAITING_URL_FOR_SCRAPING_STATE:
            if "http" not in text.lower(): # <<< THAY ĐỔI
      
                await send_telegram_message(chat_id, "❌ URL không hợp lệ. Vui lòng gửi lại:")
            else:
                pages_to_scrape = user_data.get("pages_to_scrape", 1)
                merge_count = user_data.get("merge_count", 20)
                is_first = user_data.get("is_first_scrape", True)
                await send_telegram_message(chat_id, f"🔎 Đang lấy dữ liệu từ {pages_to_scrape} trang...")         
                result_dict = await scrape_website_chapter_list(text, pages_to_scrape) # <<< THAY ĐỔI        
                if 'error' in result_dict:
                    await send_telegram_message(chat_id, f"❌ Không lấy được dữ liệu. Lý do: {result_dict.get('error')}")
                else:
                    data = result_dict.get('data', [])
                    if not data:
                        await send_telegram_message(chat_id, "Không lấy được chương nào từ URL bạn gửi.")
                    elif await update_audio_sheet(data, is_first):
                        # Cập nhật số lượng nối file vào D1
                        def update_merge_count(book):
                            ws = book["Audio"]
                            ws.cell(row=1, column=4, value=str(merge_count))
                        await modify_excel_sheet(update_merge_count)
                        
                        # Upload lại file Excel lên Drive
                        drive_creds = await get_drive_credentials(chat_id)
                        if drive_creds:
                            drive_service = build('drive', 'v3', credentials=drive_creds)
                            await upload_file_to_drive(drive_service, WORKING_EXCEL_PATH, DRIVE_EXCEL_FILE_ID)
                        
                        user_data["is_first_scrape"] = False
                        user_data["state"] = AWAITING_ADD_MORE_URL_CONFIRMATION_STATE
                        await send_telegram_message(chat_id, f"✅ Đã lấy và cập nhật thành công {len(data)} chương. Bạn có muốn thêm link từ truyện khác không?", ADD_MORE_KEYBOARD)
                    else:
                        user_data["state"] = AUDIO_MENU_STATE
                        await send_telegram_message(chat_id, "Lỗi khi cập nhật file Excel.", AUDIO_MENU_KEYBOARD)
                        
                        
        elif state == AWAITING_TRACE_URL_STATE:
            if "http" not in text.lower():
                await send_telegram_message(chat_id, "❌ URL không hợp lệ. Vui lòng gửi lại:")
            else:
                pages_to_trace = user_data.get("pages_to_trace", 1)
                # Reset trạng thái ngay lập tức để tránh xử lý lại
                user_data["state"] = AUDIO_MENU_STATE
                # Chạy tác vụ nền để không block bot
                background_tasks.add_task(run_trace_workflow, chat_id, text, pages_to_trace)
                await send_telegram_message(chat_id, "✅ Đã nhận yêu cầu. Bắt đầu chạy quy trình Truy Vết trong nền...")
        # <<< BLOCK CODE MỚI KẾT THÚC
                
        else:
            await send_telegram_message(chat_id, "Lệnh không hợp lệ. Vui lòng dùng lệnh /audio để bắt đầu hoặc sử dụng các nút bấm.")

        # Lưu lại trạng thái của người dùng
    if user_id:
        user_sessions[str(user_id)] = user_data
    return {"status": "ok"}


@app.get("/")
def read_root():
    return {"message": "Audio Bot handler is running."}