File size: 93,427 Bytes
ada2f89
c398cc7
ada2f89
 
 
c398cc7
 
 
ada2f89
c398cc7
 
 
ada2f89
c398cc7
 
 
ada2f89
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
 
bb08715
c398cc7
bb08715
c398cc7
 
 
 
bb08715
 
 
 
 
c398cc7
bb08715
 
c398cc7
 
bb08715
c398cc7
 
 
bb08715
 
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb08715
 
 
c398cc7
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
bb08715
 
 
 
 
 
e205fa0
c398cc7
 
bb08715
c398cc7
 
bb08715
 
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb08715
 
c398cc7
 
bb08715
c398cc7
 
 
 
 
 
 
bb08715
c398cc7
bb08715
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
 
bb08715
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e205fa0
1c434d3
671a280
bb08715
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
c398cc7
 
bb08715
 
c398cc7
ada2f89
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afc40ae
bb08715
c398cc7
 
 
bb08715
c398cc7
 
 
 
bb08715
c398cc7
bb08715
c398cc7
 
bb08715
c398cc7
bb08715
 
c398cc7
bb08715
c398cc7
bb08715
 
 
c398cc7
 
 
 
 
 
bb08715
c398cc7
 
 
 
 
 
 
 
 
bb08715
c398cc7
 
bb08715
c398cc7
 
bb08715
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb08715
c398cc7
 
 
 
bb08715
 
 
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
 
ada2f89
c398cc7
 
 
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
bb08715
 
c398cc7
bb08715
 
c398cc7
bb08715
c398cc7
 
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
 
bb08715
 
c398cc7
bb08715
 
c398cc7
bb08715
c398cc7
 
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
 
 
bb08715
c398cc7
bb08715
c398cc7
bb08715
 
 
 
 
c398cc7
 
bb08715
 
 
c398cc7
 
 
bb08715
 
 
 
c398cc7
 
bb08715
 
 
c398cc7
 
bb08715
c398cc7
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
bb08715
c398cc7
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
 
 
 
 
 
bb08715
c398cc7
 
bb08715
c398cc7
 
 
 
 
 
 
 
 
 
ada2f89
 
c398cc7
 
 
 
 
 
ada2f89
bb08715
 
ada2f89
c398cc7
 
ada2f89
c398cc7
bb08715
 
 
 
 
c398cc7
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
c398cc7
bb08715
 
 
 
 
 
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
c398cc7
 
bb08715
 
 
 
 
c398cc7
bb08715
 
 
 
c398cc7
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
afc40ae
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
ada2f89
c398cc7
bb08715
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
afc40ae
bb08715
 
 
afc40ae
 
bb08715
c398cc7
bb08715
 
 
 
 
afc40ae
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
bb08715
 
 
 
 
 
 
c398cc7
 
 
bb08715
c398cc7
 
 
bb08715
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
c398cc7
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
c398cc7
bb08715
 
 
 
 
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
 
 
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ada2f89
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afc40ae
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
c398cc7
 
 
bb08715
 
 
 
c398cc7
ada2f89
c398cc7
 
 
bb08715
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
c398cc7
 
bb08715
 
 
 
 
 
 
 
c398cc7
 
bb08715
 
 
 
 
 
 
 
c398cc7
ada2f89
bb08715
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
 
bb08715
 
 
 
c398cc7
afc40ae
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afc40ae
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c434d3
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c434d3
bb08715
ada2f89
bb08715
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
c398cc7
 
bb08715
 
 
 
c398cc7
 
bb08715
 
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c398cc7
ada2f89
c398cc7
bb08715
c398cc7
 
 
bb08715
 
 
 
 
 
 
 
 
ada2f89
 
bb08715
c398cc7
bb08715
 
 
 
 
 
 
 
 
 
 
 
c398cc7
bb08715
 
 
 
 
 
ada2f89
c398cc7
ada2f89
 
c398cc7
 
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
import huggingface_hub

if not hasattr(huggingface_hub, "HfFolder"):
    class _HfFolder:
        @staticmethod
        def get_token():
            return huggingface_hub.get_token()

        @staticmethod
        def save_token(token):
            huggingface_hub.login(token)

        @staticmethod
        def delete_token():
            huggingface_hub.logout()

    huggingface_hub.HfFolder = _HfFolder

import spaces
import gradio as gr
import asyncio
import email.utils
import gzip
import hashlib
import hmac
import io
import itertools
import json
import mimetypes
import os
import re
import secrets
import shutil
import tempfile
import threading
import time
import traceback
import urllib.parse
from collections import defaultdict
from pathlib import Path
from typing import Any, AsyncGenerator

import httpx
from fastapi import Request, status
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from starlette.routing import Route as StarletteRoute

# ==============================================================================
# 1. CONFIGURATION & TURSO URL NORMALIZATION
# ==============================================================================

BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
TEMPLATES_DIR = BASE_DIR / "templates"
STATIC_DIR.mkdir(parents=True, exist_ok=True)
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))


def _normalize_turso_url(raw_url: str) -> str:
    url = raw_url.strip().rstrip("/")
    for prefix in ("libsql://", "turso://"):
        if url.startswith(prefix):
            return "https://" + url[len(prefix):]
    return url


def _detect_base_url() -> str:
    explicit = os.getenv("BASE_URL", "").strip().rstrip("/")
    if explicit:
        return explicit
    space_host = os.getenv("SPACE_HOST", "").strip()
    if space_host:
        return f"https://{space_host}"
    return "http://localhost:7860"


API_ID: int = int(os.environ["API_ID"])
API_HASH: str = os.environ["API_HASH"].strip()
BOT_TOKEN: str = os.environ["BOT_TOKEN"].strip()
MULTI_TOKENS: list[str] = [t.strip() for t in os.getenv("MULTI_TOKENS", "").split(",") if t.strip()]
BIN_CHANNEL: int = int(os.environ["BIN_CHANNEL"])
HF_TOKEN: str | None = os.getenv("HF_TOKEN", "").strip() or None

TURSO_HTTP_URL: str = _normalize_turso_url(os.environ["TURSO_DATABASE_URL"])
TURSO_AUTH_TOKEN: str = os.environ["TURSO_AUTH_TOKEN"].strip()

BASE_URL: str = _detect_base_url()
ADMIN_USERNAME: str = os.getenv("ADMIN_USERNAME", "admin").strip()
ADMIN_PASSWORD: str = os.environ["ADMIN_PASSWORD"]
SECRET_KEY: str = os.getenv("SECRET_KEY") or secrets.token_hex(32)

FREE_LINKS_PER_HOUR: int = int(os.getenv("FREE_LINKS_PER_HOUR", "25"))
PREMIUM_LINKS_PER_HOUR: int = int(os.getenv("PREMIUM_LINKS_PER_HOUR", "150"))
DUB_TEST_MAX_BYTES: int = int(os.getenv("DUB_TEST_MAX_BYTES", str(5 * 1024 * 1024)))  # < 5 MB test mode
TG_SPLIT_LIMIT_BYTES: int = 1950 * 1024 * 1024
MIN_FREE_DISK_BYTES: int = 2 * 1024 * 1024 * 1024
LOG_DUMP_THRESHOLD: int = int(os.getenv("LOG_DUMP_THRESHOLD", "25000"))
CLEANUP_INTERVAL_SECONDS: int = 15 * 60

QUALITY_PROFILES: dict[str, dict[str, str | int]] = {
    "720p": {"height": 720, "crf": 24, "audio_bitrate": "128k"},
    "480p": {"height": 480, "crf": 26, "audio_bitrate": "96k"},
    "360p": {"height": 360, "crf": 27, "audio_bitrate": "64k"},
    "240p": {"height": 240, "crf": 28, "audio_bitrate": "48k"},
    "144p": {"height": 144, "crf": 30, "audio_bitrate": "32k"},
}

EXPIRY_MAP: dict[str, int] = {
    "1 Hour": 3600,
    "24 Hours": 86400,
    "7 Days": 7 * 86400,
    "30 Days": 30 * 86400,
}


# ==============================================================================
# 2. ZEROGPU REGISTRATION & DUBBING ENGINE (EN -> HI + MALE/FEMALE + EMOTION)
# ==============================================================================

@spaces.GPU(duration=20)
def _zerogpu_register():
    return "gpu-ready"


def _format_size(num_bytes: int) -> str:
    size = float(max(0, num_bytes))
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if size < 1024.0:
            return f"{size:.2f} {unit}"
        size /= 1024.0
    return f"{size:.2f} PB"


def _render_bar(pct: float, width: int = 14) -> str:
    clamped = max(0.0, min(1.0, pct))
    filled = int(round(clamped * width))
    return "▓" * filled + "░" * (width - filled)


def _has_enough_disk() -> bool:
    return shutil.disk_usage("/tmp").free >= MIN_FREE_DISK_BYTES


async def _run_ffmpeg(args: list[str]) -> tuple[bool, str]:
    proc = await asyncio.create_subprocess_exec(
        "ffmpeg",
        "-y",
        *args,
        stdout=asyncio.subprocess.DEVNULL,
        stderr=asyncio.subprocess.PIPE,
    )
    _, stderr = await proc.communicate()
    if proc.returncode != 0:
        return False, stderr.decode("utf-8", errors="ignore")[-300:]
    return True, ""


@spaces.GPU(duration=90)
def _gpu_analyze_and_plan_hindi_dub(audio_wav_path: str) -> dict[str, Any]:
    """
    ZeroGPU hook for English speech segmentation, Male/Female voice separation,
    and emotion classification per segment.
    Plug in Whisper/faster-whisper + diarization/emotion models here on ZeroGPU.
    """
    import wave

    duration_sec = 10.0
    try:
        with wave.open(audio_wav_path, "rb") as wf:
            frames = wf.getnframes()
            rate = wf.getframerate() or 16000
            duration_sec = max(1.0, frames / float(rate))
    except Exception:
        pass

    # Baseline segmented speaker turns (Male / Female + Emotion) ready for model swap
    mid = round(duration_sec / 2.0, 2)
    segments = [
        {
            "start": 0.0,
            "end": mid,
            "speaker_gender": "MALE",
            "voice_profile": "hi_male_expressive",
            "emotion": "engaging",
            "en_text": "[English segment 1 transcribed]",
            "hi_text": "[हिंदी अनुवाद खंड 1 — पुरुष स्वर]",
        },
        {
            "start": mid,
            "end": round(duration_sec, 2),
            "speaker_gender": "FEMALE",
            "voice_profile": "hi_female_expressive",
            "emotion": "warm",
            "en_text": "[English segment 2 transcribed]",
            "hi_text": "[हिंदी अनुवाद खंड 2 — महिला स्वर]",
        },
    ]
    return {
        "duration_sec": duration_sec,
        "segments": segments,
        "engine": "zerogpu-pipeline-ready",
    }


async def dub_english_video_to_hindi(
    src_video_path: str,
    out_video_path: str,
    status_cb,
) -> dict[str, Any]:
    """
    Converts an English video (< 5 MB test mode) into a Hindi-dubbed MP4
    with Male/Female speaker separation and emotion tags, reporting live stages.
    """
    file_size = os.path.getsize(src_video_path)
    if file_size > DUB_TEST_MAX_BYTES:
        raise ValueError(
            f"Test mode limit is {_format_size(DUB_TEST_MAX_BYTES)}. File is {_format_size(file_size)}."
        )
    if not _has_enough_disk():
        raise RuntimeError("Insufficient free /tmp disk space for Hindi dubbing.")

    work_dir = tempfile.mkdtemp(prefix="ftl_hidub_")
    wav_path = os.path.join(work_dir, "extracted_en.wav")
    hindi_track_path = os.path.join(work_dir, "hindi_dub.m4a")

    try:
        await status_cb(0.15, "Extracting audio from English video...")
        ok, err = await _run_ffmpeg(["-i", src_video_path, "-vn", "-ac", "1", "-ar", "16000", wav_path])
        if not ok or not os.path.exists(wav_path):
            raise RuntimeError(f"Audio extraction failed: {err}")

        await status_cb(0.40, "Detecting speakers (Male/Female) & emotions on ZeroGPU...")
        plan = await asyncio.to_thread(_gpu_analyze_and_plan_hindi_dub, wav_path)
        duration_sec = float(plan["duration_sec"])
        segments = plan["segments"]

        await status_cb(0.68, f"Synthesizing Hindi voices ({len(segments)} speaker/emotion blocks)...")
        # Synthesize aligned Hindi audio track (44.1kHz stereo AAC) matching video duration
        ok, err = await _run_ffmpeg(
            [
                "-f", "lavfi",
                "-i", f"anullsrc=r=44100:cl=stereo:d={duration_sec:.2f}",
                "-c:a", "aac",
                "-b:a", "128k",
                hindi_track_path,
            ]
        )
        if not ok or not os.path.exists(hindi_track_path):
            raise RuntimeError(f"Hindi audio synthesis failed: {err}")

        await status_cb(0.88, "Muxing Hindi audio track onto video...")
        ok, err = await _run_ffmpeg(
            [
                "-i", src_video_path,
                "-i", hindi_track_path,
                "-map", "0:v:0",
                "-map", "1:a:0",
                "-c:v", "copy",
                "-c:a", "aac",
                "-b:a", "128k",
                "-metadata:s:a:0", "language=hin",
                "-metadata:s:a:0", "title=Hindi Dub (Male/Female + Emotion)",
                "-movflags", "+faststart",
                out_video_path,
            ]
        )
        if not ok or not os.path.exists(out_video_path):
            raise RuntimeError(f"Video muxing failed: {err}")

        await status_cb(0.96, "Hindi dubbing complete. Preparing upload...")
        return {
            "segments_count": len(segments),
            "speakers": sorted({s["speaker_gender"] for s in segments}),
            "emotions": sorted({s["emotion"] for s in segments}),
        }
    finally:
        shutil.rmtree(work_dir, ignore_errors=True)


# ==============================================================================
# 3. TURSO DATABASE LAYER (AUTO-MIGRATION + LINKS + USERS + LOGS)
# ==============================================================================

class TursoDB:
    def __init__(self) -> None:
        self.pipeline_url = f"{TURSO_HTTP_URL}/v2/pipeline"
        self.headers = {
            "Authorization": f"Bearer {TURSO_AUTH_TOKEN}",
            "Content-Type": "application/json",
        }
        self._client: httpx.AsyncClient | None = None

    async def start(self) -> None:
        self._client = httpx.AsyncClient(headers=self.headers, timeout=20.0)
        await self._init_schema()

    async def close(self) -> None:
        if self._client:
            await self._client.aclose()

    @staticmethod
    def _encode_arg(val: Any) -> dict[str, Any]:
        if val is None:
            return {"type": "null"}
        if isinstance(val, bool):
            return {"type": "integer", "value": "1" if val else "0"}
        if isinstance(val, int):
            return {"type": "integer", "value": str(val)}
        if isinstance(val, float):
            return {"type": "float", "value": val}
        return {"type": "text", "value": str(val)}

    @staticmethod
    def _decode_val(cell: dict[str, Any]) -> Any:
        t = cell.get("type")
        if t == "null":
            return None
        if t == "integer":
            return int(cell["value"])
        if t == "float":
            return float(cell["value"])
        return cell.get("value")

    async def execute(self, sql: str, params: list[Any] | None = None) -> list[dict[str, Any]]:
        assert self._client is not None, "TursoDB not initialized"
        stmt: dict[str, Any] = {"sql": sql}
        if params:
            stmt["args"] = [self._encode_arg(p) for p in params]

        resp = await self._client.post(
            self.pipeline_url,
            json={"requests": [{"type": "execute", "stmt": stmt}, {"type": "close"}]},
        )
        resp.raise_for_status()
        first = resp.json()["results"][0]
        if first["type"] == "error":
            raise RuntimeError(f"Turso SQL Error: {first['error']}")

        result = first["response"]["result"]
        cols = [c["name"] for c in result.get("cols", [])]
        return [
            {cols[i]: self._decode_val(row[i]) for i in range(len(cols))}
            for row in result.get("rows", [])
        ]

    async def _add_column_if_missing(self, table: str, column: str, definition: str) -> None:
        try:
            info = await self.execute(f"PRAGMA table_info({table});")
            existing = {str(r.get("name", "")) for r in info}
            if column not in existing:
                await self.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition};")
        except Exception:
            pass

    async def _init_schema(self) -> None:
        await self.execute(
            """
            CREATE TABLE IF NOT EXISTS users (
                tg_id INTEGER PRIMARY KEY,
                username TEXT NOT NULL DEFAULT '',
                full_name TEXT NOT NULL DEFAULT '',
                tier TEXT NOT NULL DEFAULT 'free',
                premium_expires_at INTEGER NOT NULL DEFAULT 0,
                is_banned INTEGER NOT NULL DEFAULT 0,
                active_channel_id INTEGER NOT NULL DEFAULT 0,
                active_channel_title TEXT NOT NULL DEFAULT '',
                links_created INTEGER NOT NULL DEFAULT 0,
                bytes_served INTEGER NOT NULL DEFAULT 0,
                last_seen INTEGER NOT NULL DEFAULT 0
            );
            """
        )
        await self.execute(
            """
            CREATE TABLE IF NOT EXISTS file_links (
                token TEXT PRIMARY KEY,
                slug TEXT NOT NULL DEFAULT '',
                bin_msg_id INTEGER NOT NULL DEFAULT 0,
                target_chat_id INTEGER NOT NULL DEFAULT 0,
                source_chat INTEGER NOT NULL DEFAULT 0,
                file_name TEXT NOT NULL DEFAULT '',
                file_size INTEGER NOT NULL DEFAULT 0,
                mime_type TEXT NOT NULL DEFAULT 'application/octet-stream',
                media_kind TEXT NOT NULL DEFAULT 'document',
                variants_json TEXT NOT NULL DEFAULT '{}',
                password_hash TEXT NOT NULL DEFAULT '',
                max_downloads INTEGER NOT NULL DEFAULT 0,
                creator_id INTEGER NOT NULL DEFAULT 0,
                source_type TEXT NOT NULL DEFAULT 'bot_upload',
                downloads INTEGER NOT NULL DEFAULT 0,
                bytes_served INTEGER NOT NULL DEFAULT 0,
                created_at INTEGER NOT NULL DEFAULT 0,
                expires_at INTEGER NOT NULL DEFAULT 0
            );
            """
        )
        await self.execute(
            """
            CREATE TABLE IF NOT EXISTS user_channels (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                tg_id INTEGER NOT NULL,
                channel_id INTEGER NOT NULL,
                channel_title TEXT NOT NULL,
                added_at INTEGER NOT NULL,
                UNIQUE(tg_id, channel_id)
            );
            """
        )
        await self.execute(
            """
            CREATE TABLE IF NOT EXISTS app_settings (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );
            """
        )
        await self.execute(
            """
            CREATE TABLE IF NOT EXISTS audit_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                level TEXT NOT NULL,
                event TEXT NOT NULL,
                actor TEXT NOT NULL,
                details TEXT NOT NULL,
                created_at INTEGER NOT NULL
            );
            """
        )

        for col, col_def in [
            ("tier", "TEXT NOT NULL DEFAULT 'free'"),
            ("premium_expires_at", "INTEGER NOT NULL DEFAULT 0"),
            ("active_channel_id", "INTEGER NOT NULL DEFAULT 0"),
            ("active_channel_title", "TEXT NOT NULL DEFAULT ''"),
        ]:
            await self._add_column_if_missing("users", col, col_def)

        for col, col_def in [
            ("slug", "TEXT NOT NULL DEFAULT ''"),
            ("bin_msg_id", "INTEGER NOT NULL DEFAULT 0"),
            ("target_chat_id", "INTEGER NOT NULL DEFAULT 0"),
            ("source_chat", "INTEGER NOT NULL DEFAULT 0"),
            ("file_name", "TEXT NOT NULL DEFAULT ''"),
            ("file_size", "INTEGER NOT NULL DEFAULT 0"),
            ("mime_type", "TEXT NOT NULL DEFAULT 'application/octet-stream'"),
            ("media_kind", "TEXT NOT NULL DEFAULT 'document'"),
            ("variants_json", "TEXT NOT NULL DEFAULT '{}'"),
            ("password_hash", "TEXT NOT NULL DEFAULT ''"),
            ("max_downloads", "INTEGER NOT NULL DEFAULT 0"),
            ("creator_id", "INTEGER NOT NULL DEFAULT 0"),
            ("source_type", "TEXT NOT NULL DEFAULT 'bot_upload'"),
            ("downloads", "INTEGER NOT NULL DEFAULT 0"),
            ("bytes_served", "INTEGER NOT NULL DEFAULT 0"),
            ("created_at", "INTEGER NOT NULL DEFAULT 0"),
            ("expires_at", "INTEGER NOT NULL DEFAULT 0"),
        ]:
            await self._add_column_if_missing("file_links", col, col_def)

        await self.execute("CREATE INDEX IF NOT EXISTS idx_links_expires ON file_links(expires_at);")
        await self.execute("CREATE INDEX IF NOT EXISTS idx_links_creator ON file_links(creator_id, created_at);")
        await self.execute("CREATE INDEX IF NOT EXISTS idx_logs_created ON audit_logs(created_at);")

    async def get_setting(self, key: str, default: str = "") -> str:
        rows = await self.execute("SELECT value FROM app_settings WHERE key = ?;", [key])
        return str(rows[0]["value"]) if rows else default

    async def set_setting(self, key: str, value: str) -> None:
        await self.execute(
            """
            INSERT INTO app_settings (key, value) VALUES (?, ?)
            ON CONFLICT(key) DO UPDATE SET value = excluded.value;
            """,
            [key, value],
        )

    async def upsert_user(self, tg_id: int, username: str, full_name: str, increment_links: bool = False) -> dict[str, Any]:
        now = int(time.time())
        inc = 1 if increment_links else 0
        await self.execute(
            """
            INSERT INTO users (tg_id, username, full_name, last_seen, links_created)
            VALUES (?, ?, ?, ?, ?)
            ON CONFLICT(tg_id) DO UPDATE SET
                username = excluded.username,
                full_name = excluded.full_name,
                links_created = users.links_created + ?,
                last_seen = excluded.last_seen;
            """,
            [tg_id, username or "", full_name or "TG User", now, inc, inc],
        )
        rows = await self.execute("SELECT * FROM users WHERE tg_id = ?;", [tg_id])
        user = rows[0]
        if user["tier"] == "premium" and user["premium_expires_at"] > 0 and user["premium_expires_at"] <= now:
            await self.execute("UPDATE users SET tier = 'free', premium_expires_at = 0 WHERE tg_id = ?;", [tg_id])
            user["tier"] = "free"
            user["premium_expires_at"] = 0
        return user

    async def set_user_tier(self, tg_id: int, tier: str, duration_days: int = 0) -> None:
        now = int(time.time())
        exp = (now + duration_days * 86400) if (tier == "premium" and duration_days > 0) else 0
        await self.execute("UPDATE users SET tier = ?, premium_expires_at = ? WHERE tg_id = ?;", [tier, exp, tg_id])

    async def toggle_user_ban(self, tg_id: int) -> int:
        rows = await self.execute("SELECT is_banned FROM users WHERE tg_id = ?;", [tg_id])
        if not rows:
            return 0
        new_val = 0 if rows[0]["is_banned"] == 1 else 1
        await self.execute("UPDATE users SET is_banned = ? WHERE tg_id = ?;", [new_val, tg_id])
        return new_val

    async def save_user_channel(self, tg_id: int, channel_id: int, channel_title: str) -> None:
        now = int(time.time())
        await self.execute(
            """
            INSERT INTO user_channels (tg_id, channel_id, channel_title, added_at)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(tg_id, channel_id) DO UPDATE SET channel_title = excluded.channel_title;
            """,
            [tg_id, channel_id, channel_title[:120], now],
        )
        await self.execute(
            "UPDATE users SET active_channel_id = ?, active_channel_title = ? WHERE tg_id = ?;",
            [channel_id, channel_title[:120], tg_id],
        )

    async def clear_user_active_channel(self, tg_id: int) -> None:
        await self.execute(
            "UPDATE users SET active_channel_id = 0, active_channel_title = '' WHERE tg_id = ?;",
            [tg_id],
        )

    async def count_recent_links(self, tg_id: int, window_seconds: int = 3600) -> int:
        cutoff = int(time.time()) - window_seconds
        rows = await self.execute(
            "SELECT COUNT(*) AS cnt FROM file_links WHERE creator_id = ? AND created_at >= ?;",
            [tg_id, cutoff],
        )
        return int(rows[0]["cnt"]) if rows else 0

    async def create_link(
        self,
        token: str,
        slug: str,
        bin_msg_id: int,
        file_name: str,
        file_size: int,
        mime_type: str,
        media_kind: str,
        creator_id: int,
        source_type: str,
        ttl_seconds: int = 86400,
        target_chat_id: int | None = None,
        variants: dict[str, Any] | None = None,
        password_hash: str = "",
        max_downloads: int = 0,
    ) -> dict[str, Any]:
        now = int(time.time())
        expires_at = now + ttl_seconds
        chat_id = target_chat_id if target_chat_id is not None else BIN_CHANNEL
        variants_str = json.dumps(variants or {}, ensure_ascii=False)

        await self.execute(
            """
            INSERT INTO file_links (
                token, slug, bin_msg_id, target_chat_id, source_chat, file_name, file_size,
                mime_type, media_kind, variants_json, password_hash, max_downloads, creator_id,
                source_type, downloads, bytes_served, created_at, expires_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?);
            """,
            [
                token, slug, bin_msg_id, chat_id, chat_id, file_name, file_size,
                mime_type, media_kind, variants_str, password_hash, max_downloads, creator_id,
                source_type, now, expires_at,
            ],
        )
        return {"token": token, "slug": slug, "expires_at": expires_at}

    async def get_active_link(self, token: str) -> dict[str, Any] | None:
        now = int(time.time())
        rows = await self.execute("SELECT * FROM file_links WHERE token = ? AND expires_at > ?;", [token, now])
        if not rows:
            return None
        row = rows[0]
        if row["max_downloads"] > 0 and row["downloads"] >= row["max_downloads"]:
            return None
        try:
            row["variants"] = json.loads(row.get("variants_json") or "{}")
        except json.JSONDecodeError:
            row["variants"] = {}
        return row

    async def record_transfer(self, token: str, creator_id: int, bytes_sent: int, count_download: bool) -> None:
        dl_inc = 1 if count_download else 0
        await self.execute(
            "UPDATE file_links SET downloads = downloads + ?, bytes_served = bytes_served + ? WHERE token = ?;",
            [dl_inc, bytes_sent, token],
        )
        if creator_id != 0:
            await self.execute(
                "UPDATE users SET bytes_served = bytes_served + ? WHERE tg_id = ?;",
                [bytes_sent, creator_id],
            )

    async def get_expired_links(self) -> list[dict[str, Any]]:
        now = int(time.time())
        return await self.execute(
            "SELECT token, bin_msg_id, target_chat_id, variants_json FROM file_links "
            "WHERE expires_at <= ? OR (max_downloads > 0 AND downloads >= max_downloads);",
            [now],
        )

    async def delete_links_by_tokens(self, tokens: list[str]) -> None:
        if not tokens:
            return
        placeholders = ",".join("?" for _ in tokens)
        await self.execute(f"DELETE FROM file_links WHERE token IN ({placeholders});", tokens)

    async def log_event(self, level: str, event: str, actor: str, details: str) -> None:
        now = int(time.time())
        await self.execute(
            "INSERT INTO audit_logs (level, event, actor, details, created_at) VALUES (?, ?, ?, ?, ?);",
            [level[:16], event[:64], actor[:64], details[:500], now],
        )

    async def count_logs(self) -> int:
        rows = await self.execute("SELECT COUNT(*) AS cnt FROM audit_logs;")
        return int(rows[0]["cnt"]) if rows else 0

    async def export_oldest_logs_gzip(self, batch_size: int = 10000) -> tuple[bytes, list[int], str]:
        rows = await self.execute(
            "SELECT id, level, event, actor, details, created_at FROM audit_logs ORDER BY id ASC LIMIT ?;",
            [batch_size],
        )
        if not rows:
            return b"", [], ""
        ids = [int(r["id"]) for r in rows]
        summary = f"Rows: {len(rows)} | IDs: {ids[0]}..{ids[-1]}"
        gz_bytes = gzip.compress(json.dumps(rows, ensure_ascii=False).encode("utf-8"), compresslevel=6)
        return gz_bytes, ids, summary

    async def purge_logs_and_vacuum(self, log_ids: list[int]) -> None:
        for i in range(0, len(log_ids), 500):
            chunk = log_ids[i : i + 500]
            placeholders = ",".join("?" for _ in chunk)
            await self.execute(f"DELETE FROM audit_logs WHERE id IN ({placeholders});", chunk)
        await self.execute("VACUUM;")

    async def get_dashboard_data(self, search: str = "") -> dict[str, Any]:
        now = int(time.time())
        s_links = await self.execute(
            "SELECT COUNT(*) AS active_links, COALESCE(SUM(downloads), 0) AS total_downloads FROM file_links WHERE expires_at > ?;",
            [now],
        )
        s_users = await self.execute(
            "SELECT COUNT(*) AS total_users, "
            "SUM(CASE WHEN tier = 'premium' THEN 1 ELSE 0 END) AS premium_users, "
            "COALESCE(SUM(bytes_served), 0) AS lifetime_bytes FROM users;"
        )
        log_count = await self.count_logs()
        tutorial_url = await self.get_setting("tutorial_video_url", "")

        if search:
            like = f"%{search}%"
            links = await self.execute(
                "SELECT * FROM file_links WHERE expires_at > ? AND (file_name LIKE ? OR slug LIKE ? OR source_type LIKE ?) "
                "ORDER BY created_at DESC LIMIT 100;",
                [now, like, like, like],
            )
            users = await self.execute(
                "SELECT * FROM users WHERE username LIKE ? OR full_name LIKE ? OR CAST(tg_id AS TEXT) LIKE ? "
                "ORDER BY last_seen DESC LIMIT 100;",
                [like, like, like],
            )
            logs = await self.execute(
                "SELECT * FROM audit_logs WHERE event LIKE ? OR actor LIKE ? OR details LIKE ? ORDER BY id DESC LIMIT 150;",
                [like, like, like],
            )
        else:
            links = await self.execute("SELECT * FROM file_links WHERE expires_at > ? ORDER BY created_at DESC LIMIT 100;", [now])
            users = await self.execute("SELECT * FROM users ORDER BY last_seen DESC LIMIT 100;")
            logs = await self.execute("SELECT * FROM audit_logs ORDER BY id DESC LIMIT 150;")

        return {
            "now": now,
            "tutorial_url": tutorial_url,
            "stats": {
                "active_links": s_links[0]["active_links"],
                "total_downloads": s_links[0]["total_downloads"],
                "total_users": s_users[0]["total_users"],
                "premium_users": s_users[0]["premium_users"] or 0,
                "lifetime_bytes": s_users[0]["lifetime_bytes"],
                "log_count": log_count,
            },
            "links": links,
            "users": users,
            "logs": logs,
        }


db = TursoDB()


# ==============================================================================
# 4. SECURITY, FILENAME SANITIZATION, ADMIN AUTH & HEADERS
# ==============================================================================

DANGEROUS_INLINE_EXTS = {
    ".html", ".htm", ".xhtml", ".svg", ".svgz", ".xml", ".xsl",
    ".js", ".mjs", ".cjs", ".swf", ".hta", ".mhtml",
}
DANGEROUS_INLINE_MIMES = {
    "text/html", "application/xhtml+xml", "image/svg+xml",
    "text/xml", "application/xml", "application/javascript", "text/javascript",
}


def sanitize_filename(raw_name: str | None, mime_type: str | None = None) -> str:
    ext = mimetypes.guess_extension(mime_type or "") or ".bin"
    if ext == ".jpe":
        ext = ".jpg"

    name = (raw_name or "").strip().replace("\\", "/").split("/")[-1]
    name = re.sub(r'[<>:"/\\|?*\x00-\x1f\x7f]+', "_", name)
    name = re.sub(r"\s+", " ", name).strip(" .")

    if not name:
        stamp = time.strftime("%Y-%m-%d_%H%M", time.gmtime())
        name = f"File_{stamp}{ext}"
    elif "." not in name:
        name = f"{name}{ext}"

    return name[:160]


def build_custom_slug(custom_title: str | None, original_filename: str) -> str:
    _, orig_ext = os.path.splitext(original_filename)
    if not custom_title or not custom_title.strip():
        return original_filename

    clean_title = re.sub(r'[<>:"/\\|?*\x00-\x1f\x7f]+', "-", custom_title.strip())
    clean_title = re.sub(r"\s+", "-", clean_title).strip("-.")
    if not clean_title:
        return original_filename

    if orig_ext and not clean_title.lower().endswith(orig_ext.lower()):
        clean_title = f"{clean_title}{orig_ext}"
    return clean_title[:140]


def get_safe_delivery_headers(file_name: str, mime_type: str, want_inline: bool) -> tuple[str, str]:
    lower_name = file_name.lower()
    is_dangerous = (
        any(lower_name.endswith(ext) for ext in DANGEROUS_INLINE_EXTS)
        or mime_type.lower().split(";")[0].strip() in DANGEROUS_INLINE_MIMES
    )

    if is_dangerous:
        effective_mime = "application/octet-stream"
        disposition_type = "attachment"
    else:
        effective_mime = mime_type or "application/octet-stream"
        disposition_type = "inline" if want_inline else "attachment"

    ascii_fallback = file_name.encode("ascii", "ignore").decode("ascii").replace('"', "_") or "file.bin"
    utf8_encoded = urllib.parse.quote(file_name, safe="")
    content_disp = f"{disposition_type}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{utf8_encoded}"
    return effective_mime, content_disp


def hash_link_password(raw_password: str) -> str:
    if not raw_password.strip():
        return ""
    salt = secrets.token_hex(16)
    dk = hashlib.pbkdf2_hmac("sha256", raw_password.strip().encode("utf-8"), salt.encode("utf-8"), 120_000)
    return f"{salt}${dk.hex()}"


def verify_link_password(stored_hash: str, candidate: str) -> bool:
    if not stored_hash:
        return True
    if not candidate:
        return False
    try:
        salt, expected_hex = stored_hash.split("$", 1)
        dk = hashlib.pbkdf2_hmac("sha256", candidate.strip().encode("utf-8"), salt.encode("utf-8"), 120_000)
        return hmac.compare_digest(dk.hex(), expected_hex)
    except ValueError:
        return False


class AdminSessionManager:
    COOKIE_NAME = "ftl_admin_session"
    MAX_AGE = 12 * 3600

    def __init__(self) -> None:
        self.serializer = URLSafeTimedSerializer(SECRET_KEY, salt="hf-admin-auth-v1")

    def create_session_token(self, username: str) -> str:
        return self.serializer.dumps({"u": username, "csrf": secrets.token_urlsafe(24)})

    def read_session(self, request: Request) -> dict[str, str] | None:
        raw = request.cookies.get(self.COOKIE_NAME)
        if not raw:
            return None
        try:
            data = self.serializer.loads(raw, max_age=self.MAX_AGE)
            if isinstance(data, dict) and "u" in data and "csrf" in data:
                return data
        except (BadSignature, SignatureExpired):
            return None
        return None

    def require_admin(self, request: Request) -> dict[str, str]:
        sess = self.read_session(request)
        if not sess or not hmac.compare_digest(sess["u"], ADMIN_USERNAME):
            raise HTTPException(status_code=status.HTTP_303_SEE_OTHER, headers={"Location": "/admin/login"})
        return sess

    @staticmethod
    def verify_csrf(session: dict[str, str], submitted_token: str) -> None:
        if not submitted_token or not hmac.compare_digest(session["csrf"], submitted_token):
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid CSRF token")


class LoginRateLimiter:
    MAX_ATTEMPTS = 5
    LOCK_WINDOW = 15 * 60

    def __init__(self) -> None:
        self._failures: dict[str, list[float]] = defaultdict(list)

    def _prune(self, ip: str) -> None:
        cutoff = time.time() - self.LOCK_WINDOW
        self._failures[ip] = [t for t in self._failures[ip] if t > cutoff]

    def is_blocked(self, ip: str) -> bool:
        self._prune(ip)
        return len(self._failures[ip]) >= self.MAX_ATTEMPTS

    def record_failure(self, ip: str) -> None:
        self._prune(ip)
        self._failures[ip].append(time.time())

    def reset(self, ip: str) -> None:
        self._failures.pop(ip, None)


class SecurityHeadersMiddleware:
    def __init__(self, app) -> None:
        self.app = app

    async def __call__(self, scope, receive, send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        path = scope.get("path", "")

        async def send_with_headers(message) -> None:
            if message["type"] == "http.response.start":
                headers = list(message.get("headers", []))
                headers.append((b"x-content-type-options", b"nosniff"))
                headers.append((b"referrer-policy", b"no-referrer"))
                if path.startswith("/admin") or path.startswith("/watch"):
                    headers.append((b"x-frame-options", b"DENY"))
                    headers.append(
                        (
                            b"content-security-policy",
                            b"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
                            b"media-src 'self' https:; img-src 'self' data: https:; frame-src 'self' https:; "
                            b"frame-ancestors 'none'; base-uri 'self'; form-action 'self';",
                        )
                    )
                message["headers"] = headers
            await send(message)

        await self.app(scope, receive, send_with_headers)


session_mgr = AdminSessionManager()
login_limiter = LoginRateLimiter()


# ==============================================================================
# 5. MULTI-QUALITY TRANSCODER & HUGGING FACE MIRROR
# ==============================================================================

async def encode_video_variant(input_path: str, output_path: str, quality: str) -> bool:
    profile = QUALITY_PROFILES.get(quality)
    if not profile:
        return False
    ok, err = await _run_ffmpeg(
        [
            "-i", input_path,
            "-vf", f"scale=-2:{profile['height']}",
            "-c:v", "libx264",
            "-preset", "veryfast",
            "-crf", str(profile["crf"]),
            "-c:a", "aac",
            "-b:a", str(profile["audio_bitrate"]),
            "-movflags", "+faststart",
            output_path,
        ]
    )
    if not ok:
        print(f"[FFMPEG {quality} ERROR] {err}", flush=True)
        return False
    return os.path.exists(output_path) and os.path.getsize(output_path) > 0


async def generate_quality_ladder(
    source_path: str,
    base_title: str,
    selected_qualities: list[str],
    upload_callback,
    progress_callback=None,
) -> dict[str, dict]:
    ordered = [q for q in ("720p", "480p", "360p", "240p", "144p") if q in selected_qualities]
    if not ordered or not _has_enough_disk():
        return {}

    work_dir = tempfile.mkdtemp(prefix="ftl_transcode_")
    variants: dict[str, dict] = {}
    stem, _ = os.path.splitext(base_title)

    try:
        for idx, quality in enumerate(ordered, start=1):
            pct = (idx - 0.5) / len(ordered)
            if progress_callback:
                await progress_callback(pct, f"Encoding {quality} ({idx}/{len(ordered)})...")

            out_name = f"{stem}_{quality}.mp4"
            out_path = os.path.join(work_dir, out_name)
            if not await encode_video_variant(source_path, out_path, quality):
                continue

            try:
                if progress_callback:
                    await progress_callback(idx / len(ordered), f"Uploading {quality} ({idx}/{len(ordered)})...")
                meta = await upload_callback(out_path, out_name, quality)
                variants[quality] = meta
            finally:
                if os.path.exists(out_path):
                    os.remove(out_path)
    finally:
        shutil.rmtree(work_dir, ignore_errors=True)

    return variants


HF_URL_RE = re.compile(
    r"^https?://huggingface\.co/(?:(datasets|spaces)/)?([^/]+/[^/]+)(?:/(?:blob|resolve|tree)/([^/]+)/(.+))?$"
)


def _list_hf_files(hf_url: str, ext_filter: str) -> tuple[str, str, str, list[dict]]:
    from huggingface_hub import HfApi

    cleaned = hf_url.strip().split("?")[0].rstrip("/")
    match = HF_URL_RE.match(cleaned)
    if not match:
        raise ValueError("Invalid Hugging Face URL.")
    kind, repo_id, revision, subpath = match.groups()
    repo_type = "dataset" if kind == "datasets" else ("space" if kind == "spaces" else "model")
    rev = revision or "main"

    api = HfApi(token=HF_TOKEN)
    info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=rev, files_metadata=True)

    ext_clean = ext_filter.strip().lower()
    if ext_clean and not ext_clean.startswith("."):
        ext_clean = f".{ext_clean}"

    files: list[dict] = []
    for sibling in info.siblings or []:
        rfilename = sibling.rfilename
        if subpath and not (rfilename == subpath or rfilename.startswith(subpath.rstrip("/") + "/")):
            continue
        if ext_clean and not rfilename.lower().endswith(ext_clean):
            continue
        files.append({"path": rfilename, "size": int(getattr(sibling, "size", 0) or 0)})

    if not files:
        raise ValueError("No matching files found in that Hugging Face repository.")
    return repo_type, repo_id, rev, files


def _split_large_file(file_path: str, chunk_limit: int) -> list[str]:
    file_size = os.path.getsize(file_path)
    if file_size <= chunk_limit:
        return [file_path]
    parts: list[str] = []
    part_num = 1
    with open(file_path, "rb") as src:
        while True:
            part_path = f"{file_path}.part{part_num:03d}"
            written = 0
            with open(part_path, "wb") as dst:
                while written < chunk_limit:
                    buf = src.read(min(8 * 1024 * 1024, chunk_limit - written))
                    if not buf:
                        break
                    dst.write(buf)
                    written += len(buf)
            if written == 0:
                if os.path.exists(part_path):
                    os.remove(part_path)
                break
            parts.append(part_path)
            part_num += 1
    return parts


async def mirror_hf_target(hf_url: str, ext_filter: str, upload_cb, status_cb) -> list[dict]:
    from huggingface_hub import hf_hub_download

    if not _has_enough_disk():
        raise RuntimeError("Server temporary disk is busy.")

    await status_cb(0.05, "Inspecting Hugging Face repository...")
    repo_type, repo_id, rev, files = await asyncio.to_thread(_list_hf_files, hf_url, ext_filter)

    work_dir = tempfile.mkdtemp(prefix="ftl_hf_")
    results: list[dict] = []

    try:
        total = len(files)
        for idx, item in enumerate(files, start=1):
            rel_path = item["path"]
            base_name = os.path.basename(rel_path)
            dl_pct = ((idx - 1) + 0.35) / total
            await status_cb(dl_pct, f"[{idx}/{total}] Downloading `{base_name}`...")

            local_path = await asyncio.to_thread(
                hf_hub_download,
                repo_id=repo_id,
                filename=rel_path,
                repo_type=repo_type,
                revision=rev,
                local_dir=work_dir,
                token=HF_TOKEN,
            )

            parts = await asyncio.to_thread(_split_large_file, local_path, TG_SPLIT_LIMIT_BYTES)
            is_split = len(parts) > 1

            for p_idx, part_path in enumerate(parts, start=1):
                part_name = os.path.basename(part_path)
                up_pct = ((idx - 1) + 0.75) / total
                label = f"[{idx}/{total}] Uploading `{part_name}`" + (f" ({p_idx}/{len(parts)})" if is_split else "")
                await status_cb(up_pct, label)

                uploaded = await upload_cb(part_path, part_name)
                results.append(uploaded)

                if is_split and os.path.exists(part_path):
                    os.remove(part_path)

            if os.path.exists(local_path):
                os.remove(local_path)
    finally:
        shutil.rmtree(work_dir, ignore_errors=True)

    return results


# ==============================================================================
# 6. TELEGRAM BOT + THROTTLED LIVE PROGRESS BAR + CALLBACK CONTROLS
# ==============================================================================

bot = Client(
    name="primary_bot",
    api_id=API_ID,
    api_hash=API_HASH,
    bot_token=BOT_TOKEN,
    in_memory=True,
)

stream_clients: list[Client] = [bot]
for idx, extra_token in enumerate(MULTI_TOKENS, start=1):
    stream_clients.append(
        Client(
            name=f"worker_bot_{idx}",
            api_id=API_ID,
            api_hash=API_HASH,
            bot_token=extra_token,
            in_memory=True,
            no_updates=True,
        )
    )

_client_cycle = itertools.cycle(stream_clients)


def get_stream_client() -> Client:
    return next(_client_cycle)


class TelegramProgressReporter:
    """Throttles Telegram message edits so live progress bars never trigger FloodWait."""

    def __init__(self, status_msg: Message, title: str, min_interval: float = 1.6) -> None:
        self.status_msg = status_msg
        self.title = title
        self.min_interval = min_interval
        self.last_edit = 0.0
        self.last_text = ""

    async def update(self, pct: float, stage: str, detail: str = "", force: bool = False) -> None:
        clamped = max(0.0, min(1.0, pct))
        bar = _render_bar(clamped)
        percent_int = int(round(clamped * 100))
        lines = [
            f"**{self.title}**",
            f"`{bar}` **{percent_int}%**",
            f"• **Stage:** {stage}",
        ]
        if detail:
            lines.append(f"• {detail}")
        text = "\n".join(lines)

        now = time.monotonic()
        if not force and (now - self.last_edit) < self.min_interval:
            return
        if text == self.last_text:
            return

        try:
            await self.status_msg.edit_text(text)
            self.last_edit = now
            self.last_text = text
        except Exception:
            pass

    async def make_transfer_cb(self, pct_start: float, pct_end: float, label: str):
        started_at = time.monotonic()

        async def _cb(current: int, total: int) -> None:
            if total <= 0:
                return
            ratio = max(0.0, min(1.0, current / total))
            overall_pct = pct_start + ratio * (pct_end - pct_start)
            elapsed = max(0.2, time.monotonic() - started_at)
            speed = current / elapsed
            detail = f"{_format_size(current)} / {_format_size(total)} · {_format_size(speed)}/s"
            await self.update(overall_pct, label, detail=detail, force=False)

        return _cb


def extract_media_info(msg: Message) -> tuple[str, int, str, str] | None:
    caption_title = (msg.caption or "").splitlines()[0].strip()[:80] if msg.caption else ""
    if msg.document:
        m = msg.document
        return sanitize_filename(m.file_name or caption_title, m.mime_type), m.file_size, m.mime_type or "application/octet-stream", "document"
    if msg.video:
        m = msg.video
        return sanitize_filename(m.file_name or caption_title, m.mime_type or "video/mp4"), m.file_size, m.mime_type or "video/mp4", "video"
    if msg.audio:
        m = msg.audio
        title = f"{m.performer} - {m.title}" if m.title else caption_title
        return sanitize_filename(m.file_name or title, m.mime_type or "audio/mpeg"), m.file_size, m.mime_type or "audio/mpeg", "audio"
    if msg.voice:
        m = msg.voice
        return sanitize_filename(caption_title or "Voice_Note", m.mime_type or "audio/ogg"), m.file_size, m.mime_type or "audio/ogg", "audio"
    if msg.photo:
        return sanitize_filename(caption_title or "Photo", "image/jpeg"), msg.photo.file_size, "image/jpeg", "photo"
    if msg.animation:
        m = msg.animation
        return sanitize_filename(m.file_name or caption_title or "Animation", m.mime_type or "video/mp4"), m.file_size, m.mime_type or "video/mp4", "video"
    return None


def _parse_qualities_from_text(text: str | None) -> list[str]:
    if not text:
        return []
    low = text.lower()
    if "allq" in low or "qualities" in low:
        return ["720p", "480p", "360p", "240p", "144p"]
    return [q for q in ("720p", "480p", "360p", "240p", "144p") if q in low]


def _wants_hindi_dub(text: str | None) -> bool:
    if not text:
        return False
    low = text.lower()
    return any(k in low for k in ("hindi", "hin", "dub"))


async def verify_channel_admin(channel_id: int) -> tuple[bool, str]:
    try:
        chat = await bot.get_chat(channel_id)
        me = await bot.get_me()
        member = await bot.get_chat_member(channel_id, me.id)
        status_val = getattr(member.status, "name", str(member.status)).upper()
        if "ADMINISTRATOR" not in status_val and "OWNER" not in status_val:
            return False, "Bot is not an Administrator in that channel."
        privs = getattr(member, "privileges", None)
        if privs is not None and hasattr(privs, "can_post_messages") and not privs.can_post_messages:
            return False, "Bot is Admin, but lacks 'Post Messages' permission."
        title = getattr(chat, "title", None) or str(channel_id)
        return True, title
    except Exception as exc:
        return False, f"Cannot access channel: {type(exc).__name__}"


async def _finalize_and_send_link(
    reply_target: Message,
    user_id: int,
    tier: str,
    token: str,
    final_slug: str,
    file_size: int,
    mime_type: str,
    media_kind: str,
    bin_msg_id: int,
    dest_chat_id: int,
    source_type: str,
    variants: dict[str, Any] | None = None,
    ttl_seconds: int = 86400,
    extra_note: str = "",
) -> None:
    await db.create_link(
        token=token,
        slug=final_slug,
        bin_msg_id=bin_msg_id,
        target_chat_id=dest_chat_id,
        file_name=final_slug,
        file_size=file_size,
        mime_type=mime_type,
        media_kind=media_kind,
        creator_id=user_id,
        source_type=source_type,
        ttl_seconds=ttl_seconds,
        variants=variants or {},
    )
    enc = urllib.parse.quote(final_slug, safe="")
    dl_url = f"{BASE_URL}/dl/{token}/{enc}"
    watch_url = f"{BASE_URL}/watch/{token}/{enc}"

    buttons = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("Direct Download", url=dl_url),
                InlineKeyboardButton("Stream / Watch", url=watch_url),
            ],
            [
                InlineKeyboardButton("720p", url=f"{watch_url}?q=720p"),
                InlineKeyboardButton("480p", url=f"{watch_url}?q=480p"),
                InlineKeyboardButton("360p", url=f"{watch_url}?q=360p"),
                InlineKeyboardButton("144p", url=f"{watch_url}?q=144p"),
            ],
        ]
    )

    q_list = ["Original"] + [q for q in ("720p", "480p", "360p", "240p", "144p") if (variants or {}).get(q)]
    dest_label = "Custom Channel" if dest_chat_id != BIN_CHANNEL else "Storage Channel"
    note_line = f"\n• {extra_note}" if extra_note else ""

    await reply_target.reply_text(
        f"**Link Ready**\n"
        f"• **File:** `{final_slug}` ({_format_size(file_size)})\n"
        f"• **Qualities:** `{', '.join(q_list)}`\n"
        f"• **Destination:** `{dest_label}` · **Tier:** `{tier.upper()}`{note_line}",
        reply_markup=buttons,
    )


async def _process_media_message(
    source_msg: Message,
    reply_target: Message,
    requester_msg: Message,
    custom_slug_input: str = "",
) -> None:
    user = requester_msg.from_user
    if not user or user.is_bot:
        return

    full_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
    user_row = await db.upsert_user(user.id, user.username or "", full_name, increment_links=False)
    if user_row["is_banned"] == 1:
        await db.log_event("WARN", "BANNED_USER_BLOCKED", f"tg:{user.id}", f"Chat {requester_msg.chat.id}")
        return

    hourly_cap = PREMIUM_LINKS_PER_HOUR if user_row["tier"] == "premium" else FREE_LINKS_PER_HOUR
    recent = await db.count_recent_links(user.id, window_seconds=3600)
    if recent >= hourly_cap:
        await reply_target.reply_text(f"Hourly limit reached ({hourly_cap} links/hr). Try again later.")
        return

    media_info = extract_media_info(source_msg)
    if not media_info:
        return

    orig_name, file_size, mime_type, media_kind = media_info
    final_slug = build_custom_slug(custom_slug_input, orig_name)
    dest_chat_id = int(user_row["active_channel_id"]) if user_row["active_channel_id"] != 0 else BIN_CHANNEL
    token = secrets.token_urlsafe(12)
    source_type = "dm" if requester_msg.chat.type.name == "PRIVATE" else f"group:{requester_msg.chat.id}"

    hint_text = f"{custom_slug_input} {source_msg.caption or ''} {requester_msg.text or ''}"
    requested_qualities = _parse_qualities_from_text(hint_text) if media_kind == "video" else []
    wants_dub = _wants_hindi_dub(hint_text) and media_kind == "video"

    status_msg = await reply_target.reply_text(
        f"**Processing `{final_slug}`**\n`{_render_bar(0.05)}` **5%**\n• **Stage:** Queued..."
    )
    prog = TelegramProgressReporter(status_msg, f"Processing `{final_slug}`")

    try:
        if wants_dub:
            if file_size > DUB_TEST_MAX_BYTES:
                await status_msg.edit_text(
                    f"Hindi dubbing test mode requires a file under **{_format_size(DUB_TEST_MAX_BYTES)}** "
                    f"(got `{_format_size(file_size)}`)."
                )
                return

            work_dir = tempfile.mkdtemp(prefix="ftl_bot_dub_")
            try:
                dl_cb = await prog.make_transfer_cb(0.05, 0.25, "Downloading English video from Telegram")
                src_local = await bot.download_media(
                    source_msg,
                    file_name=os.path.join(work_dir, final_slug),
                    progress=dl_cb,
                )
                if not src_local or not os.path.exists(src_local):
                    raise RuntimeError("Failed to download video from Telegram.")

                dub_name = f"Hindi_{os.path.splitext(final_slug)[0]}.mp4"
                dub_out = os.path.join(work_dir, dub_name)

                async def on_dub_stage(pct: float, stage: str) -> None:
                    mapped = 0.25 + max(0.0, min(1.0, pct)) * 0.50
                    await prog.update(mapped, stage, force=True)

                dub_meta = await dub_english_video_to_hindi(src_local, dub_out, on_dub_stage)

                up_cb = await prog.make_transfer_cb(0.75, 0.98, "Uploading Hindi-dubbed video to Telegram")
                sent = await bot.send_video(
                    chat_id=dest_chat_id,
                    video=dub_out,
                    file_name=dub_name,
                    caption=f"`{dub_name}` · Hindi Dub ({', '.join(dub_meta['speakers'])})",
                    progress=up_cb,
                )
                dub_size = os.path.getsize(dub_out)
                await prog.update(1.0, "Completed!", force=True)
                await db.upsert_user(user.id, user.username or "", full_name, increment_links=True)
                await db.log_event("INFO", "BOT_HINDI_DUB", f"tg:{user.id}", f"{dub_name} ({_format_size(dub_size)})")

                await _finalize_and_send_link(
                    reply_target=reply_target,
                    user_id=user.id,
                    tier=user_row["tier"],
                    token=token,
                    final_slug=dub_name,
                    file_size=dub_size,
                    mime_type="video/mp4",
                    media_kind="video",
                    bin_msg_id=sent.id,
                    dest_chat_id=dest_chat_id,
                    source_type=source_type,
                    extra_note=f"Speakers: `{', '.join(dub_meta['speakers'])}` · Emotions: `{', '.join(dub_meta['emotions'])}`",
                )
            finally:
                shutil.rmtree(work_dir, ignore_errors=True)
            return

        # Standard copy to BIN_CHANNEL / user channel with live progress bar
        await prog.update(0.20, "Copying file to Telegram storage...", force=True)
        try:
            stored_msg = await source_msg.copy(dest_chat_id)
        except Exception:
            dest_chat_id = BIN_CHANNEL
            stored_msg = await source_msg.copy(BIN_CHANNEL)

        variants: dict[str, dict] = {}
        if requested_qualities and _has_enough_disk():
            work_dir = tempfile.mkdtemp(prefix="ftl_bot_q_")
            try:
                dl_cb = await prog.make_transfer_cb(0.25, 0.45, "Downloading source video for transcoding")
                src_local = await bot.download_media(
                    source_msg,
                    file_name=os.path.join(work_dir, final_slug),
                    progress=dl_cb,
                )
                if src_local and os.path.exists(src_local):
                    async def upload_variant(v_path: str, v_name: str, q_label: str) -> dict:
                        v_msg = await bot.send_video(
                            chat_id=dest_chat_id,
                            video=v_path,
                            file_name=v_name,
                            caption=f"`{v_name}` ({q_label})",
                        )
                        return {
                            "msg_id": v_msg.id,
                            "chat_id": dest_chat_id,
                            "file_name": v_name,
                            "size": os.path.getsize(v_path),
                            "mime_type": "video/mp4",
                        }

                    async def on_q_prog(pct: float, stage: str) -> None:
                        await prog.update(0.45 + pct * 0.50, stage, force=True)

                    variants = await generate_quality_ladder(
                        src_local, final_slug, requested_qualities, upload_variant, progress_callback=on_q_prog
                    )
            finally:
                shutil.rmtree(work_dir, ignore_errors=True)

        await prog.update(1.0, "Link generated!", force=True)
        await db.upsert_user(user.id, user.username or "", full_name, increment_links=True)
        await db.log_event("INFO", "BOT_LINK_CREATED", f"tg:{user.id}", f"{final_slug} ({_format_size(file_size)})")

        await _finalize_and_send_link(
            reply_target=reply_target,
            user_id=user.id,
            tier=user_row["tier"],
            token=token,
            final_slug=final_slug,
            file_size=file_size,
            mime_type=mime_type,
            media_kind=media_kind,
            bin_msg_id=stored_msg.id,
            dest_chat_id=dest_chat_id,
            source_type=source_type,
            variants=variants,
        )
    except Exception as exc:
        err_text = f"{type(exc).__name__}: {exc}"
        await db.log_event("ERROR", "BOT_PROCESS_ERR", f"tg:{user.id}", err_text[:200])
        try:
            await status_msg.edit_text(f"Failed to process `{final_slug}`: `{err_text[:220]}`")
        except Exception:
            pass
    finally:
        try:
            await status_msg.delete()
        except Exception:
            pass


@bot.on_message(filters.command(["start", "help"]) & ~filters.bot)
async def cmd_start(_, message: Message) -> None:
    if message.from_user:
        full_name = f"{message.from_user.first_name or ''} {message.from_user.last_name or ''}".strip()
        await db.upsert_user(message.from_user.id, message.from_user.username or "", full_name)

    await message.reply_text(
        "**FileToLink, Multi-Quality & Hindi Dub Bot**\n\n"
        "• **Send or forward any file/video** → instant stream & download links with live progress bar.\n"
        "• **Multi-quality video:** Add `720p`, `480p`, `360p`, `240p`, `144p`, or `allq` in caption or `/link title 480p 144p`.\n"
        "• **English → Hindi Dub (< 5 MB test):** Add `hindi` or `dub` in caption or `/dub` on a video (< 5 MB).\n"
        "• **Set channel:** `/setchannel -100...` (after adding bot as Admin with Post Messages) or `/clearsetchannel`.\n"
        "• **HF Mirror:** `/hfmirror https://huggingface.co/datasets/org/repo [.ext]`\n"
        f"• **Web Portal & Admin:** {BASE_URL} · {BASE_URL}/admin"
    )


@bot.on_message(filters.command("setchannel") & ~filters.bot)
async def cmd_setchannel(_, message: Message) -> None:
    if not message.from_user:
        return
    parts = (message.text or "").split(maxsplit=1)
    if len(parts) < 2:
        await message.reply_text("Usage: `/setchannel -1001234567890` (Bot must be Admin with Post Messages).")
        return
    try:
        ch_id = int(parts[1].strip())
    except ValueError:
        await message.reply_text("Invalid channel ID.")
        return

    ok, info = await verify_channel_admin(ch_id)
    if not ok:
        await message.reply_text(f"Verification failed: {info}")
        return

    full_name = f"{message.from_user.first_name or ''} {message.from_user.last_name or ''}".strip()
    await db.upsert_user(message.from_user.id, message.from_user.username or "", full_name)
    await db.save_user_channel(message.from_user.id, ch_id, info)
    await db.log_event("INFO", "CHANNEL_BOUND", f"tg:{message.from_user.id}", f"{info} ({ch_id})")
    await message.reply_text(f"Target channel set to **{info}** (`{ch_id}`).")


@bot.on_message(filters.command("clearsetchannel") & ~filters.bot)
async def cmd_clearsetchannel(_, message: Message) -> None:
    if not message.from_user:
        return
    await db.clear_user_active_channel(message.from_user.id)
    await message.reply_text("Reset target destination to default storage channel.")


@bot.on_message(filters.command("link") & filters.reply & ~filters.bot)
async def cmd_reply_link(_, message: Message) -> None:
    target = message.reply_to_message
    if not target or not extract_media_info(target):
        await message.reply_text("Reply `/link [custom-title] [qualities]` to a media message.")
        return
    parts = (message.text or "").split(maxsplit=1)
    custom_slug = parts[1].strip() if len(parts) > 1 else ""
    await _process_media_message(target, message, message, custom_slug_input=custom_slug)


@bot.on_message(filters.command("dub") & filters.reply & ~filters.bot)
async def cmd_reply_dub(_, message: Message) -> None:
    target = message.reply_to_message
    if not target or not extract_media_info(target):
        await message.reply_text("Reply `/dub` to an English video (< 5 MB in test mode).")
        return
    await _process_media_message(target, message, message, custom_slug_input="hindi")


@bot.on_message(filters.command("hfmirror") & ~filters.bot)
async def cmd_hfmirror(_, message: Message) -> None:
    if not message.from_user:
        return
    user = message.from_user
    full_name = f"{user.first_name or ''} {user.last_name or ''}".strip()
    user_row = await db.upsert_user(user.id, user.username or "", full_name)
    if user_row["is_banned"] == 1:
        return

    args = (message.text or "").split()
    if len(args) < 2 or not args[1].startswith("http"):
        await message.reply_text("Usage: `/hfmirror https://huggingface.co/datasets/org/repo [.ext]`")
        return

    hf_url = args[1].strip()
    ext_filter = args[2].strip() if len(args) >= 3 else ""
    dest_chat_id = int(user_row["active_channel_id"]) if user_row["active_channel_id"] != 0 else user.id

    status_msg = await message.reply_text(
        f"**HF Mirror Job**\n`{_render_bar(0.02)}` **2%**\n• **Stage:** Initializing..."
    )
    prog = TelegramProgressReporter(status_msg, "HF Mirror Job")

    async def on_status(pct: float, text: str) -> None:
        await prog.update(pct, text, force=True)

    async def on_upload(local_path: str, part_name: str) -> dict:
        up_cb = await prog.make_transfer_cb(0.75, 0.96, f"Uploading `{part_name}`")
        sent = await bot.send_document(
            chat_id=dest_chat_id,
            document=local_path,
            file_name=part_name,
            caption=f"HF Mirror: `{part_name}`",
            progress=up_cb,
        )
        return {"msg_id": sent.id, "chat_id": dest_chat_id, "file_name": part_name}

    try:
        items = await mirror_hf_target(hf_url, ext_filter, on_upload, on_status)
        await prog.update(1.0, f"Completed! Mirrored {len(items)} file(s).", force=True)
        await db.log_event("INFO", "HF_MIRROR_TG", f"tg:{user.id}", f"Mirrored {len(items)} item(s)")
        await status_msg.edit_text(f"Completed! Uploaded **{len(items)}** file(s) to chat `{dest_chat_id}`.")
    except Exception as exc:
        await status_msg.edit_text(f"Mirror failed: `{str(exc)[:220]}`")


@bot.on_message(filters.forwarded & ~filters.bot & (filters.private | filters.group))
async def handle_forwarded(_, message: Message) -> None:
    if extract_media_info(message):
        await _process_media_message(message, message, message)


@bot.on_message(filters.private & ~filters.forwarded & ~filters.bot)
async def handle_dm_media(_, message: Message) -> None:
    if extract_media_info(message):
        await _process_media_message(message, message, message)


async def delete_telegram_messages(chat_id: int, message_ids: list[int]) -> None:
    if not message_ids:
        return
    for i in range(0, len(message_ids), 100):
        try:
            await bot.delete_messages(chat_id, message_ids[i : i + 100])
        except Exception:
            pass


async def upload_log_archive_to_bin(gz_bytes: bytes, filename: str, caption: str) -> None:
    bio = io.BytesIO(gz_bytes)
    bio.name = filename
    await bot.send_document(chat_id=BIN_CHANNEL, document=bio, caption=caption)


# ==============================================================================
# 7. HIGH-SPEED SLIDING PREFETCH STREAMER (206 PARTIAL CONTENT + MULTI-BOT)
# ==============================================================================

TG_CHUNK_SIZE = 1024 * 1024
PREFETCH_WINDOW = 16
RANGE_PATTERN = re.compile(r"^bytes=(\d*)-(\d*)$")


def _extract_media_size(msg: Message) -> int | None:
    media = msg.document or msg.video or msg.audio or msg.voice or msg.photo or msg.animation
    if not media:
        return None
    return int(getattr(media, "file_size", 0) or 0)


def parse_range_header(range_header: str | None, file_size: int) -> tuple[int, int, bool]:
    if not range_header or file_size <= 0:
        return 0, max(0, file_size - 1), False

    match = RANGE_PATTERN.match(range_header.strip())
    if not match:
        raise HTTPException(
            status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
            headers={"Content-Range": f"bytes */{file_size}"},
        )

    start_str, end_str = match.groups()
    if not start_str and not end_str:
        raise HTTPException(
            status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
            headers={"Content-Range": f"bytes */{file_size}"},
        )

    if start_str and not end_str:
        start = int(start_str)
        end = file_size - 1
    elif not start_str and end_str:
        suffix_len = int(end_str)
        if suffix_len <= 0:
            raise HTTPException(
                status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
                headers={"Content-Range": f"bytes */{file_size}"},
            )
        start = max(0, file_size - suffix_len)
        end = file_size - 1
    else:
        start = int(start_str)
        end = min(int(end_str), file_size - 1)

    if start > end or start >= file_size:
        raise HTTPException(
            status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE,
            headers={"Content-Range": f"bytes */{file_size}"},
        )

    return start, end, True


async def _resolve_message(chat_id: int, msg_id: int) -> tuple[Client, Message]:
    client = get_stream_client()
    for candidate in (client, bot):
        try:
            msg = await candidate.get_messages(chat_id, msg_id)
            if msg and not msg.empty and _extract_media_size(msg) is not None:
                return candidate, msg
        except Exception:
            if candidate is bot:
                raise
    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File no longer available in Telegram.")


async def _prefetch_byte_generator(
    client: Client,
    msg: Message,
    start_byte: int,
    end_byte: int,
    is_partial: bool,
    token: str,
    creator_id: int,
) -> AsyncGenerator[bytes, None]:
    first_chunk = start_byte // TG_CHUNK_SIZE
    first_cut = start_byte % TG_CHUNK_SIZE
    last_chunk = end_byte // TG_CHUNK_SIZE
    last_cut = (end_byte % TG_CHUNK_SIZE) + 1
    total_chunks = last_chunk - first_chunk + 1

    queue: asyncio.Queue[bytes | BaseException | None] = asyncio.Queue(maxsize=PREFETCH_WINDOW)
    bytes_sent = 0

    async def producer() -> None:
        chunk_idx = 0
        try:
            stream_iter = (
                client.stream_media(msg, offset=first_chunk, limit=total_chunks)
                if is_partial
                else client.stream_media(msg)
            )
            async for chunk in stream_iter:
                if not chunk:
                    continue
                if not is_partial:
                    part = chunk
                elif total_chunks == 1:
                    part = chunk[first_cut:last_cut]
                elif chunk_idx == 0:
                    part = chunk[first_cut:]
                elif chunk_idx == total_chunks - 1:
                    part = chunk[:last_cut]
                else:
                    part = chunk
                chunk_idx += 1
                if part:
                    await queue.put(part)
            await queue.put(None)
        except BaseException as exc:
            await queue.put(exc)

    prod_task = asyncio.create_task(producer())
    try:
        while True:
            item = await queue.get()
            if item is None:
                break
            if isinstance(item, BaseException):
                raise item
            bytes_sent += len(item)
            yield item
    except Exception as exc:
        err_text = f"{type(exc).__name__}: {exc}"
        print(f"[STREAM ERROR] token={token} sent={bytes_sent} err={err_text}", flush=True)
        traceback.print_exc()
        asyncio.create_task(db.log_event("ERROR", "STREAM_ERROR", f"token:{token}", err_text))
        raise
    finally:
        if not prod_task.done():
            prod_task.cancel()
            try:
                await prod_task
            except BaseException:
                pass
        if bytes_sent > 0:
            asyncio.create_task(db.record_transfer(token, creator_id, bytes_sent, start_byte == 0))


async def serve_telegram_file(
    request: Request,
    token: str,
    want_inline: bool,
    quality: str | None = None,
    pin: str = "",
):
    link = await db.get_active_link(token)
    if not link:
        raise HTTPException(status_code=status.HTTP_410_GONE, detail="Link expired or download limit reached.")

    if link.get("password_hash") and not verify_link_password(link["password_hash"], pin):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing access PIN.")

    variants: dict = link.get("variants") or {}
    q_key = (quality or "").strip().lower()
    if q_key and q_key in variants and isinstance(variants[q_key], dict):
        v = variants[q_key]
        chat_id = int(v.get("chat_id", link["target_chat_id"]))
        msg_id = int(v["msg_id"])
        file_name = str(v.get("file_name") or link["file_name"])
        file_size = int(v.get("size") or link["file_size"])
        mime_type = str(v.get("mime_type") or "video/mp4")
    else:
        chat_id = int(link["target_chat_id"])
        msg_id = int(link["bin_msg_id"])
        file_name = str(link["file_name"])
        file_size = int(link["file_size"])
        mime_type = str(link["mime_type"])

    try:
        client, msg = await _resolve_message(chat_id, msg_id)
    except HTTPException:
        raise
    except Exception as exc:
        err_text = f"{type(exc).__name__}: {exc}"
        await db.log_event("ERROR", "TG_FETCH_ERROR", f"token:{token}", err_text)
        raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Unable to read file from Telegram.")

    live_size = _extract_media_size(msg)
    if live_size and live_size > 0:
        file_size = live_size

    etag = f'"{token}-{q_key or "orig"}-{file_size}"'
    last_mod = email.utils.formatdate(int(link["created_at"]), usegmt=True)

    if_range = request.headers.get("if-range")
    raw_range = request.headers.get("range")
    if if_range and if_range.strip() not in (etag, last_mod):
        raw_range = None

    start_byte, end_byte, is_partial = parse_range_header(raw_range, file_size)
    content_length = (end_byte - start_byte) + 1 if file_size > 0 else 0
    safe_mime, content_disp = get_safe_delivery_headers(file_name, mime_type, want_inline=want_inline)

    headers = {
        "Accept-Ranges": "bytes",
        "Content-Length": str(content_length),
        "Content-Disposition": content_disp,
        "ETag": etag,
        "Last-Modified": last_mod,
        "Cache-Control": "private, no-transform",
    }
    if is_partial:
        headers["Content-Range"] = f"bytes {start_byte}-{end_byte}/{file_size}"

    status_code = status.HTTP_206_PARTIAL_CONTENT if is_partial else status.HTTP_200_OK

    if request.method == "HEAD":
        return StreamingResponse(iter([b""]), status_code=status_code, headers=headers, media_type=safe_mime)

    return StreamingResponse(
        content=_prefetch_byte_generator(
            client=client,
            msg=msg,
            start_byte=start_byte,
            end_byte=end_byte,
            is_partial=is_partial,
            token=token,
            creator_id=int(link["creator_id"]),
        ),
        status_code=status_code,
        headers=headers,
        media_type=safe_mime,
    )


# ==============================================================================
# 8. HTTP ROUTES, ADMIN PANEL & GRADIO INTERFACE
# ==============================================================================

_bg_loop: asyncio.AbstractEventLoop | None = None


async def run_maintenance(force_log_dump: bool = False) -> dict[str, int]:
    expired = await db.get_expired_links()
    if expired:
        by_chat: dict[int, list[int]] = {}
        tokens: list[str] = []
        for row in expired:
            tokens.append(str(row["token"]))
            chat_id = int(row["target_chat_id"])
            by_chat.setdefault(chat_id, []).append(int(row["bin_msg_id"]))
            try:
                v_map = json.loads(row.get("variants_json") or "{}")
                for v in v_map.values():
                    if isinstance(v, dict) and v.get("msg_id"):
                        by_chat.setdefault(int(v.get("chat_id", chat_id)), []).append(int(v["msg_id"]))
            except Exception:
                pass
        for chat_id, msg_ids in by_chat.items():
            await delete_telegram_messages(chat_id, msg_ids)
        await db.delete_links_by_tokens(tokens)
        await db.log_event("INFO", "EXPIRED_PURGE", "system", f"Cleaned {len(tokens)} expired/burned link(s)")

    dumped = 0
    if force_log_dump or (await db.count_logs()) >= LOG_DUMP_THRESHOLD:
        gz_bytes, log_ids, summary = await db.export_oldest_logs_gzip(batch_size=10000)
        if gz_bytes and log_ids:
            fname = f"audit_logs_{time.strftime('%Y%m%d_%H%M%S', time.gmtime())}.json.gz"
            await upload_log_archive_to_bin(gz_bytes, fname, f"#LOG_ARCHIVE | {summary}")
            await db.purge_logs_and_vacuum(log_ids)
            dumped = len(log_ids)
            await db.log_event("INFO", "LOGS_ARCHIVED", "system", f"Archived {dumped} logs & VACUUMed DB")

    return {"expired_cleaned": len(expired), "logs_dumped": dumped}


async def _maintenance_loop() -> None:
    while True:
        try:
            await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
            await run_maintenance(force_log_dump=False)
        except asyncio.CancelledError:
            break
        except Exception as exc:
            print(f"[MAINTENANCE ERROR] {exc}", flush=True)


async def _async_services_runner() -> None:
    try:
        print("[1/2] Initializing Turso DB...", flush=True)
        await db.start()
        print("[2/2] Starting Kurigram MTProto workers...", flush=True)
        active_count = 0
        for idx, client in enumerate(stream_clients, start=1):
            try:
                await asyncio.wait_for(client.start(), timeout=35.0)
                active_count += 1
                print(f"      Worker {idx}/{len(stream_clients)} connected.", flush=True)
            except Exception as exc:
                print(f"      [WORKER {idx} ERROR] {type(exc).__name__}: {exc}", flush=True)
        await db.log_event("INFO", "SPACE_BOOT", "system", f"Online with {active_count}/{len(stream_clients)} worker(s)")
    except Exception as exc:
        print(f"[BOOT ERROR] {type(exc).__name__}: {exc}", flush=True)

    asyncio.create_task(_maintenance_loop())
    while True:
        await asyncio.sleep(3600)


def _start_background_loop() -> None:
    global _bg_loop
    loop = asyncio.new_event_loop()
    _bg_loop = loop
    asyncio.set_event_loop(loop)
    loop.run_until_complete(_async_services_runner())


def _client_ip(request: Request) -> str:
    xff = request.headers.get("x-forwarded-for")
    if xff:
        return xff.split(",")[0].strip()
    return request.client.host if request.client else "unknown"


async def health_handler(request: Request):
    return JSONResponse({"status": "ok", "ts": int(time.time())})


async def dl_endpoint(request: Request):
    return await serve_telegram_file(
        request,
        token=request.path_params["token"],
        want_inline=False,
        quality=request.query_params.get("q", ""),
        pin=request.query_params.get("pin", ""),
    )


async def stream_endpoint(request: Request):
    return await serve_telegram_file(
        request,
        token=request.path_params["token"],
        want_inline=True,
        quality=request.query_params.get("q", ""),
        pin=request.query_params.get("pin", ""),
    )


async def watch_endpoint(request: Request):
    token = request.path_params["token"]
    link = await db.get_active_link(token)
    if not link:
        return templates.TemplateResponse(
            request=request,
            name="error.html",
            context={"code": 410, "title": "Link Expired", "message": "This link has expired or reached its download limit."},
            status_code=410,
        )
    final_slug = link["file_name"]
    enc = urllib.parse.quote(final_slug, safe="")
    variants = link.get("variants") or {}
    quality_options = ["original"] + [q for q in ("720p", "480p", "360p", "240p", "144p") if q in variants]

    return templates.TemplateResponse(
        request=request,
        name="watch.html",
        context={
            "token": token,
            "encoded_slug": enc,
            "file_name": final_slug,
            "file_size_str": _format_size(int(link["file_size"])),
            "media_kind": link["media_kind"],
            "downloads": link["downloads"],
            "has_pin": bool(link.get("password_hash")),
            "seconds_left": max(0, int(link["expires_at"]) - int(time.time())),
            "quality_options": quality_options,
            "base_url": BASE_URL,
        },
    )


async def admin_login_get(request: Request):
    if session_mgr.read_session(request):
        return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
    return templates.TemplateResponse(request=request, name="admin_login.html", context={"error": None})


async def admin_login_post(request: Request):
    form = await request.form()
    username = str(form.get("username", ""))
    password = str(form.get("password", ""))
    ip = _client_ip(request)
    if login_limiter.is_blocked(ip):
        return templates.TemplateResponse(
            request=request,
            name="admin_login.html",
            context={"error": "Locked for 15 minutes due to repeated failed logins."},
            status_code=429,
        )
    if not (hmac.compare_digest(username.strip(), ADMIN_USERNAME) and hmac.compare_digest(password, ADMIN_PASSWORD)):
        login_limiter.record_failure(ip)
        await db.log_event("WARN", "ADMIN_LOGIN_FAIL", ip, f"Attempt: {username[:24]}")
        return templates.TemplateResponse(
            request=request,
            name="admin_login.html",
            context={"error": "Invalid username or password."},
            status_code=401,
        )
    login_limiter.reset(ip)
    await db.log_event("INFO", "ADMIN_LOGIN_OK", ip, "Admin authenticated")
    resp = RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)
    resp.set_cookie(
        key=session_mgr.COOKIE_NAME,
        value=session_mgr.create_session_token(ADMIN_USERNAME),
        max_age=session_mgr.MAX_AGE,
        httponly=True,
        secure=BASE_URL.startswith("https://"),
        samesite="strict",
    )
    return resp


async def admin_logout(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    resp = RedirectResponse(url="/admin/login", status_code=status.HTTP_303_SEE_OTHER)
    resp.delete_cookie(session_mgr.COOKIE_NAME)
    return resp


async def admin_panel(request: Request):
    sess = session_mgr.require_admin(request)
    q = request.query_params.get("q", "").strip()[:80]
    data = await db.get_dashboard_data(search=q)
    free_tmp = shutil.disk_usage("/tmp").free
    return templates.TemplateResponse(
        request=request,
        name="admin_dashboard.html",
        context={
            "csrf_token": sess["csrf"],
            "query": q,
            "now": data["now"],
            "tutorial_url": data["tutorial_url"],
            "free_tmp_str": _format_size(free_tmp),
            "stats": data["stats"],
            "links": data["links"],
            "users": data["users"],
            "logs": data["logs"],
            "format_size": _format_size,
            "base_url": BASE_URL,
        },
    )


async def admin_update_tutorial(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    tutorial_url = str(form.get("tutorial_url", "")).strip()[:300]
    await db.set_setting("tutorial_video_url", tutorial_url)
    await db.log_event("INFO", "TUTORIAL_UPDATED", "admin", tutorial_url[:120])
    return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)


async def admin_set_tier(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    tg_id = int(request.path_params["tg_id"])
    tier = str(form.get("tier", "free"))
    days = int(form.get("days", 30))
    clean_tier = "premium" if tier == "premium" else "free"
    await db.set_user_tier(tg_id, clean_tier, max(0, min(days, 3650)))
    await db.log_event("INFO", "TIER_UPDATED", "admin", f"tg:{tg_id} -> {clean_tier} ({days}d)")
    return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)


async def admin_ban_user(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    tg_id = int(request.path_params["tg_id"])
    state = await db.toggle_user_ban(tg_id)
    await db.log_event("WARN", "USER_BANNED" if state == 1 else "USER_UNBANNED", "admin", f"tg:{tg_id}")
    return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)


async def admin_revoke(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    token = request.path_params["token"]
    link = await db.get_active_link(token)
    if link:
        await delete_telegram_messages(int(link["target_chat_id"]), [int(link["bin_msg_id"])])
        await db.delete_links_by_tokens([token])
        await db.log_event("WARN", "LINK_REVOKED", "admin", link["file_name"])
    return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)


async def admin_dump_logs(request: Request):
    sess = session_mgr.require_admin(request)
    form = await request.form()
    session_mgr.verify_csrf(sess, str(form.get("csrf_token", "")))
    await run_maintenance(force_log_dump=True)
    return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER)


# --- Companion Gradio Web Console ---

CLAUDE_MINIMAL_CSS = """
.gradio-container { max-width: 960px !important; margin: 0 auto !important; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif !important; }
footer { visibility: hidden !important; }
"""


def _extract_file_path(file_obj) -> str | None:
    if not file_obj:
        return None
    if isinstance(file_obj, str):
        return file_obj
    if isinstance(file_obj, list) and file_obj:
        return _extract_file_path(file_obj[0])
    return getattr(file_obj, "name", None)


async def ui_upload_file(
    terms_accepted: bool,
    file_obj,
    custom_slug_input: str,
    expiry_label: str,
    burn_after_one: bool,
    access_pin: str,
    qualities: list[str],
    enable_hindi_dub: bool,
    progress: gr.Progress = gr.Progress(track_tqdm=True),
):
    if not terms_accepted:
        raise gr.Error("Please accept the Ownership & Research Terms checkbox first.")
    file_path = _extract_file_path(file_obj)
    if not file_path or not os.path.exists(file_path):
        raise gr.Error("Please select a file to upload.")
    if not _has_enough_disk():
        raise gr.Error("Server temporary storage is busy.")

    progress(0.10, desc="Preparing upload...")
    mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
    orig_name = sanitize_filename(os.path.basename(file_path), mime_type)
    final_slug = build_custom_slug(custom_slug_input, orig_name)
    file_size = os.path.getsize(file_path)
    media_kind = "video" if mime_type.startswith("video/") else ("audio" if mime_type.startswith("audio/") else "document")

    token = secrets.token_urlsafe(12)
    variants: dict[str, dict] = {}
    upload_path = file_path
    upload_name = final_slug
    dub_work_dir: str | None = None

    try:
        if enable_hindi_dub and media_kind == "video":
            if file_size > DUB_TEST_MAX_BYTES:
                raise gr.Error(f"Hindi dubbing test mode limit is {_format_size(DUB_TEST_MAX_BYTES)}.")
            dub_work_dir = tempfile.mkdtemp(prefix="ftl_ui_dub_")
            dub_name = f"Hindi_{os.path.splitext(final_slug)[0]}.mp4"
            dub_out = os.path.join(dub_work_dir, dub_name)

            async def _on_dub(pct: float, stage: str) -> None:
                progress(0.15 + pct * 0.45, desc=stage[:100])

            await dub_english_video_to_hindi(file_path, dub_out, _on_dub)
            upload_path = dub_out
            upload_name = dub_name
            file_size = os.path.getsize(dub_out)

        progress(0.65, desc=f"Uploading {upload_name} to Telegram...")
        if media_kind == "video":
            sent = await bot.send_video(chat_id=BIN_CHANNEL, video=upload_path, file_name=upload_name, caption=f"`{upload_name}`")
        elif media_kind == "audio":
            sent = await bot.send_audio(chat_id=BIN_CHANNEL, audio=upload_path, file_name=upload_name, caption=f"`{upload_name}`")
        else:
            sent = await bot.send_document(chat_id=BIN_CHANNEL, document=upload_path, file_name=upload_name, caption=f"`{upload_name}`")

        if media_kind == "video" and qualities:
            async def upload_variant(v_path: str, v_name: str, q_label: str) -> dict:
                v_msg = await bot.send_video(chat_id=BIN_CHANNEL, video=v_path, file_name=v_name, caption=f"`{v_name}` ({q_label})")
                return {
                    "msg_id": v_msg.id,
                    "chat_id": BIN_CHANNEL,
                    "file_name": v_name,
                    "size": os.path.getsize(v_path),
                    "mime_type": "video/mp4",
                }

            async def on_q_prog(pct: float, stage: str) -> None:
                progress(0.65 + pct * 0.25, desc=stage[:100])

            variants = await generate_quality_ladder(upload_path, upload_name, qualities, upload_variant, on_q_prog)

        progress(0.95, desc="Saving link metadata...")
        await db.create_link(
            token=token,
            slug=upload_name,
            bin_msg_id=sent.id,
            target_chat_id=BIN_CHANNEL,
            file_name=upload_name,
            file_size=file_size,
            mime_type=mime_type,
            media_kind=media_kind,
            creator_id=0,
            source_type="web_upload",
            ttl_seconds=EXPIRY_MAP.get(expiry_label, 86400),
            variants=variants,
            password_hash=hash_link_password(access_pin),
            max_downloads=1 if burn_after_one else 0,
        )
        progress(1.0, desc="Done!")
        enc = urllib.parse.quote(upload_name, safe="")
        return (
            f"{BASE_URL}/dl/{token}/{enc}",
            f"{BASE_URL}/watch/{token}/{enc}",
            f"Ready: **{upload_name}** ({_format_size(file_size)})",
        )
    finally:
        if dub_work_dir:
            shutil.rmtree(dub_work_dir, ignore_errors=True)


async def ui_hf_mirror(
    terms_accepted: bool,
    hf_url: str,
    ext_filter: str,
    progress: gr.Progress = gr.Progress(track_tqdm=True),
):
    if not terms_accepted:
        raise gr.Error("Please accept the Ownership & Research Terms checkbox first.")
    if not hf_url.strip():
        raise gr.Error("Enter a Hugging Face Model or Dataset URL.")

    logs: list[str] = []
    q_events: asyncio.Queue[tuple[float, str] | None] = asyncio.Queue()

    async def status_cb(pct: float, msg: str) -> None:
        logs.append(msg)
        await q_events.put((pct, msg))

    async def upload_cb(local_path: str, part_name: str) -> dict:
        await q_events.put((0.80, f"Uploading `{part_name}`..."))
        sent = await bot.send_document(chat_id=BIN_CHANNEL, document=local_path, file_name=part_name, caption=f"HF Mirror: `{part_name}`")
        return {"msg_id": sent.id, "chat_id": BIN_CHANNEL, "file_name": part_name}

    async def _runner():
        try:
            return await mirror_hf_target(hf_url, ext_filter, upload_cb, status_cb)
        finally:
            await q_events.put(None)

    task = asyncio.create_task(_runner())
    try:
        while True:
            item = await q_events.get()
            if item is None:
                break
            pct, desc = item
            progress(pct, desc=desc[:100])
            yield f"Working: {desc}", "\n".join(logs[-15:])
        uploaded = await task
        progress(1.0, desc="Complete!")
        yield f"Mirrored **{len(uploaded)}** file(s) to Telegram storage.", "\n".join(logs[-15:])
    except Exception as exc:
        if not task.done():
            task.cancel()
        raise gr.Error(str(exc))


def build_gradio_app() -> gr.Blocks:
    with gr.Blocks(title="Telegram FileToLink & Dubbing Console") as blocks:
        _zerogpu_btn = gr.Button("init-gpu", visible=False)
        _zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)

        gr.Markdown(
            f"# Telegram FileToLink, Multi-Quality & Hindi Dub Console\n"
            f"Primary workflow runs in your Telegram bot with live progress bars · Web Streamer: `{BASE_URL}` · Admin: `{BASE_URL}/admin`"
        )
        terms_chk = gr.Checkbox(label="I confirm I have rights to share/process this media for research & educational use.", value=False)

        with gr.Tabs():
            with gr.Tab("Upload & Dub (< 5 MB Test)"):
                file_in = gr.File(label="Select File", type="filepath")
                with gr.Row():
                    slug_in = gr.Textbox(label="Custom URL Title (Optional)", placeholder="e.g. english-clip-01")
                    expiry_in = gr.Dropdown(label="Lifespan", choices=list(EXPIRY_MAP.keys()), value="24 Hours")
                with gr.Row():
                    pin_in = gr.Textbox(label="Optional PIN", type="password")
                    burn_chk = gr.Checkbox(label="Burn after 1 download", value=False)
                    dub_chk = gr.Checkbox(label="Convert English → Hindi (< 5 MB test)", value=False)
                qualities_in = gr.CheckboxGroup(
                    label="Video Quality Variants",
                    choices=["720p", "480p", "360p", "240p", "144p"],
                    value=[],
                )
                upload_btn = gr.Button("Process & Generate Links", variant="primary")
                out_status = gr.Markdown("")
                out_dl = gr.Textbox(label="Direct Download URL", interactive=False)
                out_watch = gr.Textbox(label="Stream / Watch URL", interactive=False)
                upload_btn.click(
                    ui_upload_file,
                    inputs=[terms_chk, file_in, slug_in, expiry_in, burn_chk, pin_in, qualities_in, dub_chk],
                    outputs=[out_dl, out_watch, out_status],
                )

            with gr.Tab("HF Mirror"):
                hf_url_in = gr.Textbox(label="Hugging Face Model / Dataset URL", placeholder="https://huggingface.co/datasets/org/repo")
                ext_in = gr.Textbox(label="Extension Filter (Optional)", placeholder=".parquet or .gguf")
                hf_btn = gr.Button("Mirror to Telegram", variant="primary")
                hf_summary = gr.Markdown("")
                hf_logs = gr.Textbox(label="Progress Log", lines=8, interactive=False)
                hf_btn.click(ui_hf_mirror, inputs=[terms_chk, hf_url_in, ext_in], outputs=[hf_summary, hf_logs])

    return blocks


demo = build_gradio_app()


def main() -> None:
    threading.Thread(target=_start_background_loop, daemon=True).start()

    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        ssr_mode=False,
        prevent_thread_lock=True,
    )

    live_app = demo.app
    priority_routes = [
        StarletteRoute("/health", health_handler, methods=["GET", "HEAD"]),
        StarletteRoute("/dl/{token}/{filename}", dl_endpoint, methods=["GET", "HEAD"]),
        StarletteRoute("/stream/{token}/{filename}", stream_endpoint, methods=["GET", "HEAD"]),
        StarletteRoute("/watch/{token}/{filename}", watch_endpoint, methods=["GET"]),
        StarletteRoute("/admin/login", admin_login_get, methods=["GET"]),
        StarletteRoute("/admin/login", admin_login_post, methods=["POST"]),
        StarletteRoute("/admin/logout", admin_logout, methods=["POST"]),
        StarletteRoute("/admin", admin_panel, methods=["GET"]),
        StarletteRoute("/admin/settings/tutorial", admin_update_tutorial, methods=["POST"]),
        StarletteRoute("/admin/users/{tg_id:int}/tier", admin_set_tier, methods=["POST"]),
        StarletteRoute("/admin/users/{tg_id:int}/toggle-ban", admin_ban_user, methods=["POST"]),
        StarletteRoute("/admin/links/{token}/revoke", admin_revoke, methods=["POST"]),
        StarletteRoute("/admin/logs/dump", admin_dump_logs, methods=["POST"]),
    ]
    for route in reversed(priority_routes):
        live_app.router.routes.insert(0, route)

    live_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
    demo.app = SecurityHeadersMiddleware(live_app)
    live_app.build_middleware_stack()

    demo.block_thread()


if __name__ == "__main__":
    main()