File size: 63,765 Bytes
e6c58c8
 
322cbb7
 
 
 
 
 
 
 
e6c58c8
 
 
 
 
 
 
 
129096b
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bde9ae
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
9bde9ae
e6c58c8
 
 
 
 
 
 
 
 
9bde9ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
 
129096b
e6c58c8
322cbb7
e6c58c8
 
 
9bde9ae
 
129096b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
322cbb7
 
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
 
 
 
 
 
 
 
9bde9ae
 
 
 
129096b
 
 
 
 
 
9bde9ae
e6c58c8
7d5d56b
 
 
 
129096b
7d5d56b
322cbb7
7d5d56b
 
 
 
 
 
 
 
 
 
 
129096b
 
7d5d56b
 
129096b
 
7d5d56b
 
 
129096b
7d5d56b
 
 
 
 
 
 
 
 
 
129096b
 
7d5d56b
 
129096b
 
7d5d56b
 
 
 
 
 
e6c58c8
322cbb7
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bca2797
322cbb7
 
bca2797
 
 
 
 
 
 
322cbb7
 
 
bca2797
322cbb7
 
 
 
 
 
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
 
129096b
322cbb7
129096b
 
322cbb7
e6c58c8
 
7d5d56b
322cbb7
7d5d56b
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129096b
 
 
e6c58c8
 
129096b
e6c58c8
 
 
 
 
129096b
e6c58c8
129096b
322cbb7
129096b
 
e6c58c8
129096b
 
e6c58c8
 
 
 
 
 
 
322cbb7
e6c58c8
 
 
322cbb7
 
 
129096b
322cbb7
 
 
 
129096b
 
 
 
 
 
 
 
 
 
 
 
322cbb7
 
129096b
9bde9ae
e6c58c8
 
129096b
322cbb7
 
 
 
e6c58c8
129096b
 
e6c58c8
 
 
 
 
 
322cbb7
129096b
322cbb7
e6c58c8
 
 
 
 
322cbb7
e6c58c8
 
322cbb7
 
 
e6c58c8
322cbb7
bca2797
 
 
 
 
 
 
322cbb7
 
 
 
 
e6c58c8
 
 
 
 
129096b
e6c58c8
 
129096b
e6c58c8
 
 
 
 
 
322cbb7
bca2797
 
 
 
 
322cbb7
bca2797
322cbb7
 
 
 
bca2797
129096b
322cbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bca2797
322cbb7
 
 
 
bca2797
 
 
 
322cbb7
 
 
 
 
 
 
 
 
bca2797
 
322cbb7
 
bca2797
322cbb7
 
 
 
 
 
e6c58c8
 
 
 
322cbb7
e6c58c8
 
 
7d5d56b
e6c58c8
322cbb7
e6c58c8
322cbb7
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
7d5d56b
e6c58c8
 
 
7d5d56b
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
322cbb7
 
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
 
 
 
322cbb7
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
9bde9ae
e6c58c8
 
322cbb7
e6c58c8
 
 
 
 
 
 
 
7d5d56b
e6c58c8
 
 
 
 
 
7d5d56b
9bde9ae
 
e6c58c8
 
7d5d56b
 
 
 
e6c58c8
 
7d5d56b
e6c58c8
 
7d5d56b
 
e6c58c8
 
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
322cbb7
e6c58c8
 
 
 
322cbb7
e6c58c8
 
 
 
 
 
322cbb7
e6c58c8
322cbb7
e6c58c8
 
7d5d56b
 
e6c58c8
 
 
322cbb7
7d5d56b
 
322cbb7
e6c58c8
 
 
322cbb7
e6c58c8
 
 
322cbb7
 
e6c58c8
 
322cbb7
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
7d5d56b
322cbb7
e6c58c8
 
322cbb7
7d5d56b
e6c58c8
322cbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
322cbb7
e6c58c8
 
 
 
7d5d56b
 
 
e6c58c8
 
7d5d56b
 
 
 
e6c58c8
7d5d56b
 
 
 
 
 
 
 
 
 
 
e6c58c8
 
 
322cbb7
 
 
e6c58c8
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
e6c58c8
 
7d5d56b
e6c58c8
 
 
 
322cbb7
 
 
 
 
e6c58c8
 
322cbb7
 
9bde9ae
322cbb7
e6c58c8
 
 
 
 
 
 
 
 
 
129096b
e6c58c8
 
 
7d5d56b
 
 
 
e6c58c8
 
 
 
 
7d5d56b
 
322cbb7
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
322cbb7
 
 
 
 
 
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6c58c8
322cbb7
 
 
9bde9ae
7d5d56b
9bde9ae
 
322cbb7
 
 
 
 
9bde9ae
322cbb7
129096b
9bde9ae
 
 
322cbb7
 
 
 
 
 
 
129096b
 
322cbb7
129096b
322cbb7
 
 
 
 
 
 
 
 
 
 
9bde9ae
129096b
9bde9ae
129096b
 
9bde9ae
 
129096b
9bde9ae
 
 
 
129096b
 
 
 
 
 
 
9bde9ae
 
129096b
9bde9ae
 
 
 
 
 
 
 
 
 
322cbb7
9bde9ae
 
322cbb7
9bde9ae
322cbb7
129096b
 
9bde9ae
129096b
9bde9ae
322cbb7
129096b
 
 
322cbb7
129096b
 
 
322cbb7
 
129096b
 
 
 
 
 
 
 
e6c58c8
322cbb7
 
 
129096b
 
322cbb7
 
 
 
 
 
129096b
 
322cbb7
 
129096b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
129096b
 
 
 
 
 
 
7d5d56b
129096b
 
 
 
7d5d56b
 
129096b
 
 
 
 
 
 
 
 
 
 
7d5d56b
129096b
 
 
 
 
 
 
 
7d5d56b
 
9bde9ae
 
 
 
 
 
 
322cbb7
 
129096b
 
 
 
 
 
 
 
 
 
9bde9ae
 
 
322cbb7
 
 
129096b
9bde9ae
129096b
9bde9ae
 
 
7d5d56b
 
 
 
 
e6c58c8
7d5d56b
322cbb7
7d5d56b
 
 
 
322cbb7
7d5d56b
 
 
322cbb7
7d5d56b
 
322cbb7
7d5d56b
 
 
 
322cbb7
7d5d56b
 
322cbb7
7d5d56b
322cbb7
7d5d56b
 
 
322cbb7
7d5d56b
 
322cbb7
7d5d56b
 
 
 
322cbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d5d56b
 
 
 
 
 
 
 
322cbb7
 
7d5d56b
322cbb7
7d5d56b
 
322cbb7
 
 
 
 
 
 
7d5d56b
322cbb7
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
7d5d56b
 
322cbb7
7d5d56b
 
 
e6c58c8
7d5d56b
 
 
 
 
322cbb7
 
 
7d5d56b
 
 
 
 
322cbb7
7d5d56b
 
e6c58c8
7d5d56b
 
 
 
322cbb7
7d5d56b
 
 
 
 
 
 
 
322cbb7
7d5d56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322cbb7
 
 
7d5d56b
 
 
 
 
322cbb7
7d5d56b
 
e6c58c8
7d5d56b
 
 
 
322cbb7
7d5d56b
 
 
 
 
 
 
 
322cbb7
7d5d56b
 
 
322cbb7
 
7d5d56b
 
 
 
 
 
322cbb7
7d5d56b
 
e6c58c8
7d5d56b
 
e6c58c8
7d5d56b
 
e6c58c8
7d5d56b
 
e6c58c8
 
7d5d56b
 
 
 
 
 
e6c58c8
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
"""
SubSource Subtitle Downloader Module for Telegram Bot.
Provides:
- Movie and TV series search with automatic Season grouping (Season 1, 2, etc.)
- Interactive Season selection sub-menu for TV series
- Interactive subtitle pagination with continuous numbering across pages
- Per-language country flag emojis for all SubSource languages (including 'All' mode)
- Automatic ZIP cleanup (leaves only extracted subtitle files in /downloads)
- Multi-file series pack handling (sends all episode subtitle files to Telegram)
- Post-download confirmation prompt (choice to send to chat or keep on server)
"""

import asyncio
import html
import io
import math
import os
import re
import tempfile
import time
import zipfile
from pathlib import Path
from typing import Any

import requests
from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram.types import (
    CallbackQuery,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    LinkPreviewOptions,
    Message,
)

from .. import LOGGER
from ..helper.ext_utils.bot_utils import new_task

try:
    from app import DOWNLOAD_PATH
except ImportError:
    DOWNLOAD_PATH = os.getenv("QBITTORRENT_SAVE_PATH", "/downloads")

# ==============================================================================
# KONFIGURASI SUBSOURCE API & BAHASA
# ==============================================================================
API_KEY = os.getenv(
    "SUBSOURCE_API_KEY",
    "sk_e643a06714b5b587c9fac35d263499df0729c68471ebb848576072228ba52c9b",
)
BASE_URL = os.getenv("SUBSOURCE_BASE_URL", "https://api.subsource.net/api/v1")

HEADERS = {
    "X-API-Key": API_KEY,
    "Accept": "application/json",
    "User-Agent": "TelegramBot-SubSource/1.0",
}

# Bahasa yang didukung untuk filter cepat tombol navigasi
LANGUAGE_OPTIONS = [
    ("id", "indonesian", "🇮🇩 Indo"),
    ("en", "english", "🇬🇧 Eng"),
    ("all", "all", "🌐 Semua"),
]

LANG_CODE_TO_NAME = {code: name for code, name, _ in LANGUAGE_OPTIONS}
LANG_NAME_TO_CODE = {name: code for code, name, _ in LANGUAGE_OPTIONS}

# Pemetaan lengkap bahasa ke emoji bendera negara dari API SubSource
LANGUAGE_FLAG_MAP: dict[str, str] = {
    "indonesian": "🇮🇩",
    "id": "🇮🇩",
    "english": "🇬🇧",
    "en": "🇬🇧",
    "arabic": "🇸🇦",
    "ar": "🇸🇦",
    "spanish": "🇪🇸",
    "es": "🇪🇸",
    "french": "🇫🇷",
    "fr": "🇫🇷",
    "german": "🇩🇪",
    "de": "🇩🇪",
    "italian": "🇮🇹",
    "it": "🇮🇹",
    "portuguese": "🇵🇹",
    "pt": "🇵🇹",
    "portuguese-br": "🇧🇷",
    "brazilian": "🇧🇷",
    "russian": "🇷🇺",
    "ru": "🇷🇺",
    "japanese": "🇯🇵",
    "ja": "🇯🇵",
    "korean": "🇰🇷",
    "ko": "🇰🇷",
    "chinese": "🇨🇳",
    "zh": "🇨🇳",
    "chinese-traditional": "🇹🇼",
    "turkish": "🇹🇷",
    "tr": "🇹🇷",
    "vietnamese": "🇻🇳",
    "vi": "🇻🇳",
    "thai": "🇹🇭",
    "th": "🇹🇭",
    "hindi": "🇮🇳",
    "hi": "🇮🇳",
    "bengali": "🇧🇩",
    "bn": "🇧🇩",
    "malay": "🇲🇾",
    "ms": "🇲🇾",
    "dutch": "🇳🇱",
    "nl": "🇳🇱",
    "polish": "🇵🇱",
    "pl": "🇵🇱",
    "swedish": "🇸🇪",
    "sv": "🇸🇪",
    "norwegian": "🇳🇴",
    "no": "🇳🇴",
    "danish": "🇩🇰",
    "da": "🇩🇰",
    "finnish": "🇫🇮",
    "fi": "🇫🇮",
    "greek": "🇬🇷",
    "el": "🇬🇷",
    "hebrew": "🇮🇱",
    "he": "🇮🇱",
    "romanian": "🇷🇴",
    "ro": "🇷🇴",
    "hungarian": "🇭🇺",
    "hu": "🇭🇺",
    "czech": "🇨🇿",
    "cs": "🇨🇿",
    "slovak": "🇸🇰",
    "sk": "🇸🇰",
    "ukrainian": "🇺🇦",
    "uk": "🇺🇦",
    "bulgarian": "🇧🇬",
    "bg": "🇧🇬",
    "croatian": "🇭🇷",
    "hr": "🇭🇷",
    "serbian": "🇷🇸",
    "sr": "🇷🇸",
    "bosnian": "🇧🇦",
    "bs": "🇧🇦",
    "slovenian": "🇸🇮",
    "sl": "🇸🇮",
    "tagalog": "🇵🇭",
    "filipino": "🇵🇭",
    "tl": "🇵🇭",
    "persian": "🇮🇷",
    "farsi": "🇮🇷",
    "farsi_persian": "🇮🇷",
    "fa": "🇮🇷",
    "urdu": "🇵🇰",
    "ur": "🇵🇰",
    "tamil": "🇮🇳",
    "ta": "🇮🇳",
    "telugu": "🇮🇳",
    "te": "🇮🇳",
    "malayalam": "🇮🇳",
    "ml": "🇮🇳",
    "kannada": "🇮🇳",
    "kn": "🇮🇳",
    "marathi": "🇮🇳",
    "mr": "🇮🇳",
    "estonian": "🇪🇪",
    "et": "🇪🇪",
    "latvian": "🇱🇻",
    "lv": "🇱🇻",
    "lithuanian": "🇱🇹",
    "lt": "🇱🇹",
    "albanian": "🇦🇱",
    "sq": "🇦🇱",
    "macedonian": "🇲🇰",
    "mk": "🇲🇰",
    "icelandic": "🇮🇸",
    "is": "🇮🇸",
    "georgian": "🇬🇪",
    "ka": "🇬🇪",
    "armenian": "🇦🇲",
    "hy": "🇦🇲",
    "azerbaijani": "🇦🇿",
    "az": "🇦🇿",
    "kazakh": "🇰🇿",
    "kk": "🇰🇿",
    "uzbek": "🇺🇿",
    "uz": "🇺🇿",
    "mongolian": "🇲🇳",
    "mn": "🇲🇳",
    "burmese": "🇲🇲",
    "my": "🇲🇲",
    "khmer": "🇰🇭",
    "km": "🇰🇭",
    "lao": "🇱🇦",
    "lo": "🇱🇦",
    "sinhala": "🇱🇰",
    "si": "🇱🇰",
    "nepali": "🇳🇵",
    "ne": "🇳🇵",
    "swahili": "🇹🇿",
    "sw": "🇹🇿",
    "afrikaans": "🇿🇦",
    "af": "🇿🇦",
}

SUB_EXTENSIONS = (".srt", ".ass", ".vtt", ".sub")
ITEMS_PER_PAGE = 5
MOVIE_ITEMS_PER_PAGE = 6
SESSION_TTL_SECONDS = 3600  # 1 jam
AUTO_CLOSE_SECONDS = 120    # 2 menit batas auto-close jika tidak ada aktivitas

# Penyimpanan sesi pencarian: key = f"{chat_id}_{message_id}"
SEARCH_SESSIONS: dict[str, dict[str, Any]] = {}
# Cache subtitle per film & bahasa: key = f"{movie_id}_{lang}"
SUBTITLE_CACHE: dict[str, dict[str, Any]] = {}
# Cache file subtitle yang telah diunduh: key = str(sub_id)
DOWNLOADED_SUBS: dict[str, dict[str, Any]] = {}
# Task auto-close pesan subtitle per session: key = f"{chat_id}_{message_id}"
AUTO_CLOSE_TASKS: dict[str, asyncio.Task] = {}


def cancel_auto_close(chat_id: int, message_id: int) -> None:
    """Membatalkan task auto-close jika ada interaksi baru atau pesan ditutup."""
    key = f"{chat_id}_{message_id}"
    task = AUTO_CLOSE_TASKS.pop(key, None)
    if task and not task.done():
        task.cancel()


def schedule_auto_close(
    client: Client,
    chat_id: int,
    message_id: int,
    delay: int = AUTO_CLOSE_SECONDS,
    temp_zip_to_clean: str | None = None,
) -> None:
    """Menjadwalkan penutupan otomatis (hapus pesan) setelah delay detik tanpa aktivitas."""
    key = f"{chat_id}_{message_id}"
    cancel_auto_close(chat_id, message_id)

    async def _auto_close_worker():
        try:
            await asyncio.sleep(delay)
            # Bersihkan sesi dari memori
            SEARCH_SESSIONS.pop(key, None)
            AUTO_CLOSE_TASKS.pop(key, None)

            # Hapus file temporary zip jika ada
            if temp_zip_to_clean and os.path.exists(temp_zip_to_clean):
                try:
                    os.remove(temp_zip_to_clean)
                except Exception:
                    pass

            # Hapus pesan dari chat Telegram agar chat tetap bersih
            try:
                await client.delete_messages(chat_id=chat_id, message_ids=message_id)
                LOGGER.info("Pesan %s berhasil ditutup otomatis setelah %s detik tanpa aktivitas.", key, delay)
            except Exception as del_err:
                LOGGER.debug("Gagal auto-delete pesan %s: %s", key, del_err)
        except asyncio.CancelledError:
            pass
        except Exception as exc:
            LOGGER.debug("Exception di auto_close_worker (%s): %s", key, exc)

    AUTO_CLOSE_TASKS[key] = asyncio.create_task(_auto_close_worker())


def get_language_flag(lang_str: str | None) -> str:
    """Mengembalikan emoji bendera negara berdasarkan nama atau kode bahasa SubSource."""
    if not lang_str:
        return "🌐"
    cleaned = lang_str.strip().lower()
    return LANGUAGE_FLAG_MAP.get(cleaned, "🌐")


def natural_sort_key(s: str) -> list[Any]:
    """Sort key untuk mengurutkan file episode secara alami (misal ep 1, ep 2, ep 10)."""
    return [int(text) if text.isdigit() else text.lower() for text in re.split(r"(\d+)", s)]


def get_download_dir() -> str:
    """Mendapatkan direktori tujuan penyimpanan unduhan subtitle."""
    target = os.getenv("SUB_DOWNLOAD_DIR") or DOWNLOAD_PATH or "/downloads"
    try:
        os.makedirs(target, exist_ok=True)
        return target
    except Exception as exc:
        LOGGER.warning("Gagal membuat direktori %s: %s. Fallback ke downloads lokal.", target, exc)
        fallback = os.path.abspath("downloads")
        os.makedirs(fallback, exist_ok=True)
        return fallback


def clean_filename(filename: str) -> str:
    """Membersihkan karakter terlarang dari nama file."""
    return re.sub(r'[\\/*?:"<>|]', "", filename).strip()


def extract_imdb_id(user_input: str) -> str | None:
    """Mengekstrak ID IMDb (misal: tt1375666) dari teks atau URL IMDb."""
    match = re.search(r"(tt\d{7,8})", user_input.strip())
    return match.group(1) if match else None


def format_bytes(size: int | float | None) -> str:
    """Format ukuran byte ke satuan yang mudah dibaca manusia."""
    if size is None or size <= 0:
        return "0 B"
    power = 1024
    n = 0
    labels = {0: "B", 1: "KiB", 2: "MiB", 3: "GiB"}
    val = float(size)
    while val >= power and n < len(labels) - 1:
        val /= power
        n += 1
    return f"{val:.2f} {labels[n]}"


def clean_html_text(text: str) -> str:
    """
    Membersihkan teks dari entitas HTML ganda/karakter ilegal bawaan API,
    dan meng-escape untuk Telegram HTML parser agar tidak menyebabkan 400 Bad Request.
    """
    if not text:
        return ""
    unescaped = html.unescape(str(text))
    stripped = re.sub(r"<[^>]+>", "", unescaped)
    return html.escape(stripped.strip())


def cleanup_old_sessions() -> None:
    """Membersihkan sesi lama yang sudah kadaluarsa dari memori."""
    now = time.time()
    expired_keys = [
        k for k, v in SEARCH_SESSIONS.items() if now - v.get("timestamp", 0) > SESSION_TTL_SECONDS
    ]
    for k in expired_keys:
        SEARCH_SESSIONS.pop(k, None)

    expired_dl = [
        k for k, v in DOWNLOADED_SUBS.items() if now - v.get("timestamp", 0) > SESSION_TTL_SECONDS
    ]
    for k in expired_dl:
        item = DOWNLOADED_SUBS.pop(k, None)
        if item and item.get("zip_path") and os.path.exists(item["zip_path"]):
            try:
                os.remove(item["zip_path"])
            except Exception:
                pass


async def safe_edit_message(
    target: Message | CallbackQuery,
    text: str,
    reply_markup: InlineKeyboardMarkup | None = None,
    auto_close: bool = True,
) -> bool:
    """Mengubah teks pesan Telegram secara aman dengan fallback ke plain text jika HTML error."""
    msg = target.message if isinstance(target, CallbackQuery) else target
    if len(text) > 4000:
        text = text[:3850] + "\n... [Teks dipotong karena melebihi batas Telegram]"

    try:
        await msg.edit_text(
            text,
            reply_markup=reply_markup,
            link_preview_options=LinkPreviewOptions(is_disabled=True),
            parse_mode=ParseMode.HTML,
        )
        if auto_close and hasattr(msg, "_client") and msg._client:
            schedule_auto_close(msg._client, msg.chat.id, msg.id)
        return True
    except MessageNotModified:
        if auto_close and hasattr(msg, "_client") and msg._client:
            schedule_auto_close(msg._client, msg.chat.id, msg.id)
        return True
    except FloodWait as exc:
        await asyncio.sleep(int(exc.value) + 1)
        return await safe_edit_message(target, text, reply_markup=reply_markup, auto_close=auto_close)
    except Exception as exc:
        LOGGER.warning("safe_edit_message: gagal kirim HTML (%s), mencoba plain text...", exc)
        try:
            plain_text = re.sub(r"<[^>]+>", "", text)
            await msg.edit_text(
                plain_text,
                reply_markup=reply_markup,
                link_preview_options=LinkPreviewOptions(is_disabled=True),
                parse_mode=None,
            )
            if auto_close and hasattr(msg, "_client") and msg._client:
                schedule_auto_close(msg._client, msg.chat.id, msg.id)
            return True
        except MessageNotModified:
            if auto_close and hasattr(msg, "_client") and msg._client:
                schedule_auto_close(msg._client, msg.chat.id, msg.id)
            return True
        except Exception as fallback_exc:
            LOGGER.error("safe_edit_message fallback juga gagal: %s", fallback_exc)
            return False


# ==============================================================================
# API & DATA STRUCTURING (SERIES & SEASON GROUPING)
# ==============================================================================
def search_movies(query: str, imdb_id: str | None = None) -> list[dict[str, Any]]:
    """Mencari film/serial di API SubSource berdasarkan judul atau IMDb ID."""
    url = f"{BASE_URL}/movies/search"

    if imdb_id:
        params = {"searchType": "imdb", "imdb": imdb_id}
    else:
        params = {"searchType": "text", "q": query}

    try:
        response = requests.get(url, headers=HEADERS, params=params, timeout=15)
        if response.status_code == 400 and not imdb_id:
            for fallback_key in ["query", "search", "title"]:
                res_fallback = requests.get(
                    url, headers=HEADERS, params={"searchType": "text", fallback_key: query}, timeout=15
                )
                if res_fallback.status_code == 200:
                    response = res_fallback
                    break

        if response.status_code != 200:
            LOGGER.error("SubSource movie search error status %s: %s", response.status_code, response.text)
            return []

        data = response.json()
        if isinstance(data, dict):
            items = data.get("data", data.get("results", []))
        elif isinstance(data, list):
            items = data
        else:
            items = []

        return items if isinstance(items, list) else [items]
    except Exception as exc:
        LOGGER.error("Exception in search_movies: %s", exc)
        return []


def group_movies_and_series(raw_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """
    Mengelompokkan hasil pencarian SubSource:
    - Serial TV dengan musim berbeda digabungkan ke 1 entri judul dengan sub-daftar seasons.
    - Film biasa tetap sebagai entri tersendiri.
    """
    grouped: list[dict[str, Any]] = []
    series_map: dict[str, dict[str, Any]] = {}

    for m in raw_items:
        m_type = (m.get("type") or "movie").lower()
        season = m.get("season")
        is_tv = (m_type in ("tvseries", "tv", "show")) or (season is not None)

        if is_tv:
            imdb_id = m.get("imdbId")
            clean_title = (m.get("title") or "").strip().lower()
            year = m.get("releaseYear") or m.get("year", "")
            key = f"imdb_{imdb_id}" if imdb_id else f"title_{clean_title}_{year}"

            if key in series_map:
                series_map[key]["seasons"].append(m)
            else:
                entry = {
                    "is_series": True,
                    "group_id": key,
                    "title": m.get("title") or m.get("name", "Unknown"),
                    "releaseYear": year,
                    "imdbId": imdb_id,
                    "type": "tvseries",
                    "seasons": [m],
                }
                series_map[key] = entry
                grouped.append(entry)
        else:
            m_copy = dict(m)
            m_copy["is_series"] = False
            grouped.append(m_copy)

    # Urutkan season untuk setiap series (Season 1, 2, ...) dan abaikan Season 0 jika ada season > 0
    for g in grouped:
        if g.get("is_series"):
            valid_seasons = [
                s for s in g["seasons"]
                if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0
            ]
            if valid_seasons:
                g["seasons"] = valid_seasons

            def season_sort_key(s: dict[str, Any]) -> int:
                s_val = s.get("season")
                try:
                    return int(s_val) if s_val is not None else 999
                except Exception:
                    return 999

            g["seasons"].sort(key=season_sort_key)

    return grouped


def get_subtitles(movie_id: int, language: str = "indonesian") -> list[dict[str, Any]]:
    """Mengambil daftar subtitle dari API SubSource untuk movie_id tertentu."""
    cache_key = f"{movie_id}_{language.lower()}"
    cached = SUBTITLE_CACHE.get(cache_key)
    if cached and time.time() - cached.get("timestamp", 0) < 600:
        return cached.get("subtitles", [])

    url = f"{BASE_URL}/subtitles"
    params: dict[str, Any] = {
        "movieId": movie_id,
        "limit": 100,
        "sort": "popular",
    }

    if language.lower() != "all":
        params["language"] = language.lower()

    try:
        response = requests.get(url, headers=HEADERS, params=params, timeout=15)
        if response.status_code != 200:
            LOGGER.error("SubSource get_subtitles error status %s: %s", response.status_code, response.text)
            return []

        data = response.json()
        subs = data.get("data", []) if isinstance(data, dict) else data
        if not isinstance(subs, list):
            subs = []

        if language.lower() != "all":
            subs = [
                s for s in subs
                if (s.get("language") or "").strip().lower() == language.lower()
            ]

        SUBTITLE_CACHE[cache_key] = {"subtitles": subs, "timestamp": time.time()}
        return subs
    except Exception as exc:
        LOGGER.error("Exception in get_subtitles: %s", exc)
        return []


def download_subtitle_file(subtitle_id: int, movie_title: str = "movie") -> dict[str, Any]:
    """
    Mengunduh file arsip ZIP subtitle dari SubSource API:
    - Mengekstrak semua file subtitle (.srt, .ass, dll) ke /downloads
    - File ZIP diunduh ke folder temporary OS (bukan di /downloads)
    - Mengurutkan file episode secara alami (Episode 1, 2, ... 25)
    - Jika series pack (> 1 file), path file ZIP disimpan sementara untuk dikirim langsung ke Telegram jika diminta
    - Jika single movie (1 file), file ZIP temporary langsung dihapus
    - Mengembalikan daftar seluruh file subtitle yang diekstrak.
    """
    url = f"{BASE_URL}/subtitles/{subtitle_id}/download"
    try:
        response = requests.get(url, headers=HEADERS, stream=True, timeout=40)
    except Exception as exc:
        return {"ok": False, "error": f"Koneksi ke SubSource gagal: {exc}"}

    if response.status_code != 200:
        LOGGER.error("SubSource download error status %s: %s", response.status_code, response.text)
        return {"ok": False, "error": f"API mengembalikan status {response.status_code}: {response.text[:200]}"}

    content_disposition = response.headers.get("content-disposition", "")
    filename = f"{clean_filename(movie_title)}_{subtitle_id}.zip"
    if "filename=" in content_disposition:
        matched = re.findall(r'filename=["\']?([^"\';]+)["\']?', content_disposition)
        if matched:
            filename = matched[0]

    filename = clean_filename(filename)
    if not filename.endswith(".zip"):
        filename += ".zip"

    # Simpan arsip ZIP di folder temporary OS agar tidak mengotori /downloads
    temp_dir = tempfile.gettempdir()
    temp_zip_path = os.path.join(temp_dir, filename)

    try:
        with open(temp_zip_path, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
    except Exception as exc:
        LOGGER.error("Gagal menulis file subtitle ke disk: %s", exc)
        return {"ok": False, "error": f"Gagal menyimpan file ke temporary disk: {exc}"}

    download_dir = get_download_dir()
    all_extracted: list[str] = []

    # Ekstraksi seluruh isi zip langsung ke download_dir (/downloads)
    try:
        if zipfile.is_zipfile(temp_zip_path):
            with zipfile.ZipFile(temp_zip_path, "r") as zip_ref:
                for member in zip_ref.namelist():
                    member_name = os.path.basename(member)
                    if not member_name:
                        continue
                    extracted_path = os.path.join(download_dir, clean_filename(member_name))
                    with zip_ref.open(member) as source, open(extracted_path, "wb") as target:
                        target.write(source.read())
                    all_extracted.append(extracted_path)
    except Exception as exc:
        LOGGER.warning("Gagal mengekstrak isi zip subtitle: %s", exc)

    # Filter khusus file subtitle asli
    subtitle_files = [f for f in all_extracted if f.lower().endswith(SUB_EXTENSIONS)]
    if not subtitle_files:
        subtitle_files = all_extracted

    # Urutkan episode secara alami
    subtitle_files.sort(key=lambda p: natural_sort_key(os.path.basename(p)))

    # Jika hanya 1 file (film), hapus zip temp sekarang karena cukup kirim file subtitle langsung
    if len(subtitle_files) <= 1:
        try:
            if os.path.exists(temp_zip_path):
                os.remove(temp_zip_path)
        except Exception:
            pass
        zip_for_sending = None
    else:
        # Jika series (> 1 file), simpan path temp zip untuk dikirim langsung ke Telegram chat
        zip_for_sending = temp_zip_path

    # Hitung total ukuran file subtitle
    total_size = sum(os.path.getsize(f) for f in subtitle_files if os.path.exists(f))
    primary_file = subtitle_files[0] if subtitle_files else ""

    return {
        "ok": True,
        "filename": os.path.basename(primary_file) if primary_file else filename,
        "primary_file": primary_file,
        "files": subtitle_files,
        "total_files": len(subtitle_files),
        "size": total_size,
        "download_dir": download_dir,
        "zip_path": zip_for_sending,
        "zip_name": filename,
    }


# ==============================================================================
# UI & KEYBOARD BUILDERS
# ==============================================================================
def build_movies_keyboard(grouped_items: list[dict[str, Any]], page: int = 1) -> InlineKeyboardMarkup:
    """Membuat keyboard daftar hasil pencarian film & serial (dengan label rapi anti overflow)."""
    total_items = len(grouped_items)
    total_pages = max(1, math.ceil(total_items / MOVIE_ITEMS_PER_PAGE))
    page = max(1, min(page, total_pages))

    start_idx = (page - 1) * MOVIE_ITEMS_PER_PAGE
    end_idx = min(start_idx + MOVIE_ITEMS_PER_PAGE, total_items)
    page_items = grouped_items[start_idx:end_idx]

    rows: list[list[InlineKeyboardButton]] = []
    for idx, item in enumerate(page_items, start=start_idx + 1):
        title = item.get("title") or item.get("name", "Unknown")
        year = item.get("releaseYear") or item.get("year", "")
        year_str = f" ({year})" if year else ""

        # Format judul bersih tanpa label season di samping judul (contoh: Attack on Titan (2013))
        raw_label = f"🎬 {idx}. {title}{year_str}"
        if len(raw_label) > 34:
            button_label = raw_label[:31] + "..."
        else:
            button_label = raw_label

        if item.get("is_series"):
            rows.append([InlineKeyboardButton(button_label, callback_data=f"sub_series:{idx - 1}")])
        else:
            m_id = item.get("movieId") or item.get("id")
            rows.append([InlineKeyboardButton(button_label, callback_data=f"sub_m:{m_id}")])

    # Baris navigasi jika lebih dari 1 halaman
    if total_pages > 1:
        nav_row: list[InlineKeyboardButton] = []
        if page > 1:
            nav_row.append(InlineKeyboardButton("◀️ Prev", callback_data=f"sub_mp:{page - 1}"))
        nav_row.append(InlineKeyboardButton(f"📄 {page}/{total_pages}", callback_data="sub_noop"))
        if page < total_pages:
            nav_row.append(InlineKeyboardButton("Next ▶️", callback_data=f"sub_mp:{page + 1}"))
        rows.append(nav_row)

    rows.append([InlineKeyboardButton("❌ Tutup", callback_data="sub_close")])
    return InlineKeyboardMarkup(rows)


def build_seasons_keyboard(series: dict[str, Any]) -> InlineKeyboardMarkup:
    """Membuat keyboard sub-pemilihan Season untuk serial TV (tanpa Season 0)."""
    raw_seasons = series.get("seasons", [])
    seasons = [s for s in raw_seasons if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0]
    if not seasons:
        seasons = raw_seasons

    rows: list[list[InlineKeyboardButton]] = []
    current_row: list[InlineKeyboardButton] = []
    for s in seasons:
        s_num = s.get("season")
        m_id = s.get("movieId") or s.get("id")
        if s_num is not None and int(s_num) != 0:
            label = f"📺 Season {s_num}"
            current_row.append(InlineKeyboardButton(label, callback_data=f"sub_m:{m_id}"))
            if len(current_row) == 2:
                rows.append(current_row)
                current_row = []

    if current_row:
        rows.append(current_row)

    rows.append([
        InlineKeyboardButton("🔙 Daftar Judul", callback_data="sub_back"),
        InlineKeyboardButton("❌ Tutup", callback_data="sub_close"),
    ])
    return InlineKeyboardMarkup(rows)


def format_seasons_message(series: dict[str, Any]) -> str:
    """Format teks pesan menu pemilihan Season serial TV (tanpa Specials / Season 0)."""
    title = series.get("title") or series.get("name", "Unknown")
    year = series.get("releaseYear") or series.get("year", "")
    year_str = f" ({year})" if year else ""
    imdb_id = series.get("imdbId")
    raw_seasons = series.get("seasons", [])
    seasons = [s for s in raw_seasons if s.get("season") not in (0, "0", None) and int(s.get("season", 0)) > 0]
    if not seasons:
        seasons = raw_seasons

    lines = [
        f"🎬 <b>{clean_html_text(title)}{year_str}</b>",
        f"🎭 Tipe: <code>TV Series</code>" + (f" | ⭐ IMDb: <code>{imdb_id}</code>" if imdb_id else ""),
        "",
        f"📺 <b>Daftar Season ({len(seasons)}):</b>",
    ]
    for s in seasons:
        s_num = s.get("season")
        if s_num in (0, "0", None) or int(s_num) == 0:
            continue
        sub_cnt = s.get("subtitleCount")
        cnt_info = f" <i>({sub_cnt} subs)</i>" if sub_cnt else ""
        lines.append(f"  • Season {s_num}{cnt_info}")

    lines.append("")
    lines.append("<i>Silakan pilih Season di bawah untuk melihat daftar subtitle:</i>")
    return "\n".join(lines)


def build_subtitles_keyboard(
    subtitles: list[dict[str, Any]],
    current_lang: str,
    page: int = 1,
    has_seasons: bool = False,
    has_multiple_movies: bool = False,
) -> InlineKeyboardMarkup:
    """
    Membuat keyboard interaktif pemilihan subtitle:
    - Tombol filter bahasa (Indo / English / Semua)
    - Tombol nomor download berkelanjutan (#1, #2 ... #6, dst.)
    - Tombol paginasi (Prev / Page / Next)
    - Tombol kembali (Ganti Season / Daftar Judul) dan Tutup
    """
    total_items = len(subtitles)
    total_pages = max(1, math.ceil(total_items / ITEMS_PER_PAGE))
    page = max(1, min(page, total_pages))

    start_idx = (page - 1) * ITEMS_PER_PAGE
    end_idx = min(start_idx + ITEMS_PER_PAGE, total_items)
    page_subtitles = subtitles[start_idx:end_idx]

    rows: list[list[InlineKeyboardButton]] = []

    # Row 1: Filter Bahasa
    lang_row: list[InlineKeyboardButton] = []
    for code, name, label in LANGUAGE_OPTIONS:
        active_mark = "✅ " if current_lang == code or current_lang == name else ""
        lang_row.append(
            InlineKeyboardButton(
                f"{active_mark}{label}",
                callback_data=f"sub_l:{code}",
            )
        )
    rows.append(lang_row)

    # Row 2: Tombol nomor subtitle berurutan sesuai nomor di pesan
    if page_subtitles:
        select_row: list[InlineKeyboardButton] = []
        for idx, sub in enumerate(page_subtitles, start=start_idx + 1):
            sub_id = sub.get("subtitleId") or sub.get("id")
            select_row.append(
                InlineKeyboardButton(
                    f"#{idx}",
                    callback_data=f"sub_dl:{sub_id}",
                )
            )
        rows.append(select_row)

    # Row 3: Navigasi Paginasi
    nav_row: list[InlineKeyboardButton] = []
    if page > 1:
        nav_row.append(InlineKeyboardButton("◀️ Prev", callback_data=f"sub_p:{page - 1}:{current_lang}"))
    nav_row.append(InlineKeyboardButton(f"📄 {page}/{total_pages}", callback_data="sub_noop"))
    if page < total_pages:
        nav_row.append(InlineKeyboardButton("Next ▶️", callback_data=f"sub_p:{page + 1}:{current_lang}"))
    rows.append(nav_row)

    # Row 4: Kontrol Bawah (Kembali ke Season / Film, dan Tutup)
    bottom_row: list[InlineKeyboardButton] = []
    if has_seasons:
        bottom_row.append(InlineKeyboardButton("🔙 Ganti Season", callback_data="sub_seasons"))
    elif has_multiple_movies:
        bottom_row.append(InlineKeyboardButton("🔙 Daftar Judul", callback_data="sub_back"))
    bottom_row.append(InlineKeyboardButton("❌ Tutup", callback_data="sub_close"))
    rows.append(bottom_row)

    return InlineKeyboardMarkup(rows)


def format_subtitles_message(
    movie: dict[str, Any],
    subtitles: list[dict[str, Any]],
    current_lang: str,
    page: int = 1,
) -> str:
    """Format teks pesan daftar subtitle dengan emoji bendera negara per bahasa."""
    title = movie.get("title") or movie.get("name", "Unknown Title")
    year = movie.get("releaseYear") or movie.get("year", "")
    year_str = f" ({year})" if year else ""
    imdb_id = movie.get("imdbId") or movie.get("imdb", "")
    m_type = movie.get("type", "movie").capitalize()
    season = movie.get("season")
    season_str = f" - Season {season}" if (season is not None and season != 0) else (" - Specials" if season == 0 else "")

    total_items = len(subtitles)
    total_pages = max(1, math.ceil(total_items / ITEMS_PER_PAGE))
    page = max(1, min(page, total_pages))

    lang_display = {
        "id": "Bahasa Indonesia 🇮🇩",
        "indonesian": "Bahasa Indonesia 🇮🇩",
        "en": "English 🇬🇧",
        "english": "English 🇬🇧",
        "all": "Semua Bahasa 🌐",
    }.get(current_lang.lower(), f"{current_lang.capitalize()} {get_language_flag(current_lang)}")

    lines = [
        f"🎬 <b>{clean_html_text(title)}{year_str}{season_str}</b>",
        f"🎭 Tipe: <code>{m_type}</code>" + (f" | ⭐ IMDb: <code>{imdb_id}</code>" if imdb_id else ""),
        f"🌐 Filter: <b>{lang_display}</b> | Total: <b>{total_items} subtitle</b>",
        f"📄 Halaman: <b>{page} / {total_pages}</b>",
        "",
    ]

    if not subtitles:
        lines.append("<i>❌ Tidak ada subtitle yang ditemukan untuk filter bahasa ini.</i>")
        lines.append("<i>Silakan klik tombol filter bahasa lain di bawah (misal: English atau Semua).</i>")
        return "\n".join(lines)

    start_idx = (page - 1) * ITEMS_PER_PAGE
    end_idx = min(start_idx + ITEMS_PER_PAGE, total_items)
    page_subtitles = subtitles[start_idx:end_idx]

    for idx, sub in enumerate(page_subtitles, start=start_idx + 1):
        sub_lang = (sub.get("language") or "").strip().lower()
        flag = get_language_flag(sub_lang)
        downloads = sub.get("downloads", 0)

        rating = sub.get("rating") or {}
        good_votes = rating.get("good", 0)
        bad_votes = rating.get("bad", 0)

        release_info = sub.get("releaseInfo")
        if isinstance(release_info, list) and release_info:
            rel_str = ", ".join(release_info)
        else:
            rel_str = str(release_info) if release_info else "Standard Release"
        if len(rel_str) > 130:
            rel_str = rel_str[:127] + "..."

        commentary = (sub.get("commentary") or "").strip()
        if not commentary:
            commentary = "-"
        elif len(commentary) > 150:
            commentary = commentary[:147] + "..."

        lines.extend([
            f"#{idx} {flag}",
            f"<b>Release Name:</b> <code>{clean_html_text(rel_str)}</code>",
            f"<b>Deskripsi:</b> <code>{clean_html_text(commentary)}</code>",
            f"<b>Total unduhan:</b> <code>{downloads}</code>",
            f"<b>Vote:</b> Good {good_votes} | Bad {bad_votes}",
            "",
        ])

    lines.append("<i>Pilih nomor subtitle di bawah untuk mengunduh:</i>")
    return "\n".join(lines)


# ==============================================================================
# TELEGRAM HANDLERS (MESSAGE & CALLBACK)
# ==============================================================================
@new_task
async def subtitle_command(client: Client, message: Message):
    """
    Handler perintah /subtitle <keyword atau IMDb link/ID>.
    Mencari film/serial di SubSource dan menampilkan menu interaktif.
    """
    text = message.text or message.caption or ""
    parts = text.split(maxsplit=1)

    query = parts[1].strip() if len(parts) > 1 else ""

    if not query and message.reply_to_message:
        reply_text = message.reply_to_message.text or message.reply_to_message.caption or ""
        query = reply_text.strip()

    if not query:
        cmd_prefix = parts[0].lstrip("/") if parts else "subtitle"
        return await message.reply_text(
            f"🎬 <b>SubSource Subtitle Downloader</b>\n\n"
            f"Gunakan perintah ini untuk mencari dan mendownload subtitle film/serial dari SubSource.\n\n"
            f"<b>Format Penggunaan:</b>\n"
            f"• <code>/{cmd_prefix} &lt;judul film / show&gt;</code>\n"
            f"• <code>/{cmd_prefix} &lt;IMDb ID&gt;</code> (misal: <code>tt1375666</code>)\n"
            f"• <code>/{cmd_prefix} &lt;link IMDb&gt;</code>\n\n"
            f"<b>Contoh:</b>\n"
            f"• <code>/{cmd_prefix} Attack on Titan</code>\n"
            f"• <code>/{cmd_prefix} Inception</code>\n"
            f"• <code>/{cmd_prefix} tt0848228</code>\n\n"
            f"<i>Output file akan otomatis diekstrak dan disimpan ke folder <code>/downloads</code>.</i>",
            parse_mode=ParseMode.HTML,
        )

    status_msg = await message.reply_text(
        f"🔍 <b>Mencari film/serial:</b> <code>{html.escape(query)}</code>...",
        parse_mode=ParseMode.HTML,
    )

    detected_imdb = extract_imdb_id(query)
    try:
        if detected_imdb:
            raw_movies = await asyncio.to_thread(search_movies, query, imdb_id=detected_imdb)
        else:
            raw_movies = await asyncio.to_thread(search_movies, query)
    except Exception as exc:
        LOGGER.error("Error search_movies in command: %s", exc)
        return await safe_edit_message(
            status_msg,
            f"❌ <b>Gagal mencari film:</b> {html.escape(str(exc))}",
        )

    if not raw_movies:
        return await safe_edit_message(
            status_msg,
            f"❌ <b>Tidak ada hasil ditemukan</b> untuk: <code>{html.escape(query)}</code>\n\n"
            f"Pastikan ejaan benar atau gunakan IMDb ID (contoh: <code>tt1375666</code>).",
        )

    grouped_items = group_movies_and_series(raw_movies)
    session_key = f"{status_msg.chat.id}_{status_msg.id}"
    cleanup_old_sessions()

    # 1. Jika ditemukan lebih dari 1 grup judul
    if len(grouped_items) > 1:
        SEARCH_SESSIONS[session_key] = {
            "query": query,
            "raw_movies": raw_movies,
            "grouped_items": grouped_items,
            "current_series": None,
            "current_movie": None,
            "current_lang": "id",
            "page": 1,
            "movie_page": 1,
            "user_id": message.from_user.id if message.from_user else 0,
            "timestamp": time.time(),
        }

        text_content = (
            f"🎬 <b>Hasil Pencarian SubSource</b>\n"
            f"Query: <code>{clean_html_text(query)}</code>\n"
            f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
            f"<i>Silakan pilih judul di bawah ini:</i>"
        )
        keyboard = build_movies_keyboard(grouped_items, page=1)
        return await safe_edit_message(status_msg, text_content, reply_markup=keyboard)

    # 2. Hanya 1 grup judul ditemukan
    single_item = grouped_items[0]

    # 2A. Jika serial TV dengan banyak Season -> Buka menu pemilihan Season
    if single_item.get("is_series") and len(single_item.get("seasons", [])) > 1:
        SEARCH_SESSIONS[session_key] = {
            "query": query,
            "raw_movies": raw_movies,
            "grouped_items": grouped_items,
            "current_series": single_item,
            "current_movie": None,
            "current_lang": "id",
            "page": 1,
            "movie_page": 1,
            "user_id": message.from_user.id if message.from_user else 0,
            "timestamp": time.time(),
        }
        text_content = format_seasons_message(single_item)
        keyboard = build_seasons_keyboard(single_item)
        return await safe_edit_message(status_msg, text_content, reply_markup=keyboard)

    # 2B. Jika film biasa atau series dengan 1 season -> Langsung buka daftar subtitle
    if single_item.get("is_series"):
        selected_movie = single_item["seasons"][0]
    else:
        selected_movie = single_item

    movie_id = selected_movie.get("movieId") or selected_movie.get("id")
    if not movie_id:
        return await safe_edit_message(status_msg, "❌ Data tidak memiliki ID yang valid dari SubSource.")

    current_lang = "id"
    api_lang = LANG_CODE_TO_NAME.get(current_lang, "indonesian")

    await safe_edit_message(
        status_msg,
        f"⏳ <b>Mengambil daftar subtitle untuk:</b> <i>{clean_html_text(selected_movie.get('title', ''))}</i>...",
    )

    try:
        subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language=api_lang)
        if not subtitles:
            subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language="english")
            if subtitles:
                current_lang = "en"
            else:
                subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language="all")
                if subtitles:
                    current_lang = "all"
    except Exception as exc:
        LOGGER.error("Gagal mengambil subtitle: %s", exc)
        return await safe_edit_message(
            status_msg,
            f"❌ <b>Gagal mengambil subtitle:</b> {html.escape(str(exc))}",
        )

    SEARCH_SESSIONS[session_key] = {
        "query": query,
        "raw_movies": raw_movies,
        "grouped_items": grouped_items,
        "current_series": None,
        "current_movie": selected_movie,
        "current_lang": current_lang,
        "subtitles": subtitles,
        "page": 1,
        "movie_page": 1,
        "user_id": message.from_user.id if message.from_user else 0,
        "timestamp": time.time(),
    }

    text_content = format_subtitles_message(selected_movie, subtitles, current_lang, page=1)
    keyboard = build_subtitles_keyboard(
        subtitles,
        current_lang,
        page=1,
        has_seasons=False,
        has_multiple_movies=False,
    )
    await safe_edit_message(status_msg, text_content, reply_markup=keyboard)


async def handle_subtitle_callback(client: Client, query: CallbackQuery):
    """
    Handler utama untuk seluruh callback query sub_*:
    - sub_series:<idx> : Memilih serial TV dan menampilkan daftar Season
    - sub_seasons      : Kembali ke menu pemilihan Season
    - sub_m:<movie_id> : Memilih Season / Film dan memuat daftar subtitle
    - sub_mp:<page>    : Paginasi daftar judul film/series
    - sub_l:<lang>     : Mengubah filter bahasa
    - sub_p:<page>:<lang> : Paginasi daftar subtitle
    - sub_dl:<sub_id>  : Mengunduh subtitle (otomatis ekstrak & bersihkan zip)
    - sub_send:<sub_id>: Mengirimkan semua file subtitle ke chat Telegram
    - sub_nosend:<sub_id>: Tetap menyimpan di server tanpa kirim ke chat
    - sub_back         : Kembali ke daftar judul film/series
    - sub_close        : Menutup tampilan
    """
    data = query.data or ""
    if not data.startswith("sub_"):
        return

    if data == "sub_noop":
        return await query.answer()

    if data == "sub_close":
        cancel_auto_close(query.message.chat.id, query.message.id)
        try:
            await query.message.delete()
        except Exception:
            try:
                await query.edit_message_reply_markup(reply_markup=None)
            except Exception:
                pass
        return await query.answer("Ditutup.")

    session_key = f"{query.message.chat.id}_{query.message.id}"
    session = SEARCH_SESSIONS.get(session_key)

    try:
        # ----------------------------------------------------------------------
        # 1. DOWNLOAD SUBTITLE & KONFIRMASI (sub_dl:<sub_id>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_dl:"):
            sub_id_str = data.split(":", 1)[1]
            try:
                sub_id = int(sub_id_str)
            except ValueError:
                return await query.answer("ID subtitle tidak valid.", show_alert=True)

            await query.answer("⏳ Mengunduh subtitle...", show_alert=False)

            movie_info = session.get("current_movie", {}) if session else {}
            movie_title = movie_info.get("title") or movie_info.get("name", "subtitle")
            season = movie_info.get("season")
            if season is not None:
                season_label = f"Season {season}" if season != 0 else "Specials"
                full_title = f"{movie_title} - {season_label}"
            else:
                full_title = movie_title

            try:
                res = await asyncio.to_thread(download_subtitle_file, sub_id, movie_title=movie_title)
            except Exception as dl_exc:
                res = {"ok": False, "error": str(dl_exc)}

            if not res.get("ok"):
                err_msg = res.get("error", "Gagal mengunduh subtitle.")
                LOGGER.error("Gagal download subtitle #%s: %s", sub_id, err_msg)
                try:
                    await query.answer(f"❌ Gagal: {err_msg[:100]}", show_alert=True)
                except Exception:
                    pass
                return await query.message.reply_text(
                    f"❌ <b>Gagal Mengunduh Subtitle #{sub_id}</b>\n\n"
                    f"Detail error: <code>{html.escape(str(err_msg))}</code>\n\n"
                    f"<i>Silakan coba pilih subtitle lain atau ganti bahasa.</i>",
                    parse_mode=ParseMode.HTML,
                )

            files = res.get("files", [])
            total_files = len(files)
            download_dir = res.get("download_dir", "/downloads")
            size_str = format_bytes(res.get("size"))

            # Simpan data unduhan untuk penanganan tombol konfirmasi kirim
            DOWNLOADED_SUBS[str(sub_id)] = {
                "files": files,
                "primary_file": res.get("primary_file", ""),
                "primary_name": res.get("filename", ""),
                "total_files": total_files,
                "movie_title": full_title,
                "size_str": size_str,
                "download_dir": download_dir,
                "zip_path": res.get("zip_path"),
                "timestamp": time.time(),
            }

            if total_files > 1:
                confirm_text = (
                    f"✅ <b>Subtitle Series Berhasil Diunduh!</b>\n\n"
                    f"🎬 <b>Series:</b> <i>{clean_html_text(full_title)}</i>\n"
                    f"📦 <b>Total Episode:</b> <code>{total_files} file subtitle</code>\n"
                    f"📁 <b>Tersimpan di:</b> <code>{html.escape(download_dir)}</code>\n"
                    f"💾 <b>Total Ukuran:</b> <code>{size_str}</code>\n\n"
                    f"<i>File subtitle telah diekstrak ke server lokal. Apakah Anda ingin mengirimkan "
                    f"file ZIP ini ke chat Telegram?</i>"
                )
                button_send_label = f"📤 Ya, Kirim File ZIP ({total_files} Episode)"
            else:
                primary_name = res.get("filename", "")
                confirm_text = (
                    f"✅ <b>Subtitle Berhasil Diunduh!</b>\n\n"
                    f"🎬 <b>Judul:</b> <i>{clean_html_text(full_title)}</i>\n"
                    f"📄 <b>File:</b> <code>{clean_html_text(primary_name)}</code>\n"
                    f"📁 <b>Lokasi:</b> <code>{html.escape(res.get('primary_file', ''))}</code>\n"
                    f"💾 <b>Ukuran:</b> <code>{size_str}</code>\n\n"
                    f"<i>Apakah Anda ingin mengirimkan file subtitle ini ke chat Telegram?</i>"
                )
                button_send_label = "📤 Ya, Kirim ke Chat"

            # Pisahkan ke baris masing-masing agar tidak melebihi lebar card UI Telegram
            confirm_keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton(button_send_label, callback_data=f"sub_send:{sub_id}")],
                [InlineKeyboardButton("📁 Tidak, Cukup Simpan di Server", callback_data=f"sub_nosend:{sub_id}")],
            ])

            confirm_msg = await query.message.reply_text(
                confirm_text,
                reply_markup=confirm_keyboard,
                parse_mode=ParseMode.HTML,
            )
            schedule_auto_close(
                client,
                confirm_msg.chat.id,
                confirm_msg.id,
                delay=120,
                temp_zip_to_clean=res.get("zip_path"),
            )

            try:
                await query.answer(f"✅ Berhasil diekstrak ({total_files} file di /downloads)!", show_alert=False)
            except Exception:
                pass
            return

        # ----------------------------------------------------------------------
        # 1A. PENGGUNA MEMILIH KIRIM KE CHAT (sub_send:<sub_id>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_send:"):
            sub_id = data.split(":", 1)[1]
            item = DOWNLOADED_SUBS.get(sub_id)
            if not item or not item.get("files"):
                return await query.answer("File tidak ditemukan atau sesi telah kadaluarsa.", show_alert=True)

            files = item["files"]
            movie_title = item["movie_title"]
            total_files = len(files)
            download_dir = item.get("download_dir", "/downloads")
            zip_path = item.get("zip_path")

            cancel_auto_close(query.message.chat.id, query.message.id)
            await query.answer("Mengirim subtitle ke chat...", show_alert=False)

            if total_files > 1:
                # Format satu pesan caption bersih sesuai instruksi:
                # 📦 {total_files} File Subtitle Telah Dikirim dan disimpan di lokal!
                caption = (
                    f"📦 <b>{total_files} File Subtitle Telah Dikirim dan disimpan di lokal!</b>\n\n"
                    f"🎬 <b>Series:</b> <i>{clean_html_text(movie_title)}</i>\n"
                    f"📁 <b>Tersimpan di:</b> <code>{html.escape(download_dir)}</code>"
                )

                # Jika zip_path tidak ditemukan, bungkus ulang dari file yang ada di /downloads
                if not zip_path or not os.path.exists(zip_path):
                    temp_zip = os.path.join(tempfile.gettempdir(), f"{clean_filename(movie_title)}_{sub_id}.zip")
                    with zipfile.ZipFile(temp_zip, "w", zipfile.ZIP_DEFLATED) as zf:
                        for f in files:
                            if os.path.exists(f):
                                zf.write(f, os.path.basename(f))
                    zip_path = temp_zip

                try:
                    await client.send_document(
                        chat_id=query.message.chat.id,
                        document=zip_path,
                        caption=caption,
                        parse_mode=ParseMode.HTML,
                    )
                except FloodWait as f_err:
                    await asyncio.sleep(int(f_err.value) + 1)
                    await client.send_document(
                        chat_id=query.message.chat.id,
                        document=zip_path,
                        caption=caption,
                        parse_mode=ParseMode.HTML,
                    )
                except Exception as send_err:
                    LOGGER.error("Gagal mengirim file zip subtitle: %s", send_err)
                    return await query.answer(f"Gagal mengirim ZIP: {send_err}", show_alert=True)
                finally:
                    # Bersihkan file ZIP dari temporary agar tidak tersisa di disk manapun
                    try:
                        if zip_path and os.path.exists(zip_path):
                            os.remove(zip_path)
                    except Exception:
                        pass

                # Hapus pesan konfirmasi agar hanya tersisa 1 pesan dokumen yang rapi di Telegram
                try:
                    await query.message.delete()
                except Exception:
                    try:
                        await query.edit_message_reply_markup(reply_markup=None)
                    except Exception:
                        pass
                return

            # Jika film biasa (1 file subtitle)
            single_file = files[0]
            caption = (
                f"📄 <b>File Subtitle Telah Dikirim dan disimpan di lokal!</b>\n\n"
                f"🎬 <b>Judul:</b> <i>{clean_html_text(movie_title)}</i>\n"
                f"📁 <b>Tersimpan di:</b> <code>{html.escape(single_file)}</code>"
            )
            try:
                await client.send_document(
                    chat_id=query.message.chat.id,
                    document=single_file,
                    caption=caption,
                    parse_mode=ParseMode.HTML,
                )
            except FloodWait as f_err:
                await asyncio.sleep(int(f_err.value) + 1)
                await client.send_document(
                    chat_id=query.message.chat.id,
                    document=single_file,
                    caption=caption,
                    parse_mode=ParseMode.HTML,
                )
            except Exception as send_err:
                LOGGER.error("Gagal mengirim dokumen subtitle: %s", send_err)
                return await query.answer(f"Gagal mengirim subtitle: {send_err}", show_alert=True)

            # Hapus pesan konfirmasi agar hanya ada 1 pesan
            try:
                await query.message.delete()
            except Exception:
                try:
                    await query.edit_message_reply_markup(reply_markup=None)
                except Exception:
                    pass
            return

        # ----------------------------------------------------------------------
        # 1B. PENGGUNA MEMILIH TIDAK KIRIM KE CHAT (sub_nosend:<sub_id>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_nosend:"):
            sub_id = data.split(":", 1)[1]
            item = DOWNLOADED_SUBS.get(sub_id)
            movie_title = item.get("movie_title", "") if item else ""
            download_dir = item.get("download_dir", "/downloads") if item else "/downloads"
            total_files = item.get("total_files", 1) if item else 1
            zip_path = item.get("zip_path") if item else None

            # Hapus temporary zip jika ada
            if zip_path and os.path.exists(zip_path):
                try:
                    os.remove(zip_path)
                except Exception:
                    pass

            cancel_auto_close(query.message.chat.id, query.message.id)

            updated_text = (
                f"📁 <b>Subtitle Tetap Tersimpan di Server</b>\n\n"
                f"🎬 <b>Judul/Series:</b> <i>{clean_html_text(movie_title)}</i>\n"
                f"📦 <b>Jumlah File:</b> <code>{total_files} file</code>\n"
                f"📁 <b>Lokasi:</b> <code>{html.escape(download_dir)}</code>\n\n"
                f"<i>File subtitle tetap tersimpan di folder <code>/downloads</code> untuk media server (tanpa file ZIP).</i>"
            )
            await safe_edit_message(query, updated_text, reply_markup=None, auto_close=False)
            return await query.answer("Subtitle tetap disimpan di /downloads!")

        # Jika sesi pencarian sudah tidak ada di memori
        if not session:
            return await query.answer(
                "Sesi pencarian telah kadaluarsa. Silakan ketik perintah /subtitle kembali.",
                show_alert=True,
            )

        # ----------------------------------------------------------------------
        # 2. NAVIGASI DAFTAR JUDUL FILM/SERIES (sub_mp:<page>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_mp:"):
            page = int(data.split(":", 1)[1])
            session["movie_page"] = page
            grouped_items = session.get("grouped_items", [])
            text_content = (
                f"🎬 <b>Hasil Pencarian SubSource</b>\n"
                f"Query: <code>{clean_html_text(session.get('query', ''))}</code>\n"
                f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
                f"<i>Silakan pilih judul di bawah ini:</i>"
            )
            keyboard = build_movies_keyboard(grouped_items, page=page)
            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return await query.answer()

        # ----------------------------------------------------------------------
        # 3. KEMBALI KE DAFTAR JUDUL (sub_back)
        # ----------------------------------------------------------------------
        if data == "sub_back":
            grouped_items = session.get("grouped_items", [])
            page = session.get("movie_page", 1)
            session["current_series"] = None
            text_content = (
                f"🎬 <b>Hasil Pencarian SubSource</b>\n"
                f"Query: <code>{clean_html_text(session.get('query', ''))}</code>\n"
                f"Ditemukan <b>{len(grouped_items)}</b> judul film/series.\n\n"
                f"<i>Silakan pilih judul di bawah ini:</i>"
            )
            keyboard = build_movies_keyboard(grouped_items, page=page)
            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return await query.answer()

        # ----------------------------------------------------------------------
        # 4. MEMILIH SERIAL TV -> SUB-PEMILIHAN SEASON (sub_series:<idx>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_series:"):
            idx = int(data.split(":", 1)[1])
            grouped_items = session.get("grouped_items", [])
            if not (0 <= idx < len(grouped_items)):
                return await query.answer("Series tidak ditemukan.", show_alert=True)

            series = grouped_items[idx]
            session["current_series"] = series

            text_content = format_seasons_message(series)
            keyboard = build_seasons_keyboard(series)
            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return await query.answer()

        # ----------------------------------------------------------------------
        # 5. KEMBALI KE MENU SEASON SERIAL TV (sub_seasons)
        # ----------------------------------------------------------------------
        if data == "sub_seasons":
            series = session.get("current_series")
            if not series:
                return await query.answer("Data series tidak ditemukan.", show_alert=True)

            text_content = format_seasons_message(series)
            keyboard = build_seasons_keyboard(series)
            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return await query.answer()

        # ----------------------------------------------------------------------
        # 6. MEMILIH SEASON / FILM (sub_m:<movie_id>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_m:"):
            movie_id_str = data.split(":", 1)[1]
            try:
                movie_id = int(movie_id_str)
            except ValueError:
                return await query.answer("Movie ID tidak valid.", show_alert=True)

            # Cari movie object baik dari raw_movies atau dari seasons dalam series
            raw_movies = session.get("raw_movies", [])
            selected_movie = next(
                (m for m in raw_movies if (m.get("movieId") or m.get("id")) == movie_id),
                None,
            )
            if not selected_movie and session.get("current_series"):
                seasons = session["current_series"].get("seasons", [])
                selected_movie = next(
                    (s for s in seasons if (s.get("movieId") or s.get("id")) == movie_id),
                    None,
                )

            if not selected_movie:
                return await query.answer("Judul tidak ditemukan dalam sesi.", show_alert=True)

            await query.answer("Memuat subtitle...")
            current_lang = session.get("current_lang", "id")
            api_lang = LANG_CODE_TO_NAME.get(current_lang, "indonesian")

            try:
                subtitles = await asyncio.to_thread(get_subtitles, movie_id, language=api_lang)
                if not subtitles and current_lang == "id":
                    subtitles_en = await asyncio.to_thread(get_subtitles, movie_id, language="english")
                    if subtitles_en:
                        current_lang = "en"
                        subtitles = subtitles_en
            except Exception as fetch_err:
                LOGGER.error("Gagal mengambil subtitle untuk movie %s: %s", movie_id, fetch_err)
                return await safe_edit_message(
                    query,
                    f"❌ <b>Gagal memuat subtitle untuk:</b> <i>{clean_html_text(selected_movie.get('title', ''))}</i>\n\n"
                    f"Detail error: <code>{html.escape(str(fetch_err))}</code>",
                    reply_markup=InlineKeyboardMarkup([
                        [InlineKeyboardButton("🔙 Kembali", callback_data="sub_seasons" if session.get("current_series") else "sub_back")],
                        [InlineKeyboardButton("❌ Tutup", callback_data="sub_close")],
                    ]),
                )

            session["current_movie"] = selected_movie
            session["current_lang"] = current_lang
            session["subtitles"] = subtitles
            session["page"] = 1

            has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
            has_multiple_movies = len(session.get("grouped_items", [])) > 1

            text_content = format_subtitles_message(selected_movie, subtitles, current_lang, page=1)
            keyboard = build_subtitles_keyboard(
                subtitles,
                current_lang,
                page=1,
                has_seasons=has_seasons,
                has_multiple_movies=has_multiple_movies,
            )

            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return

        # ----------------------------------------------------------------------
        # 7. GANTI FILTER BAHASA (sub_l:<lang_code>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_l:"):
            lang_code = data.split(":", 1)[1]
            if lang_code == session.get("current_lang"):
                return await query.answer("Filter bahasa ini sudah aktif.")

            movie = session.get("current_movie")
            if not movie:
                return await query.answer("Film/Season belum dipilih.", show_alert=True)

            movie_id = movie.get("movieId") or movie.get("id")
            api_lang = LANG_CODE_TO_NAME.get(lang_code, "indonesian")

            await query.answer("Mengambil subtitle...")
            try:
                subtitles = await asyncio.to_thread(get_subtitles, int(movie_id), language=api_lang)
            except Exception as fetch_err:
                LOGGER.error("Gagal ganti bahasa: %s", fetch_err)
                return await query.answer(f"❌ Gagal memuat subtitle: {fetch_err}", show_alert=True)

            session["current_lang"] = lang_code
            session["subtitles"] = subtitles
            session["page"] = 1

            has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
            has_multiple_movies = len(session.get("grouped_items", [])) > 1

            text_content = format_subtitles_message(movie, subtitles, lang_code, page=1)
            keyboard = build_subtitles_keyboard(
                subtitles,
                lang_code,
                page=1,
                has_seasons=has_seasons,
                has_multiple_movies=has_multiple_movies,
            )

            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return

        # ----------------------------------------------------------------------
        # 8. PAGINASI DAFTAR SUBTITLE (sub_p:<page>:<lang_code>)
        # ----------------------------------------------------------------------
        if data.startswith("sub_p:"):
            parts = data.split(":")
            page = int(parts[1])
            lang_code = parts[2] if len(parts) > 2 else session.get("current_lang", "id")

            movie = session.get("current_movie")
            if not movie:
                return await query.answer("Film/Season belum dipilih.", show_alert=True)

            session["page"] = page
            subtitles = session.get("subtitles", [])
            has_seasons = bool(session.get("current_series") and len(session["current_series"].get("seasons", [])) > 1)
            has_multiple_movies = len(session.get("grouped_items", [])) > 1

            text_content = format_subtitles_message(movie, subtitles, lang_code, page=page)
            keyboard = build_subtitles_keyboard(
                subtitles,
                lang_code,
                page=page,
                has_seasons=has_seasons,
                has_multiple_movies=has_multiple_movies,
            )

            await safe_edit_message(query, text_content, reply_markup=keyboard)
            return await query.answer()

    except Exception as exc:
        LOGGER.error("Exception in handle_subtitle_callback (data=%s): %s", data, exc, exc_info=True)
        try:
            await query.answer(f"❌ Terjadi kesalahan: {str(exc)[:100]}", show_alert=True)
        except Exception:
            pass
        try:
            await query.message.reply_text(
                f"❌ <b>Terjadi kesalahan saat memproses permintaan subtitle:</b>\n"
                f"<code>{html.escape(str(exc))}</code>",
                parse_mode=ParseMode.HTML,
            )
        except Exception:
            pass