File size: 54,676 Bytes
a330af4
db41b9b
93094bf
cb18578
 
 
db41b9b
 
a330af4
 
 
 
 
 
 
 
 
699389b
a330af4
 
900c3a8
db41b9b
a330af4
 
 
93094bf
e4b4835
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a330af4
0334f45
 
 
 
 
 
 
 
 
 
 
 
a330af4
93094bf
a330af4
 
900c3a8
 
 
 
 
 
 
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4b4835
 
 
 
 
 
 
 
 
 
a330af4
e4b4835
 
a330af4
d59d8ea
e4b4835
 
 
d59d8ea
 
 
 
e4b4835
 
 
 
d59d8ea
e4b4835
 
 
 
 
 
 
 
 
 
d59d8ea
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
d59d8ea
e4b4835
 
 
 
 
d59d8ea
e4b4835
 
 
 
 
 
d59d8ea
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d59d8ea
e4b4835
 
 
 
 
 
 
 
 
d59d8ea
 
e4b4835
d59d8ea
 
e4b4835
d59d8ea
 
 
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf3320
1d6e15b
 
 
 
 
900c3a8
 
1d6e15b
 
900c3a8
 
f0eee2c
1d6e15b
 
900c3a8
cb18578
 
f0eee2c
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
f0eee2c
 
900c3a8
cb18578
f0eee2c
 
 
cb18578
1d6e15b
cb18578
 
e6abf12
f0eee2c
cb18578
f0eee2c
 
cb18578
f0eee2c
 
 
 
cb18578
 
f0eee2c
5bf3320
f0eee2c
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf3320
f0eee2c
cb18578
 
 
 
 
 
 
f0eee2c
 
 
cb18578
f0eee2c
 
 
900c3a8
1d6e15b
5bf3320
cb18578
5bf3320
f0eee2c
900c3a8
1d6e15b
f0eee2c
cb18578
5bf3320
 
f0eee2c
 
cb18578
 
 
 
30720b7
5bf3320
30720b7
5bf3320
900c3a8
cb18578
f0eee2c
cb18578
 
 
 
f0eee2c
cb18578
 
 
 
 
f0eee2c
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30720b7
 
cb18578
f0eee2c
 
900c3a8
f0eee2c
900c3a8
cb18578
f0eee2c
 
 
 
 
 
900c3a8
cb18578
5bf3320
cb18578
 
f0eee2c
cb18578
f0eee2c
 
cb18578
 
 
 
 
 
f0eee2c
30720b7
 
5bf3320
f0eee2c
 
cb18578
 
 
 
 
f0eee2c
 
 
 
 
 
 
cb18578
f0eee2c
cb18578
 
 
 
5bf3320
f0eee2c
 
cb18578
 
5bf3320
f0eee2c
5bf3320
f0eee2c
900c3a8
cb18578
f0eee2c
 
 
900c3a8
e4b4835
 
 
 
30720b7
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
30720b7
 
cb18578
 
e4b4835
 
30720b7
cb18578
 
e4b4835
 
 
 
 
 
f0eee2c
 
cb18578
 
 
 
 
 
e4b4835
30720b7
cb18578
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
 
1d6e15b
900c3a8
f0eee2c
 
1d6e15b
f0eee2c
 
 
 
1d6e15b
 
f0eee2c
1d6e15b
900c3a8
 
1d6e15b
f0eee2c
1d6e15b
 
 
cb18578
e4b4835
 
 
 
 
 
 
 
 
 
1d6e15b
e4b4835
 
1d6e15b
 
 
e4b4835
 
 
1d6e15b
e4b4835
 
 
 
 
 
 
 
 
900c3a8
1d6e15b
e4b4835
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
 
 
e4b4835
 
 
db41b9b
e4b4835
 
 
 
db41b9b
 
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
 
e4b4835
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
db41b9b
 
e4b4835
 
db41b9b
e4b4835
db41b9b
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
db41b9b
 
e4b4835
 
db41b9b
e4b4835
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
 
e4b4835
 
 
 
 
 
 
 
 
 
 
db41b9b
 
 
 
e4b4835
db41b9b
e4b4835
 
 
db41b9b
e4b4835
db41b9b
 
 
 
 
e4b4835
db41b9b
 
 
 
e4b4835
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
db41b9b
e4b4835
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
db41b9b
 
e4b4835
 
db41b9b
e4b4835
db41b9b
 
e4b4835
db41b9b
 
 
 
e4b4835
 
db41b9b
e4b4835
 
db41b9b
e4b4835
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
 
e4b4835
 
 
db41b9b
e4b4835
 
db41b9b
e4b4835
 
 
 
db41b9b
e4b4835
 
 
db41b9b
e4b4835
 
 
db41b9b
e4b4835
db41b9b
 
e4b4835
 
 
db41b9b
e4b4835
db41b9b
 
e4b4835
 
db41b9b
 
 
426e8e9
 
 
1d6e15b
e4b4835
 
ad34132
e4b4835
 
 
 
 
 
 
 
db41b9b
 
 
e4b4835
 
 
db41b9b
 
e4b4835
db41b9b
e4b4835
 
426e8e9
 
e4b4835
426e8e9
93094bf
426e8e9
 
 
 
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
1d6e15b
426e8e9
 
1d6e15b
426e8e9
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
 
 
1d6e15b
 
 
 
 
 
 
426e8e9
1d6e15b
426e8e9
 
93094bf
 
1d6e15b
93094bf
426e8e9
 
 
93094bf
a330af4
 
426e8e9
93094bf
 
e4b4835
 
93094bf
e4b4835
 
 
 
 
 
 
93094bf
e4b4835
93094bf
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
93094bf
e4b4835
 
 
 
 
 
93094bf
 
 
 
 
426e8e9
 
93094bf
 
426e8e9
 
93094bf
426e8e9
 
93094bf
 
426e8e9
 
93094bf
 
426e8e9
 
93094bf
426e8e9
 
93094bf
 
426e8e9
 
 
 
 
 
 
 
 
 
8b468c1
93094bf
426e8e9
 
 
 
 
93094bf
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
93094bf
a330af4
 
 
 
 
905e847
 
a330af4
 
 
4303eeb
 
93094bf
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
 
 
a330af4
 
 
426e8e9
a330af4
 
 
 
 
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
"""
StreamForge API v9 - Multi-Language Stream Scraper
Scrapes direct m3u8 URLs from multiple sources
Updated: MovieBox, Castle, VidLink, VidSrc, NetMirror
Added: VidFast, ShowBox, GoatAPI
Removed: CineSu (dead), PrimeSrc (Cloudflare), DooFlix (API key revoked)
v9: Added Cineby, PurStream, Movix, MoviesHunt, HDHub4u, VegaMovies, Movies4u
    (ported + live-tested from All-in-One-Nuvio & MediaVanced repos)
"""

from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import httpx
import json
import re
import base64
import time
import asyncio
import hashlib
from urllib.parse import quote

app = FastAPI(
    title="StreamForge API",
    description="Multi-language m3u8 stream scraper",
    version="10.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973"
TMDB_BASE = "https://api.themoviedb.org/3"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Accept": "application/json, text/html, */*",
    "Accept-Language": "en-US,en;q=0.5",
}


# ===== Models =====

class ScrapeRequest(BaseModel):
    tmdb_id: int
    media_type: str = "movie"
    season: Optional[int] = None
    episode: Optional[int] = None
    sources: Optional[list[str]] = None


# ===== Helpers =====

async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict:
    async with httpx.AsyncClient(timeout=10) as client:
        type_path = "tv" if media_type == "tv" else "movie"
        resp = await client.get(
            f"{TMDB_BASE}/{type_path}/{tmdb_id}",
            params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"}
        )
        data = resp.json()
        return {
            "imdb_id": data.get("external_ids", {}).get("imdb_id"),
            "title": data.get("title") or data.get("name"),
            "year": (data.get("release_date") or data.get("first_air_date") or "")[:4],
        }


async def get_tmdb_info_with_key(tmdb_id: int, media_type: str, api_key: str) -> dict:
    async with httpx.AsyncClient(timeout=10) as client:
        type_path = "tv" if media_type == "tv" else "movie"
        resp = await client.get(
            f"{TMDB_BASE}/{type_path}/{tmdb_id}",
            params={"api_key": api_key, "append_to_response": "external_ids"}
        )
        data = resp.json()
        return {
            "imdb_id": data.get("external_ids", {}).get("imdb_id"),
            "title": data.get("title") or data.get("name"),
            "year": (data.get("release_date") or data.get("first_air_date") or "")[:4],
        }


def detect_language(label: str) -> str:
    lower = label.lower()
    if "hindi" in lower or "hin" in lower: return "Hindi"
    if "tamil" in lower or "tam" in lower: return "Tamil"
    if "telugu" in lower or "tel" in lower: return "Telugu"
    if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali"
    if "malayalam" in lower or "mal" in lower: return "Malayalam"
    if "kannada" in lower or "kan" in lower: return "Kannada"
    if "english" in lower or "eng" in lower or "en" == lower: return "English"
    if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian"
    if "french" in lower or "fra" in lower or "vf" in lower: return "French"
    if "german" in lower or "deu" in lower or "ger" in lower: return "German"
    if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish"
    if "multi" in lower: return "Multi"
    return "English"


def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: int = 16):
    """OpenSSL EVP_BytesToKey compatible key derivation (MD5 iterative)."""
    dtot = b""
    d = b""
    while len(dtot) < key_len + iv_len:
        d = hashlib.md5(d + password + salt).digest()
        dtot += d
    return dtot[:key_len], dtot[key_len:key_len + iv_len]


def normalize_title(title: str) -> str:
    """Normalize title by removing brackets, (Dub), (HD), etc."""
    cleaned = re.sub(r'\[[^\]]*\]', '', title)
    cleaned = re.sub(r'\((?:Dub|HD|Cam|TS|HDRip|BRRip|DVDRip|WEBRip|WEB-DL)\)', '', cleaned, flags=re.IGNORECASE)
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    return cleaned


def extract_language_from_title(title: str) -> str:
    """Extract language from title brackets like [Hindi], [Tamil] etc."""
    bracket_match = re.search(r'\[([^\]]+)\]', title)
    if bracket_match:
        lang_text = bracket_match.group(1)
        detected = detect_language(lang_text)
        if detected != "English" or lang_text.lower() == "english":
            return detected
    return ""


def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto", language: str = "English") -> dict:
    return {
        "source": source,
        "title": title,
        "quality": quality,
        "language": detect_language(language) if language else "English",
        "url": url,
        "type": "m3u8" if ".m3u8" in url else "direct",
    }


def _sf_norm(s: str) -> str:
    return re.sub(r"[^a-z0-9]", "", (s or "").lower())


# ---------- PurStream (Nuvio purstream.js): search + sheet API ----------

async def scrape_purstream(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []

    try:
        info = await get_tmdb_info(tmdb_id, media_type)
        title = info.get("title")
        if not title:
            return [], ["PurStream: no TMDB title"]

        headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://purstream.club/"}
        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client:
            resp = await client.get(f"https://api.purstream.club/api/v1/search-bar/search/{quote(str(title))}")
            items = resp.json().get("data", {}).get("items", {})
            candidates = []
            for key in ("movies", "tv", "series", "tvshows"):
                bucket = items.get(key) or {}
                sub = bucket.get("items") if isinstance(bucket, dict) else bucket
                if isinstance(sub, list):
                    candidates.extend(sub)

            # catalog items lack tmdbId -> match by title, verify tmdbId via sheet
            media_id, sheet = None, None
            for item in candidates:
                if _sf_norm(item.get("title")) == _sf_norm(title):
                    try:
                        probe = (await client.get(
                            f"https://api.purstream.club/api/v1/media/{item['id']}/sheet")).json()
                        if str(probe.get("data", {}).get("items", {}).get("tmdbId")) == str(tmdb_id):
                            media_id, sheet = item.get("id"), probe
                            break
                    except Exception:
                        continue
            if not media_id or sheet is None:
                return [], ["PurStream: title not found in catalog"]

            urls = sheet.get("data", {}).get("items", {}).get("urls", [])
            if media_type == "tv":
                s, e = season or 1, episode or 1
                pat = re.compile(rf"/S{s:02d}/E{e:02d}/|S{s}\.?E{e}\b", re.I)
                urls = [u for u in urls if pat.search(u.get("url") or "") or pat.search(u.get("name") or "")]

            for u in urls:
                url = u.get("url")
                if not url:
                    continue
                name = u.get("name") or "PurStream"
                results.append(_sf_stream_result(f"PurStream/{name}", f"PurStream - {name}", url))

            if not results:
                errors.append("PurStream: no stream urls")

    except Exception as e:
        errors.append(f"PurStream: {str(e)}")

    return results, errors


# ---------- Movix (Nuvio movix.js): api.movix.cash direct API ----------

async def scrape_movix(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []

    try:
        headers = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://movix.cash/"}
        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=headers) as client:
            if media_type == "tv":
                url = f"https://api.movix.cash/api/purstream/tv/{tmdb_id}/stream"
                params = {"season": season or 1, "episode": episode or 1}
            else:
                url = f"https://api.movix.cash/api/purstream/movie/{tmdb_id}/stream"
                params = {}
            resp = await client.get(url, params=params)
            data = resp.json()
            if data.get("error"):
                return [], [f"Movix: {data.get('error')}"]

            for src in data.get("sources", []):
                surl = src.get("url")
                if not surl:
                    continue
                name = src.get("name") or "Movix"
                results.append(_sf_stream_result(f"Movix/{name}", f"Movix - {name}", surl))

            if not results:
                errors.append("Movix: no sources")

    except Exception as e:
        errors.append(f"Movix: {str(e)}")

    return results, errors


# ---------- HubCloud family resolver (MediaVanced hubcloud.py, generalized) ----------

_SF_LINK_PROVIDERS = re.compile(
    r'https?://[^\s"\'<>]*(?:hubcloud\.[a-z]+/(?:drive|video)/[A-Za-z0-9_\-]+'
    r'|hubdrive\.[a-z]+/file/[A-Za-z0-9]+'
    r'|hblinks\.[a-z]+/archives/\d+'
    r'|vcloud\.[a-z]+/[A-Za-z0-9]+'
    r'|nexdrive\.[a-z]+/[A-Za-z0-9]+'
    r'|abhilinks\.[a-z]+/archives/\d+/?)',
)
_SF_SPORTVERSE = re.compile(r'https?://sportverse\.cc/hubcloud\.php\?[^"\'<>]+')
_SF_MOBILE_UA = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Mobile Safari/537.36"


def _sf_extract_links(html: str) -> list:
    seen, out = set(), []
    for m in _SF_LINK_PROVIDERS.finditer(html or ""):
        u = m.group(0)
        if u not in seen:
            seen.add(u)
            out.append(u)
    return out


def _sf_pixeldrain_direct(u: str) -> str:
    m = re.search(r'pixeldrain\.[a-z]+/u/([A-Za-z0-9]+)', u)
    if m:
        return f"https://pixeldrain.com/api/file/{m.group(1)}?download"
    return u


async def _sf_resolve_hubcloud(client: httpx.AsyncClient, link: str) -> list:
    """Resolve one hubcloud-family page into direct file URLs."""
    out = []
    try:
        if "/video/" in link or "hubvid" in link:
            page = (await client.get(link)).text
            sport = _SF_SPORTVERSE.search(page)
            if sport:
                page = (await client.get(sport.group(0), headers={"Referer": link})).text
        else:
            page = (await client.post(link)).text
            m = re.search(r"var\s+url\s*=\s*'(https?://[^']+)'", page)
            if m:
                page = (await client.get(m.group(1))).text
        for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):
            u = b.group(1)
            chunk = page[b.start():b.start() + 800]
            fm = re.search(r'download="([^"]{5,110})"', chunk)
            fname = fm.group(1) if fm else ""
            if "pixeldrain" in u:
                out.append({"url": _sf_pixeldrain_direct(u), "label": fname or "Direct"})
            elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:
                out.append({"url": u, "label": fname or "Direct"})
            elif "cloudflarestorage" in u or "workers.dev" in u:
                out.append({"url": u, "label": fname or "Direct"})
    except Exception:
        pass
    return out


def _sf_quality_from_name(name: str) -> str:
    low = (name or "").lower()
    if "2160" in low or "4k" in low: return "4K"
    if "1080" in low: return "1080p FHD"
    if "720" in low: return "720p HD"
    if "480" in low: return "480p SD"
    return "Auto"


def _sf_lang_from_name(name: str) -> str:
    low = (name or "").lower()
    if "dual audio" in low or "multi" in low: return "Multi"
    langs = []
    if "hindi" in low or "esubs" in low: langs.append("Hindi")
    if "tamil" in low: langs.append("Tamil")
    if "telugu" in low: langs.append("Telugu")
    if "english" in low or "eng" in low: langs.append("English")
    return " + ".join(langs) if langs else "English"


def _sf_episode_matches(label: str, season: int, episode: int) -> bool:
    if not label:
        return True
    low = label.lower()
    s_ok = re.search(rf'\bs{season:02d}e{episode:02d}\b|s{season}\.?e{episode}\b|season.{season}\b', low)
    e_ok = re.search(rf'\be{episode:02d}\b|episode.{episode}\b|ep.{episode}\b|e{episode}\b', low)
    season_only = re.search(rf'season.{season}\b|s{season:02d}\b|s{season}\b', low)
    # Correct-episode or correct-season labels always match
    if s_ok or season_only or (e_ok and (season_only or "season" in low)):
        return True
    # Labels mentioning a DIFFERENT season/episode are rejected
    other = re.search(r'\bs\d{1,2}e\d{1,2}\b|season.\d+\b|\be\d{1,2}\b|episode.\d+\b', low)
    if other:
        return False
    # No markers at all -> generic pack link, accept
    return True


def _sf_hubcloud_results(source_name: str, resolved: list, media_type: str, season, episode) -> list:
    results = []
    seen_urls = set()
    for r in resolved:
        u, label = r["url"], r["label"]
        if u in seen_urls:
            continue
        seen_urls.add(u)
        if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):
            continue
        results.append(_sf_stream_result(
            f"{source_name}/HubCloud", f"{source_name} - {label or 'Direct'}", u,
            quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
    return results


PHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json"
VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"

_SF_HUB_HEADERS = {"User-Agent": _SF_MOBILE_UA, "Accept": "text/html,application/xhtml+xml,*/*", "Accept-Language": "en-US,en;q=0.5"}


# ===== Castle Scraper (hlowb.com API with AES-CBC) - v10 FIXED (multi-language m3u8) =====

async def scrape_castle(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []

    try:
        from Crypto.Cipher import AES
        from Crypto.Util.Padding import unpad

        info = await get_tmdb_info(tmdb_id, media_type)
        title = info.get("title", "")
        if not title:
            errors.append("Castle: No title from TMDB")
            return results, errors

        CASTLE_BASE = "https://api.hlowb.com"
        PKG = "com.external.castle"
        CH = "IndiaA"
        CLI = "1"
        LANG = "en-US"
        SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475"

        CASTLE_HEADERS = {
            "User-Agent": "okhttp/4.9.3",
            "Accept": "application/json",
            "Accept-Language": "en-US,en;q=0.9",
            "Connection": "Keep-Alive",
            "Referer": "https://api.hlowb.com",
        }

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:
            # Step 1: Get security key
            sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={
                "channel": CH, "clientType": CLI, "lang": LANG
            })
            if sec_r.status_code != 200:
                errors.append(f"Castle: sec key HTTP {sec_r.status_code}")
                return results, errors

            sec_j = sec_r.json()
            raw_k = sec_j.get("data", "")
            if not raw_k or not isinstance(raw_k, str):
                errors.append("Castle: bad sec key response")
                return results, errors

            # The security key may be base64-encoded or plain text
            try:
                sec_key = base64.b64decode(raw_k).decode("utf-8", errors="ignore")
            except Exception:
                sec_key = raw_k

            # AES decryption: key = first 16 chars of (sec_key + "T!BgJB"), IV = same
            combined = (sec_key + "T!BgJB")
            aes_k = (combined + "\x00" * max(0, 16 - len(combined)))[:16].encode("utf-8")
            aes_iv = aes_k

            def castle_decrypt(text):
                """Decrypt Castle API response."""
                d = text
                try:
                    j = json.loads(text)
                    if isinstance(j, dict) and isinstance(j.get("data"), str):
                        d = j["data"]
                except Exception:
                    pass

                # Try base64 decode first
                try:
                    raw = base64.b64decode(d)
                    c = AES.new(aes_k, AES.MODE_CBC, aes_iv)
                    dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
                    return json.loads(dec)
                except Exception:
                    pass

                # Try hex decode
                try:
                    raw = bytes.fromhex(d)
                    c = AES.new(aes_k, AES.MODE_CBC, aes_iv)
                    dec = unpad(c.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
                    return json.loads(dec)
                except Exception:
                    pass

                # Try plain JSON (some endpoints may return unencrypted)
                try:
                    return json.loads(text)
                except Exception:
                    raise ValueError(f"Castle decrypt failed for data length={len(d)}")

            # Step 2: Search
            kw = f"{title} {info.get('year', '')}".strip()
            sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={
                "channel": CH, "clientType": CLI, "keyword": kw, "lang": LANG,
                "mode": "1", "packageName": PKG, "page": "1", "size": "30"
            })
            if sr.status_code != 200:
                errors.append(f"Castle: search HTTP {sr.status_code}")
                return results, errors

            try:
                sp = castle_decrypt(sr.text)
            except Exception as e:
                errors.append(f"Castle: search decrypt fail: {e}")
                return results, errors

            if not isinstance(sp, dict) or sp.get("code") != 200:
                errors.append(f"Castle: search API error (code={sp.get('code') if isinstance(sp, dict) else 'N/A'})")
                return results, errors

            db = sp.get("data", {})
            if isinstance(db, str):
                try:
                    db = json.loads(db)
                except Exception:
                    db = {}
            rows = db.get("rows", []) if isinstance(db, dict) else []
            if not rows:
                errors.append("Castle: no search results")
                return results, errors

            # Match by title - also check subjectType for movie/tv filtering
            mid = None
            tl = normalize_title(title).lower()
            target_subject_type = 1 if media_type == "movie" else 2

            # First try: exact normalized title match + correct subjectType
            for r in rows:
                if not isinstance(r, dict):
                    continue
                rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
                r_type = r.get("subjectType", r.get("type", 0))
                if tl == rt and r_type == target_subject_type:
                    mid = r.get("id")
                    break

            # Second try: substring match + correct subjectType
            if not mid:
                for r in rows:
                    if not isinstance(r, dict):
                        continue
                    rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
                    r_type = r.get("subjectType", r.get("type", 0))
                    if (tl in rt or rt in tl) and r_type == target_subject_type:
                        mid = r.get("id")
                        break

            # Third try: exact/substring match without type filter
            if not mid:
                for r in rows:
                    if not isinstance(r, dict):
                        continue
                    rt = normalize_title(r.get("title", "") or r.get("name", "")).lower()
                    if tl in rt or rt in tl:
                        mid = r.get("id")
                        break

            # Fallback: first result
            if not mid and isinstance(rows[0], dict):
                mid = rows[0].get("id")

            if not mid:
                errors.append("Castle: no match")
                return results, errors
            mid = str(mid)

            # Step 3: Get details
            dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={
                "channel": CH, "clientType": CLI, "lang": LANG,
                "movieId": mid, "packageName": PKG
            })
            if dr.status_code != 200:
                errors.append(f"Castle: detail HTTP {dr.status_code}")
                return results, errors

            try:
                dp = castle_decrypt(dr.text)
            except Exception:
                dp = {}

            dd = dp.get("data", dp)
            if isinstance(dd, str):
                try:
                    dd = json.loads(dd)
                except Exception:
                    dd = {}
            if not isinstance(dd, dict):
                dd = {}

            # For TV: navigate seasons/episodes
            ep_id = mid  # Default: same as movieId for movies
            if media_type == "tv" and season and episode:
                seasons = dd.get("seasons", [])
                s_id = mid
                for s_item in seasons:
                    if not isinstance(s_item, dict):
                        continue
                    if s_item.get("number") == season or s_item.get("seasonNum") == season:
                        sid = s_item.get("id")
                        if sid and str(sid) != mid:
                            s_id = str(sid)
                            sdr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={
                                "channel": CH, "clientType": CLI, "lang": LANG,
                                "movieId": s_id, "packageName": PKG
                            })
                            try:
                                sdp = castle_decrypt(sdr.text)
                                sdd = sdp.get("data", sdp)
                                if isinstance(sdd, dict):
                                    dd = sdd
                            except Exception:
                                pass
                        break
                eps = dd.get("episodes", [])
                for ep in eps:
                    if not isinstance(ep, dict):
                        continue
                    if ep.get("number") == episode or ep.get("episodeNum") == episode:
                        ep_id = str(ep.get("id", ""))
                        break
                mid = s_id
            else:
                # Movies: check for episodes list (some movies have a single "episode")
                eps = dd.get("episodes", [])
                if eps and isinstance(eps[0], dict):
                    ep_id = str(eps[0].get("id", ""))

            # Step 4: Get video via getVideo2 - v10 fixed flow (multi-language, ported from Nuvio castle.js)
            CASTLE_LANGS = [("English", "1003"), ("Tamil", "1033"), ("Telugu", "1037")]
            for lang_name, lang_id in CASTLE_LANGS:
                for resolution in [3, 2, 1]:  # Try 1080p, 720p, 480p
                    try:
                        body = {
                            "mode": "1",
                            "appMarket": "GuanWang",
                            "clientType": CLI,
                            "woolUser": "false",
                            "apkSignKey": SIGN,
                            "androidVersion": "13",
                            "movieId": mid,
                            "episodeId": str(ep_id),
                            "languageId": lang_id,
                            "isNewUser": "true",
                            "resolution": str(resolution),
                            "packageName": PKG,
                        }
                        vr = await client.post(
                            f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
                            params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},
                            json=body,
                            headers={"Content-Type": "application/json"}
                        )
                        if vr.status_code != 200:
                            continue

                        try:
                            vp = castle_decrypt(vr.text)
                        except Exception:
                            continue

                        vd = vp.get("data", vp)
                        if isinstance(vd, str):
                            try:
                                vd = json.loads(vd)
                            except Exception:
                                continue
                        if not isinstance(vd, dict):
                            continue

                        vurl = vd.get("videoUrl", "")
                        if not vurl:
                            continue

                        quality_map = {1: "480p", 2: "720p", 3: "1080p"}
                        quality = quality_map.get(resolution, "720p")

                        vids = vd.get("videos", [])
                        if vids and isinstance(vids, list):
                            for v in vids:
                                if not isinstance(v, dict):
                                    continue
                                vu = v.get("url", vurl)
                                q = v.get("resolutionDescription", v.get("resolution", quality))
                                q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q))
                                subs = v.get("subtitles", [])
                                result_item = {
                                    "source": "Castle",
                                    "title": f"Castle [{lang_name}] - {q}",
                                    "quality": q,
                                    "language": lang_name,
                                    "url": vu,
                                    "type": "m3u8" if ".m3u8" in vu else "direct",
                                }
                                if subs:
                                    result_item["subtitles"] = subs
                                results.append(result_item)
                        else:
                            results.append({
                                "source": "Castle",
                                "title": f"Castle [{lang_name}] - {quality}",
                                "quality": quality,
                                "language": lang_name,
                                "url": vurl,
                                "type": "m3u8" if ".m3u8" in vurl else "direct",
                            })
                        break  # Got a stream, stop trying lower resolutions
                    except Exception:
                        continue

            # Deduplicate
            seen = set()
            uniq = []
            for r in results:
                if r["url"] not in seen:
                    seen.add(r["url"])
                    uniq.append(r)
            results = uniq

            if not results:
                errors.append("Castle: no streams found")

    except ImportError:
        errors.append("Castle: pycryptodome not installed")
    except Exception as e:
        errors.append(f"Castle ERR: {type(e).__name__}: {str(e)}")

    return results, errors


# ===== NetMirror Scraper (net27.cc embed-tmdb API) - v10 REWRITE =====
# Ported from All-in-One-Nuvio netmirror.js (live-tested: mp4 360p-1080p, movie+TV)

_NETMIRROR_BASE = "https://net27.cc"
_NETMIRROR_HEADERS = {
    "Accept": "application/json, text/plain, */*",
    "Referer": "https://net27.cc/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",
}


async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    """NetMirror via net27.cc - takes TMDB id directly, returns direct mp4 streams (multi-res)."""
    results = []
    errors = []
    try:
        url = f"{_NETMIRROR_BASE}/api/embed-tmdb/{tmdb_id}"
        if media_type == "tv":
            url += f"?type=tv&s={season or 1}&e={episode or 1}"

        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            resp = await client.get(url, headers=_NETMIRROR_HEADERS)
            if resp.status_code != 200:
                errors.append(f"NetMirror: embed-tmdb HTTP {resp.status_code}")
                return results, errors
            try:
                data = resp.json()
            except Exception:
                errors.append("NetMirror: non-JSON response")
                return results, errors

        streams = data.get("streams") or []
        if not isinstance(streams, list) or not streams:
            # Fallback: single mp4 field
            mp4 = data.get("mp4")
            if mp4:
                streams = [{"url": mp4, "resolution": data.get("resolution", "Auto")}]
            else:
                errors.append("NetMirror: no streams in response")
                return results, errors

        for s in streams:
            if not isinstance(s, dict):
                continue
            u = s.get("url")
            if not u:
                continue
            res = str(s.get("resolution") or "").strip()
            quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto")
            results.append(_sf_stream_result(
                "NetMirror", f"NetMirror - {quality}", u,
                quality=quality, language="Multi"))
    except Exception as ex:
        errors.append(f"NetMirror: {str(ex)}")
    return results, errors


# ===== VidLove Scraper (api.shows.st JSON API) - v10 NEW =====
# Ported from player.vidlove.cc frontend (replaces 111movies which redirects here)
# Live-tested: m3u8 master playlist, movie+TV

_VIDLOVE_API = "https://api.shows.st"


async def scrape_vidlove(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []
    try:
        if media_type == "tv":
            url = f"{_VIDLOVE_API}/tv?id={tmdb_id}&season={season or 1}&episode={episode or 1}&mode=json"
        else:
            url = f"{_VIDLOVE_API}/movie?id={tmdb_id}&mode=json"

        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            resp = await client.get(url, headers={
                "User-Agent": HEADERS["User-Agent"],
                "Referer": "https://player.vidlove.cc/",
                "Accept": "application/json, text/plain, */*",
            })
            if resp.status_code != 200:
                errors.append(f"VidLove: API HTTP {resp.status_code}")
                return results, errors
            data = resp.json()

        src = data.get("source") or {}
        stream_url = src.get("url")
        if not stream_url:
            errors.append("VidLove: no source url in response")
            return results, errors

        label = src.get("label") or "VidLove"
        results.append(_sf_stream_result(
            "VidLove", f"VidLove - {label}", stream_url,
            quality="Auto (multi-quality)", language="Multi"))
    except Exception as ex:
        errors.append(f"VidLove: {str(ex)}")
    return results, errors


# ===== PlayBox Scraper (streamdata.vaplayer.ru API) - v10 NEW =====
# Ported from MediaVanced playbox.py / Nuvio playimdb.js (live-tested: m3u8 multi-quality, movie+TV)

_PLAYBOX_API = "https://streamdata.vaplayer.ru/api.php"


async def scrape_playbox(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []
    try:
        url = f"{_PLAYBOX_API}?tmdb={tmdb_id}&type={media_type}"
        if media_type != "movie":
            url += f"&season={season or 1}&episode={episode or 1}"

        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            resp = await client.get(url, headers={
                "User-Agent": HEADERS["User-Agent"],
                "Referer": "https://nextgencloudfabric.com",
                "Origin": "https://nextgencloudfabric.com",
                "Accept": "*/*",
            })
            if resp.status_code != 200:
                errors.append(f"PlayBox: API HTTP {resp.status_code}")
                return results, errors
            data = resp.json()

        urls = ((data.get("data") or {}).get("stream_urls")) or []
        if not urls:
            errors.append("PlayBox: no stream urls")
            return results, errors

        for u in urls:
            if not u or not isinstance(u, str):
                continue
            results.append(_sf_stream_result(
                "PlayBox", "PlayBox - m3u8", u,
                quality="Auto", language="Multi"))
    except Exception as ex:
        errors.append(f"PlayBox: {str(ex)}")
    return results, errors


# ---------- VegaMovies (Nuvio vegamovies.js port, v10): search.php?q=imdb -> wp-json -> nexdrive -> vcloud/hubcloud ----------
# Live-tested: direct MKV (2160p/1080p/720p) via pixeldrain + r2, movie+TV

VEGA_URLS = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"
_VEGA_DEFAULT_SITE = "https://new2.vegamovies.futbol"


def _sf_b64_all(s: str) -> str:
    s = s.strip()
    for _ in range(2):
        try:
            pad = s + "=" * (-len(s) % 4)
            s = base64.b64decode(pad).decode("utf-8", errors="ignore")
        except Exception:
            break
    return s


async def _sf_resolve_vcloud(client: httpx.AsyncClient, vcloud_url: str, referer: str) -> list:
    """Resolve a vcloud.fit page: fetch -> decode atob(atob()) token url -> fetch -> extract btn links."""
    out = []
    try:
        page = (await client.get(vcloud_url, headers={
            "User-Agent": _SF_MOBILE_UA, "Referer": referer, "Cookie": "xla=s4t"})).text
        # Tokenized re-entry URL (double base64) - follow it
        m = re.search(r"atob\(atob\('([A-Za-z0-9+/=]+)'\)\)", page)
        if m:
            dec = _sf_b64_all(m.group(1))
            if dec.startswith("http"):
                page2 = (await client.get(dec, headers={
                    "User-Agent": _SF_MOBILE_UA, "Referer": vcloud_url, "Cookie": "xla=s4t"})).text
                page = page2
        # Extract download button links
        for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]+class="[^"]*btn[^"]*"', page):
            u = b.group(1)
            chunk = page[b.start():b.start() + 800]
            fm = re.search(r'download="([^"]{5,110})"', chunk)
            fname = fm.group(1) if fm else "Direct"
            if "pixeldrain" in u:
                out.append({"url": _sf_pixeldrain_direct(u), "label": fname})
            elif "cloudflarestorage" in u or "workers.dev" in u or ".r2.dev" in u:
                out.append({"url": u, "label": fname})
            elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) and ".zip" not in u:
                out.append({"url": u, "label": fname})
    except Exception:
        pass
    return out


async def scrape_vegamovies(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []
    try:
        info = await get_tmdb_info(tmdb_id, media_type)
        imdb_id = info.get("imdb_id")
        if not imdb_id:
            errors.append("VegaMovies: no imdb id")
            return results, errors

        # Resolve current domain
        site = _VEGA_DEFAULT_SITE
        try:
            async with httpx.AsyncClient(timeout=10) as c:
                cfg = (await c.get(VEGA_URLS)).json()
            if isinstance(cfg, dict) and cfg.get("vegamovies"):
                site = cfg["vegamovies"].rstrip("/")
        except Exception:
            pass

        async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client:
            # Step 1: search by imdb id
            sr = await client.get(f"{site}/search.php", params={"q": imdb_id, "page": 1, "per_page": 15})
            if sr.status_code != 200:
                errors.append(f"VegaMovies: search HTTP {sr.status_code}")
                return results, errors
            try:
                sdata = sr.json()
            except Exception:
                errors.append("VegaMovies: search non-JSON")
                return results, errors

            # Typesense-style response: {"found": n, "hits": [{"document": {...}}]}
            hits = sdata.get("hits") or []
            posts = [h.get("document", h) if isinstance(h, dict) else h for h in hits]
            if not posts:
                errors.append("VegaMovies: no search results")
                return results, errors

            # Match post by title
            title_norm = _sf_norm(info.get("title") or "")
            year = str(info.get("year") or "")
            chosen = None
            for p in posts:
                if not isinstance(p, dict):
                    continue
                pt = p.get("post_title") or p.get("title") or ""
                if title_norm and title_norm in _sf_norm(pt):
                    chosen = p
                    break
            if chosen is None and posts:
                chosen = posts[0]

            post_id = chosen.get("id") if isinstance(chosen, dict) else None
            if not post_id:
                errors.append("VegaMovies: no matching post")
                return results, errors

            # Step 2: fetch post content
            pr = await client.get(f"{site}/wp-json/wp/v2/posts/{post_id}")
            if pr.status_code != 200:
                errors.append(f"VegaMovies: post HTTP {pr.status_code}")
                return results, errors
            content = (pr.json().get("content") or {}).get("rendered", "")
            nexdrive_links = re.findall(r'https?://nexdrive\.[a-z]+/[a-z0-9]+/[a-zA-Z0-9]+/?', content)
            hubcloud_links = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', content)
            if not nexdrive_links and not hubcloud_links:
                # Broad fallback: any locker link in content
                nexdrive_links = re.findall(r'https?://[^\s"\'<>]*(?:vcloud|nexdrive|dgdrive|fastdl)\.[a-z]+/[^\s"\'<>]{4,60}', content)

            resolved = []
            for hl in hubcloud_links[:4]:
                resolved.extend(await _sf_resolve_hubcloud(client, hl))
            for nl in nexdrive_links[:5]:
                if len(resolved) >= 10:
                    break
                try:
                    np = (await client.get(nl, headers={
                        "User-Agent": _SF_MOBILE_UA, "Referer": f"{site}/"})).text
                except Exception:
                    continue
                # hubcloud links inside nexdrive page
                for hl in re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', np)[:2]:
                    resolved.extend(await _sf_resolve_hubcloud(client, hl))
                # vcloud links inside nexdrive page (2 fastest: usually 1080p/720p first)
                vc_refs = list(dict.fromkeys(re.findall(r'https?://vcloud\.[a-z]+/[a-zA-Z0-9]+', np)))[:2]
                for vl in vc_refs:
                    resolved.extend(await _sf_resolve_vcloud(client, vl, str(nl)))

            results.extend(_sf_hubcloud_results("VegaMovies", resolved, media_type, season, episode))
            if not results:
                errors.append("VegaMovies: no resolvable streams")
    except Exception as ex:
        errors.append(f"VegaMovies: {str(ex)}")
    return results, errors


# ---------- MoviesHunt (Nuvio movieshunt.js port, v10): WP search -> post -> abhilinks -> hubcloud ----------
# Live-tested: direct MKV via pixeldrain, movie+TV

_MH_SITES = ["https://movieshunt.casa", "https://movieshunt.run"]


async def scrape_movieshunt(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results = []
    errors = []
    try:
        info = await get_tmdb_info(tmdb_id, media_type)
        title = info.get("title") or ""
        imdb_id = info.get("imdb_id")
        if not title:
            errors.append("MoviesHunt: no title")
            return results, errors

        q = title.replace(" ", "+")
        async with httpx.AsyncClient(timeout=25, follow_redirects=True, headers=_SF_HUB_HEADERS) as client:
            post_url = None
            for site in _MH_SITES:
                try:
                    sr = await client.get(f"{site}/", params={"s": q})
                    if sr.status_code != 200:
                        continue
                    post_links = re.findall(
                        rf'href="({re.escape(site)}/[a-z0-9-]{{10,140}}/?)"',
                        sr.text)
                    post_links = [p for p in post_links if not re.search(r'(disclaimer|contact|how-to|request|find-movie|dmca|privacy|about|page/)', p)]
                    if post_links:
                        post_url = post_links[0]
                        break
                except Exception:
                    continue

            if not post_url:
                errors.append("MoviesHunt: no matching post")
                return results, errors

            pr = await client.get(post_url)
            content = pr.text

            # abhilinks archive links (episode/movie pages)
            abhi_links = re.findall(r'https?://abhilinks\.site/archives/[a-z0-9]+/?', content)
            # direct hubcloud links
            hc_links = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', content)

            resolved = []
            for hl in hc_links[:8]:
                resolved.extend(await _sf_resolve_hubcloud(client, hl))

            for al in list(dict.fromkeys(abhi_links))[:6]:
                if len(resolved) >= 8:
                    break
                try:
                    ar = await client.get(al, headers={"User-Agent": _SF_MOBILE_UA, "Referer": post_url})
                except Exception:
                    continue
                ahc = re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[a-zA-Z0-9_]+', ar.text)
                for hl in ahc[:3]:
                    resolved.extend(await _sf_resolve_hubcloud(client, hl))

            results.extend(_sf_hubcloud_results("MoviesHunt", resolved, media_type, season, episode))
            if not results:
                errors.append("MoviesHunt: no resolvable streams")
    except Exception as ex:
        errors.append(f"MoviesHunt: {str(ex)}")
    return results, errors


# ===== Source Map =====

SOURCE_MAP = {
    "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),
               "languages": ["English", "Tamil", "Telugu"], "reliability": "high",
               "note": "hlowb.com API, AES-CBC, multi-language m3u8 (EN/Tamil/Telugu), fixed languageId flow"},
    "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),
                  "languages": ["Hindi", "English", "Multi"], "reliability": "high",
                  "note": "net27.cc embed-tmdb API, direct mp4 360p-1080p, TMDB id based, movie+TV"},
    "vidlove": {"name": "VidLove", "fn": lambda tid, mt, s, e: scrape_vidlove(tid, mt, s, e),
                "languages": ["English", "Multi"], "reliability": "high",
                "note": "api.shows.st JSON API, m3u8 master multi-quality, replaces dead 111movies"},
    "playbox": {"name": "PlayBox", "fn": lambda tid, mt, s, e: scrape_playbox(tid, mt, s, e),
                "languages": ["English", "Multi"], "reliability": "high",
                "note": "streamdata.vaplayer.ru API, multi-quality m3u8, TMDB id based"},
    "movix": {"name": "Movix", "fn": lambda tid, mt, s, e: scrape_movix(tid, mt, s, e),
              "languages": ["English", "Multi"], "reliability": "high",
              "note": "api.movix.cash direct API, m3u8 1080p"},
    "purstream": {"name": "PurStream", "fn": lambda tid, mt, s, e: scrape_purstream(tid, mt, s, e),
                  "languages": ["English", "Multi"], "reliability": "high",
                  "note": "purstream.club search+sheet API, m3u8, episodes supported"},
    "movieshunt": {"name": "MoviesHunt", "fn": lambda tid, mt, s, e: scrape_movieshunt(tid, mt, s, e),
                   "languages": ["Hindi", "English", "Multi"], "reliability": "medium",
                   "note": "WP search (movieshunt.casa) + abhilinks + hubcloud, direct MKV via pixeldrain/r2"},
    "vegamovies": {"name": "VegaMovies", "fn": lambda tid, mt, s, e: scrape_vegamovies(tid, mt, s, e),
                   "languages": ["Hindi", "English", "Multi"], "reliability": "medium",
                   "note": "search.php?q=imdb + nexdrive + vcloud chain, direct MKV up to 4K"},
}

DEFAULT_SOURCES = ["castle", "netmirror", "vidlove", "playbox", "movix"]

# ===== Helper: Run scrapers =====

async def run_scrape(tmdb_id: int, media_type: str, season: int = None, episode: int = None, source_keys: list = None):
    info = await get_tmdb_info(tmdb_id, media_type)
    title = info.get("title")
    imdb_id = info.get("imdb_id")

    all_results = []
    all_errors = []
    keys = source_keys or DEFAULT_SOURCES

    async def run_one(key: str):
        src = SOURCE_MAP.get(key)
        if not src:
            return [], [f"{key}: Unknown source"]
        try:
            r, e = await asyncio.wait_for(src["fn"](tmdb_id, media_type, season, episode), timeout=45)
            return r, e
        except asyncio.TimeoutError:
            return [], [f"{src['name']}: Timeout (45s)"]
        except Exception as ex:
            return [], [f"{src['name']}: {str(ex)}"]

    tasks = [run_one(k) for k in keys]
    task_results = await asyncio.gather(*tasks, return_exceptions=True)

    for result in task_results:
        if isinstance(result, Exception):
            all_errors.append(f"Scraper failed: {str(result)}")
        else:
            r, e = result
            all_results.extend(r)
            all_errors.extend(e)

    seen_urls = set()
    unique_results = []
    for r in all_results:
        if r["url"] not in seen_urls:
            seen_urls.add(r["url"])
            unique_results.append(r)

    return {
        "success": len(unique_results) > 0,
        "tmdb_id": tmdb_id,
        "imdb_id": imdb_id,
        "title": title,
        "year": info.get("year"),
        "results": unique_results,
        "errors": all_errors if all_errors else None,
    }


# ===== Root: JSON documentation =====

@app.get("/")
async def root():
    return {
        "api": "StreamForge",
        "version": "10.0.0",
        "description": "Multi-language m3u8/mp4/MKV stream scraper",
        "endpoints": {
            "movie": {"all_sources": "/movie/{tmdb_id}", "single_source": "/movie/{tmdb_id}/{source}",
                       "example": "/movie/912649", "example_source": "/movie/912649/castle"},
            "tv": {"all_sources": "/tv/{tmdb_id}/{season}/{episode}", "single_source": "/tv/{tmdb_id}/{season}/{episode}/{source}",
                    "example": "/tv/1396/1/1", "example_source": "/tv/1396/1/1/netmirror"},
            "search": {"path": "/search/{query}", "example": "/search/Venom"},
            "api_endpoints": {"health": "GET /api/health", "sources": "GET /api/sources", "search": "GET /api/search?q={query}",
                               "scrape": "POST /api/scrape", "scrape_all": "POST /api/scrape/all"},
        },
        "sources": {k: {kk: vv for kk, vv in v.items() if kk != "fn"} for k, v in SOURCE_MAP.items()},
        "default_sources": DEFAULT_SOURCES,
        "changelog_v10": {
            "updated": [
                "Castle - fixed getVideo2 (appMarket=GuanWang, languageId 1003/1033/1037) -> multi-language m3u8 restored",
                "NetMirror - rewritten on net27.cc embed-tmdb (TMDB-id based, mp4 360p-1080p, movie+TV)",
                "MoviesHunt - new domains (movieshunt.casa) + abhilinks + hubcloud.cx resolver, verified MKV via pixeldrain",
                "VegaMovies - new flow (search.php?q=imdb -> wp-json -> nexdrive -> vcloud token chain), up to 4K MKV",
            ],
            "added": [
                "VidLove - api.shows.st, m3u8 master multi-quality, movie+TV (replaces dead 111movies)",
                "PlayBox - streamdata.vaplayer.ru, multi-quality m3u8, movie+TV",
            ],
            "kept": ["Movix", "PurStream (verified still working)"],
            "removed": {
                "Cineby": "shutting down (user request)",
                "Videasy": "cineby-owned (user request)",
                "VidRock": "dead (vidrock.net 403, vidrock.ru timeout)",
                "MovieBox": "API removed (themoviebox.org -> HTML, fmoviesunblocked 404)",
                "AllMovieLand": "HTTP 403 (Cloudflare)",
                "VidLink": "no playlist in response (dead)",
                "VidSrc": "cloudnestra flow broken",
                "M4UHD": "m4uhd.vip Cloudflare 403",
                "VidFast": "worker route config stale vs site rebuild",
                "ShowBox": "febbox.com DNS dead",
                "GoatAPI": "empty responses",
                "HDHub4u": "DNS dead",
                "Movies4u": "m4uplay player fully string-obfuscated, unverifiable",
            },
        },
        "source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"],
        "tips": [
            "No source = default sources (castle, netmirror, vidlove, playbox, movix) - the verified-working set",
            "Castle: multi-language m3u8 (English/Tamil/Telugu), best for new Bollywood/Hollywood",
            "NetMirror: instant mp4 links 360p-1080p, movie+TV, TMDB id based",
            "VidLove/PlayBox/Movix: m3u8, work for both movie and TV",
            "MoviesHunt/VegaMovies: direct MKV downloads (Hindi multi-audio), movies+TV packs",
            "Direct MKV links work in VLC/mpv; m3u8 works in any HLS player",
        ],
    }


# ===== Simple GET endpoints =====

@app.get("/movie/{tmdb_id}")
async def movie_all(tmdb_id: int):
    return await run_scrape(tmdb_id, "movie")

@app.get("/movie/{tmdb_id}/{source}")
async def movie_source(tmdb_id: int, source: str):
    source = source.lower()
    if source not in SOURCE_MAP:
        raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})
    return await run_scrape(tmdb_id, "movie", source_keys=[source])

@app.get("/tv/{tmdb_id}/{season}/{episode}")
async def tv_all(tmdb_id: int, season: int, episode: int):
    return await run_scrape(tmdb_id, "tv", season=season, episode=episode)

@app.get("/tv/{tmdb_id}/{season}/{episode}/{source}")
async def tv_source(tmdb_id: int, season: int, episode: int, source: str):
    source = source.lower()
    if source not in SOURCE_MAP:
        raise HTTPException(400, {"error": f"Unknown source '{source}'", "available": list(SOURCE_MAP.keys())})
    return await run_scrape(tmdb_id, "tv", season=season, episode=episode, source_keys=[source])

@app.get("/search/{query}")
async def search_simple(query: str, page: int = 1):
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.get(
            f"{TMDB_BASE}/search/multi",
            params={"api_key": TMDB_API_KEY, "query": query, "page": page, "include_adult": False}
        )
        data = resp.json()
        filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]

        results = []
        for r in filtered[:20]:
            mid = r.get("id")
            mt = r.get("media_type", "movie")
            t = r.get("title") or r.get("name", "Unknown")
            year = (r.get("release_date") or r.get("first_air_date") or "")[:4]
            results.append({
                "id": mid,
                "type": "TV" if mt == "tv" else "Movie",
                "title": t,
                "year": year,
                "url": f"/{mt}/{mid}" if mt == "movie" else f"/tv/{mid}/1/1",
            })

        return {
            "query": query,
            "count": len(results),
            "results": results,
        }


# ===== JSON API endpoints =====

@app.get("/api/health")
async def health():
    return {"status": "ok", "timestamp": int(time.time())}



@app.get("/api/sources")
async def list_sources():
    return {
        "sources": {key: {"name": src["name"], "languages": src["languages"], "reliability": src["reliability"],
                           **({"note": src["note"]} if "note" in src else {})}
                    for key, src in SOURCE_MAP.items()},
        "default": DEFAULT_SOURCES,
    }

@app.get("/api/search")
async def search_tmdb(q: str = Query(...), page: int = 1):
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.get(
            f"{TMDB_BASE}/search/multi",
            params={"api_key": TMDB_API_KEY, "query": q, "page": page, "include_adult": False}
        )
        data = resp.json()
        filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")]
        return {
            "page": data.get("page"),
            "total_pages": data.get("total_pages"),
            "total_results": data.get("total_results"),
            "results": filtered,
        }

@app.post("/api/scrape")
async def scrape(request: ScrapeRequest):
    source_keys = None
    if request.sources:
        source_keys = [s.lower() for s in request.sources]
    return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, source_keys)

@app.post("/api/scrape/all")
async def scrape_all(request: ScrapeRequest):
    return await run_scrape(request.tmdb_id, request.media_type, request.season, request.episode, list(SOURCE_MAP.keys()))


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)