File size: 108,201 Bytes
a330af4
8afa4f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68dd2ae
 
d448306
 
 
 
 
 
 
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
854ee16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a330af4
 
8d13577
a330af4
8d13577
a330af4
 
 
 
 
699389b
a330af4
 
854ee16
900c3a8
8d13577
8afa4f1
 
a330af4
 
 
8d13577
8afa4f1
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
0334f45
 
 
 
 
 
 
 
 
 
 
 
8d13577
 
93094bf
a330af4
 
900c3a8
 
 
 
 
 
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17a438c
 
 
 
 
 
 
 
 
 
 
cb18578
8d13577
 
854ee16
 
8d13577
 
 
e4b4835
 
 
 
 
 
 
8d13577
 
 
 
 
 
854ee16
 
8d13577
e4b4835
a330af4
e4b4835
 
a330af4
d59d8ea
854ee16
 
 
 
 
 
 
 
 
 
 
e4b4835
 
854ee16
 
 
 
 
e4b4835
8d13577
854ee16
 
 
 
 
 
 
 
 
 
 
 
8d13577
854ee16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d13577
 
854ee16
8d13577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854ee16
 
8d13577
854ee16
 
 
 
8d13577
d59d8ea
854ee16
 
8d13577
 
 
 
854ee16
8d13577
 
d59d8ea
854ee16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d13577
854ee16
8d13577
 
 
 
854ee16
 
8d13577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854ee16
 
8d13577
 
 
 
 
 
 
 
 
 
 
854ee16
 
8d13577
 
 
 
 
 
 
 
 
d59d8ea
8d13577
854ee16
 
 
 
 
8d13577
 
854ee16
 
 
 
 
d59d8ea
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d13577
e4b4835
 
 
 
 
 
 
 
 
 
 
 
8d13577
e4b4835
 
 
 
 
8d13577
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf3320
1d6e15b
 
 
 
 
900c3a8
 
1d6e15b
 
900c3a8
 
f0eee2c
1d6e15b
 
cb18578
68dd2ae
cb18578
68dd2ae
cb18578
f0eee2c
 
900c3a8
e6abf12
68dd2ae
cb18578
68dd2ae
 
 
 
f0eee2c
68dd2ae
f0eee2c
 
 
68dd2ae
f0eee2c
5bf3320
f0eee2c
 
 
cb18578
 
68dd2ae
cb18578
68dd2ae
cb18578
5bf3320
68dd2ae
 
 
 
 
 
 
 
cb18578
68dd2ae
 
cb18578
68dd2ae
f0eee2c
 
68dd2ae
 
f0eee2c
 
 
900c3a8
5bf3320
cb18578
5bf3320
f0eee2c
900c3a8
f0eee2c
cb18578
5bf3320
 
f0eee2c
 
cb18578
 
 
 
30720b7
5bf3320
30720b7
5bf3320
900c3a8
68dd2ae
 
 
cb18578
68dd2ae
 
 
 
f0eee2c
cb18578
 
68dd2ae
f0eee2c
900c3a8
68dd2ae
cb18578
 
 
68dd2ae
 
cb18578
 
68dd2ae
cb18578
 
 
68dd2ae
cb18578
 
 
68dd2ae
30720b7
68dd2ae
f0eee2c
900c3a8
 
68dd2ae
 
 
 
 
 
 
 
cb18578
68dd2ae
cb18578
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0eee2c
5bf3320
68dd2ae
 
 
cb18578
 
 
68dd2ae
5bf3320
68dd2ae
 
 
 
 
 
 
f0eee2c
68dd2ae
5bf3320
68dd2ae
 
 
 
 
 
 
 
 
900c3a8
68dd2ae
 
f0eee2c
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30720b7
68dd2ae
cb18578
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d6e15b
68dd2ae
 
 
 
 
 
 
1d6e15b
68dd2ae
 
 
 
 
 
 
 
 
 
1d6e15b
900c3a8
 
1d6e15b
f0eee2c
1d6e15b
 
 
cb18578
68dd2ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4b4835
 
8d13577
68dd2ae
 
e4b4835
 
 
8d13577
e4b4835
 
1d6e15b
e4b4835
1d6e15b
 
 
e4b4835
 
 
1d6e15b
e4b4835
 
 
 
 
 
 
 
 
900c3a8
1d6e15b
8d13577
 
 
 
68dd2ae
8d13577
68dd2ae
8d13577
 
 
 
 
 
68dd2ae
 
 
 
8d13577
68dd2ae
 
8d13577
 
 
68dd2ae
 
 
 
 
 
 
db41b9b
68dd2ae
 
 
 
 
 
 
 
e4b4835
8d13577
 
68dd2ae
 
e4b4835
68dd2ae
 
 
 
e4b4835
7fcfe8f
8d13577
68dd2ae
8d13577
854ee16
e4b4835
 
db41b9b
8d13577
db41b9b
e4b4835
db41b9b
 
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
 
 
db41b9b
e4b4835
 
 
854ee16
 
 
 
 
e4b4835
854ee16
 
e4b4835
 
 
db41b9b
 
8d13577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c5fb7f
 
 
 
8d13577
854ee16
8d13577
 
 
 
 
854ee16
 
db83d0b
1c5fb7f
57f30e5
854ee16
 
 
8d13577
 
 
 
854ee16
 
17a438c
 
 
8d13577
17a438c
8d13577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db83d0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d13577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
e4b4835
 
db41b9b
e4b4835
 
 
 
 
 
 
 
 
 
 
 
 
db41b9b
 
e4b4835
 
 
 
 
 
 
 
 
db41b9b
 
 
 
e4b4835
db41b9b
e4b4835
8d13577
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
 
8d13577
 
 
8afa4f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
 
1d6e15b
68dd2ae
 
ad34132
68dd2ae
6bb47df
e4b4835
 
 
db41b9b
 
 
8d13577
 
 
 
 
 
db41b9b
e4b4835
 
8afa4f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
8afa4f1
 
 
8d13577
426e8e9
93094bf
426e8e9
 
 
 
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
8d13577
426e8e9
 
8d13577
426e8e9
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
 
 
1d6e15b
 
854ee16
1d6e15b
8d13577
854ee16
 
 
 
 
 
 
 
 
1d6e15b
 
8d13577
 
854ee16
 
 
 
 
 
 
 
 
1d6e15b
 
426e8e9
1d6e15b
426e8e9
 
93094bf
 
1d6e15b
93094bf
426e8e9
 
 
93094bf
a330af4
 
426e8e9
93094bf
 
68dd2ae
e4b4835
93094bf
e4b4835
 
 
 
 
854ee16
 
e4b4835
 
93094bf
e4b4835
93094bf
854ee16
 
 
 
 
 
 
 
 
 
 
 
 
8d13577
 
0c6105a
e4b4835
 
8d13577
 
 
 
e4b4835
8d13577
 
 
 
db41b9b
e4b4835
93094bf
8d13577
854ee16
 
8d13577
 
854ee16
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
"""
StreamForge API v14 - Multi-Language Stream Scraper
v14 (Vyla SDK provider wave):
  - 8 NEW sources ported from the Vyla SDK (github.com/vyla-entertainment/sdk,
    40 provider files tested one-by-one with playlist+segment verification from
    a datacenter IP):
      WORKING -> integrated: vidfast (2160p fMP4), vidup, meowtv (castle-CDN
      multi-language), lookmovie, lmscript, fsonic (direct MP4), vidrock
      (AES-GCM), hexa (intermittent).
      DEAD from datacenter (documented, NOT integrated): vidlink (site down,
      403s), vidsync (enc dec issues), pengu (google auth wall), videasy
      (Cineby property - excluded per policy), vidnest (playlist 403), cinesu
      (playlist 403), vidfast-via-nuvio (old impl), anikoto/anineko (segment
      403), vidrift/vidcore/vidvault/opstream/peachify/vixsrc/xpass/1embed/
      cinejoy/flaxmovies/fsharetv/fsonline/mapple/kisskh/anizone/anipm/
      anihq/123anime/reanime/kickassanime (no streams / anime-only catalogs).
  - Note: vidfast/vidup/meowtv/hexa depend on enc-dec.app (public crypto relay
    the sites themselves use client-side; it is also what the Vyla SDK uses).
  - Known upstream catalog gaps: NetMirror genuinely lacks some older titles
    (e.g. Venom 2018 -> noSource:true from net27.cc upstream) - the API now
    returns 13+ other sources for such titles; players should fall back.
v13 (netmirror+castle rebuild, Nuvio port):
  - NetMirror REBUILT from All-in-One-Nuvio netmirror.js: the bcdnxw CDN 429s are
    REFERER-gating: the CDN requires Referer "https://videodownloader.site/"
    (exact, trailing slash; net27.cc referers get 429 from any IP).
    Verified: viewer device IP + correct referer -> 206 video/mp4 (PRIMARY:
    play url + returned headers, Nuvio-app model); non-blocked server via our
    proxy -> 206; bcdnxw additionally 426-range-blocks HF Spaces IPs (use the
    direct url+headers path there). Movie subtitles proxied (real SRT). NewTV
    platform fallback is dead upstream - not ported.
  - Castle REBUILT from All-in-One-Nuvio castle.js: v2.0.1 getVideo2 flow with
    correct seasons[] "movieId" traversal (fixes WRONG-EPISODE bug), correct
    movieType matching (2=Movies/1=TV), per-language tracks (Tamil/OST/English)
    + TV shared-stream fallback, VTT subtitles. img*.com CDNs serve TS segments
    disguised as image/jpeg - intentional upstream obfuscation, plays fine.
  - Tested & dead (NOT integrated): vidlink, vidfast, vidsrc.me, kurage, vixsrc,
    goated, 1shows, showbox, allmovieland, moviebox, vidrock, Nuvio NewTV.
  - NOT added per policy: Cineby (dead), Videasy (Cineby property - absent).
  - Vyla (docs.vyla.cc): private GitLab repo + no public hosted API - cannot be
    self-hosted without repo access (documented, not integrated).
  - All 6 default sources verified playable end-to-end (m3u8 playlist + segment
    fetch + real TS/MP4 bytes) from a datacenter IP.
v12 (client-playability release):
  - FIXED: all proxy URLs are now ABSOLUTE (https://space/proxy_range?u=...) - the v11
    relative (/proxy_range?...) URLs broke players that don't know the API base
    (this is why NetMirror/MOON "loaded but wouldn't play")
  - Proxy engine v2: Range passthrough on BOTH /proxy and /proxy_range, HEAD support,
    Origin header injection, content-sniffed m3u8 detection, and m3u8 playlists whose
    every key/variant/segment URI is rewritten to ABSOLUTE proxy URLs (any player works)
  - PlayBox: m3u8 served through the proxy with Referer+Origin+UA injected - its gateway
    intermittently gates direct client fetches with a JSON error page (red tests)
  - Movies4u: every candidate m3u8 is validated at scrape time (acek-cdn sometimes serves
    PNG block pages / dead tokens) - only verified playlists are returned
  - Every stream now carries an absolute proxied_url fallback; Castle/Movix direct URLs
    unchanged (verified playable)
  - PersianStremio: MKV hosts confirmed Range-capable (206) - direct links kept
  - NetMirror: bcdnxw CDN 429-blocks ALL datacenter IPs (HF included) - primary stays the
    direct mp4 + Referer/UA headers (device-IP playback, like the Nuvio app); absolute
    proxied_url kept as fallback
"""

from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, Response, JSONResponse
from pydantic import BaseModel
from typing import Optional
import httpx
import json
import re
import base64
import time
import asyncio
import contextvars
import hashlib
import html as ihtml
from urllib.parse import quote, urljoin, urlparse, unquote
import random

app = FastAPI(
    title="StreamForge API",
    description="Multi-language m3u8/mp4/MKV stream scraper",
    version="14.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],
        }


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 "persian" in lower or "farsi" in lower: return "Persian"
    if "multi" in lower or "dual" in lower: return "Multi"
    return "English"


def evp_bytes_to_key(password: bytes, salt: bytes, key_len: int = 32, iv_len: int = 16):
    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:
    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:
    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 ""

_SF_CTRL_ENC = re.compile(r'%(0[0-9a-f]|1[0-9a-f]|7f)', re.IGNORECASE)


def _sf_url_has_ctrl(u: str) -> bool:
    """Detect literal or percent-encoded control characters in a URL."""
    if not u:
        return True
    if re.search(r'[\x00-\x1f\x7f]', u):
        return True
    return bool(_SF_CTRL_ENC.search(u))


def _sf_stream_result(source: str, title: str, url: str, quality: str = "Auto",
                      language: str = "English", headers: dict = None,
                      subtitles: list = None, direct_url: str = None,
                      proxied_url: str = None) -> dict:
    # strip control characters some APIs embed in URLs
    url = re.sub(r'[\x00-\x1f\x7f]', '', url or "")
    r = {
        "source": source,
        "title": title,
        "quality": quality,
        "language": detect_language(language) if language else "English",
        "url": url,
        "type": "m3u8" if ".m3u8" in url else "direct",
    }
    if headers:
        r["headers"] = headers
    if subtitles:
        r["subtitles"] = subtitles
    if direct_url:
        r["direct_url"] = direct_url
    if proxied_url:
        r["proxied_url"] = proxied_url
    return r


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


# ===== Proxy engine v2 =====
# Streams that need special headers (Referer/Origin/UA), are IP-bound, or lack CORS
# cannot be played directly by clients. They flow through /proxy_range, which does:
#   * header injection (ref / origin / ua)
#   * Range passthrough (seek) + HEAD
#   * content-sniffed m3u8 detection; every key/variant/segment URI inside a playlist
#     is rewritten to an ABSOLUTE /proxy_range URL so any player (hls.js, ExoPlayer,
#     VLC, native <video>) works without knowing the API base

_DEFAULT_BASE = "https://epiccodergg-streamforge-api.hf.space"
_BASE_URL: contextvars.ContextVar = contextvars.ContextVar("sf_base_url", default=_DEFAULT_BASE)


def _get_base() -> str:
    try:
        return _BASE_URL.get() or _DEFAULT_BASE
    except Exception:
        return _DEFAULT_BASE


@app.middleware("http")
async def _sf_base_url_middleware(request: Request, call_next):
    try:
        host = request.headers.get("host") or ""
        scheme = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").lower()
        if ".hf.space" in host:
            scheme = "https"  # never emit http:// proxy URLs for the Space (mixed content)
        base = f"{scheme}://{host}" if host else _DEFAULT_BASE
        _BASE_URL.set(base.rstrip("/") or _DEFAULT_BASE)
    except Exception:
        _BASE_URL.set(_DEFAULT_BASE)
    return await call_next(request)


def _proxy_wrap(url: str, ref: str = None, ua: str = None, origin: str = None) -> str:
    """Build an ABSOLUTE /proxy_range URL (players can use it as-is)."""
    params = [f"u={quote(url, safe='')}"]
    if ref:
        params.append(f"ref={quote(ref, safe='')}")
    if ua:
        params.append(f"ua={quote(ua, safe='')}")
    if origin:
        params.append(f"origin={quote(origin, safe='')}")
    return f"{_get_base()}/proxy_range?{'&'.join(params)}"


def _m3u8_rewrite(content: str, base_url: str, ref: str = None, ua: str = None, origin: str = None) -> str:
    """Rewrite every URI inside an m3u8 playlist to an absolute /proxy_range URL."""
    def _wrap(u: str) -> str:
        absu = urljoin(base_url, u)
        return _proxy_wrap(absu, ref, ua, origin)

    out_lines = []
    for line in content.splitlines():
        ls = line.strip()
        if not ls:
            continue
        if ls.startswith("#EXT-X-KEY") or ls.startswith("#EXT-X-MAP"):
            def key_uri(mm):
                return f'URI="{_wrap(mm.group(1))}"'
            ls = re.sub(r'URI="([^"]+)"', key_uri, ls)
            out_lines.append(ls)
        elif ls.startswith("#"):
            out_lines.append(ls)
        else:
            out_lines.append(_wrap(ls.strip('"')))
    return "\n".join(out_lines) + "\n"


def _proxy_headers(ref: str = None, ua: str = None, origin: str = None) -> dict:
    h = {"User-Agent": ua or HEADERS["User-Agent"], "Accept": "*/*"}
    if ref:
        h["Referer"] = ref
    if origin:
        h["Origin"] = origin
    return h


async def _proxy_do(u: str, ref: str, ua: str, origin: str, range_header: str = None, head_only: bool = False):
    headers = _proxy_headers(ref, ua, origin)
    if range_header:
        headers["Range"] = range_header

    try:
        client = httpx.AsyncClient(timeout=httpx.Timeout(90, connect=15), follow_redirects=True)
        req = client.build_request("GET", u, headers=headers)
        resp = await client.send(req, stream=True)
    except Exception as e:
        return JSONResponse({"error": f"proxy fetch failed: {str(e)}"},
                            status_code=502, headers={"Access-Control-Allow-Origin": "*"})

    ctype = (resp.headers.get("content-type") or "application/octet-stream").lower()
    final_url = str(resp.url)

    # NOTE: never partially-buffer the body and try to resume - an abandoned httpx
    # async iterator closes the underlying stream. Playlist detection relies on the
    # final (post-redirect) URL and the upstream content-type, which covers every
    # provider we serve (all m3u8s either carry .m3u8 in the URL or an mpegurl ctype).
    is_playlist = ".m3u8" in final_url or "mpegurl" in ctype

    if head_only:
        out = {
            "Access-Control-Allow-Origin": "*",
            "Accept-Ranges": "bytes",
            "Content-Type": ctype if (ctype and "text/html" not in ctype) else "application/octet-stream",
        }
        if resp.headers.get("content-length"):
            out["Content-Length"] = resp.headers["content-length"]
        status = resp.status_code
        await resp.aclose()
        await client.aclose()
        return Response(status_code=status, headers=out)

    if is_playlist:
        try:
            body = (await resp.aread()).decode("utf-8", errors="ignore")
        finally:
            await resp.aclose()
            await client.aclose()
        rewritten = _m3u8_rewrite(body, final_url, ref, ua, origin)
        return Response(
            content=rewritten,
            media_type="application/vnd.apple.mpegurl",
            headers={"Cache-Control": "no-cache", "Access-Control-Allow-Origin": "*"},
        )

    # binary stream (mp4/mkv/ts/segment): pipe with Range support
    # pass upstream errors through faithfully so players can fall back
    if resp.status_code not in (200, 206):
        err_body = b""
        try:
            err_body = (await resp.aread())[:400]
        finally:
            await resp.aclose()
            await client.aclose()
        return Response(content=err_body, status_code=resp.status_code,
                        media_type="text/plain", headers={"Access-Control-Allow-Origin": "*"})

    status = resp.status_code
    out_headers = {
        "Access-Control-Allow-Origin": "*",
        "Accept-Ranges": resp.headers.get("accept-ranges", "bytes"),
    }
    if resp.headers.get("content-range"):
        out_headers["Content-Range"] = resp.headers["content-range"]
    if resp.headers.get("content-length"):
        out_headers["Content-Length"] = resp.headers["content-length"]

    media_type = ctype if (ctype and "text/html" not in ctype) else "application/octet-stream"

    async def iter_bytes():
        try:
            async for chunk in resp.aiter_bytes(64 * 1024):
                yield chunk
        finally:
            await resp.aclose()
            await client.aclose()

    return StreamingResponse(iter_bytes(), status_code=status, media_type=media_type, headers=out_headers)


@app.api_route("/proxy", methods=["GET", "HEAD"], include_in_schema=False)
async def proxy_stream(u: str, ref: str = None, ua: str = None, origin: str = None, request: Request = None):
    """Stream proxy (Range-capable, header-injecting, m3u8-rewriting)."""
    range_header = request.headers.get("range") if request is not None else None
    return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request is not None and request.method == "HEAD"))


@app.api_route("/proxy_range", methods=["GET", "HEAD"], include_in_schema=False)
async def proxy_range(request: Request, u: str, ref: str = None, ua: str = None, origin: str = None):
    """Proxy that honors the client's Range header (for players that seek)."""
    range_header = request.headers.get("range")
    return await _proxy_do(u, ref, ua, origin, range_header, head_only=(request.method == "HEAD"))


# ---------- 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 or "googleusercontent.com" 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"
    if "360" in low: return "360p"
    return "Auto"


def _sf_lang_from_name(name: str) -> str:
    low = (name or "").lower()
    if "dual audio" in low or "dual" 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)
    if s_ok or season_only or (e_ok and (season_only or "season" in low)):
        return True
    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
    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


# ===== Castle Scraper v2 (hlowb.com API with AES-CBC) - multi-language m3u8 =====
# Ported from All-in-One-Nuvio providers/castle.js (verified playable 2025-09).
# Fixes vs the old v12 scraper:
#   - getVideo2 is now film-api/v2.0.1 (POST JSON body, movieId+episodeId+languageId)
#   - seasons[] entries carry the season id in the "movieId" field (NOT "id") -
#     the old scraper read the wrong field and served TV requests from the WRONG
#     SEASON (e.g. S5E1 when S1E1 was requested)
#   - movieType match: 2 = Movies, 1 = TV shows (old code had the values inverted
#     and only survived via its fallback loops)
#   - language tracks come from episodes[0].tracks[]: every track with
#     existIndividualVideo=true gets its own getVideo2 call (Tamil/OST/...),
#     the default (English) track is queried with its languageId, and TV falls
#     back to the shared stream (no languageId) exactly like the Nuvio app
#   - NOTE: the img*.com Castle CDNs disguise MPEG-TS segments as image/jpeg
#     (".jpg" URLs) - that is intentional upstream obfuscation, the bytes are
#     real TS (magic 47 40 11) and every HLS player handles them fine

CASTLE_BASE = "https://api.hlowb.com"
CASTLE_PKG = "com.external.castle"
CASTLE_CH = "IndiaA"
CASTLE_CLI = "1"
CASTLE_LANG = "en-US"
CASTLE_SIGN = "ED0955EB04E67A1D9F3305B95454FED485261475"
CASTLE_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"

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


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

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=CASTLE_HEADERS) as client:
            # 1) security key -> AES key/iv (base64 payload, key = sec + "T!BgJB" zero-padded to 16)
            sec_r = await client.get(f"{CASTLE_BASE}/v0.1/system/getSecurityKey/1", params={
                "channel": CASTLE_CH, "clientType": CASTLE_CLI, "lang": CASTLE_LANG
            })
            if sec_r.status_code != 200:
                errors.append(f"Castle: sec key HTTP {sec_r.status_code}")
                return results, errors
            try:
                sec_key = base64.b64decode(sec_r.json().get("data", "")).decode("utf-8", errors="ignore")
            except Exception:
                sec_key = sec_r.json().get("data", "")
            if not sec_key:
                errors.append("Castle: bad sec key response")
                return results, errors

            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: str):
                d = text
                try:
                    j = json.loads(text)
                    if isinstance(j, dict) and isinstance(j.get("data"), str):
                        d = j["data"]
                except Exception:
                    pass
                raw = None
                try:
                    raw = base64.b64decode(d + "=" * (-len(d) % 4))
                except Exception:
                    pass
                if raw is None or len(raw) % 16 != 0:
                    raw = None
                    try:
                        raw = bytes.fromhex(d)
                    except Exception:
                        pass
                if raw is None or len(raw) % 16 != 0 or not raw:
                    # maybe it is plain JSON already
                    return json.loads(text)
                dec = unpad(AES.new(aes_k, AES.MODE_CBC, aes_iv).decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")
                return json.loads(dec)

            # 2) search by "title year"
            kw = f"{title} {info.get('year', '')}".strip()
            sr = await client.get(f"{CASTLE_BASE}/film-api/v1.1.0/movie/searchByKeyword", params={
                "channel": CASTLE_CH, "clientType": CASTLE_CLI, "keyword": kw, "lang": CASTLE_LANG,
                "mode": "1", "packageName": CASTLE_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

            # movieType: 2 = Movies, 1 = TV shows
            want_type = 2 if media_type == "movie" else 1
            tl = _sf_norm(title)

            def _norm_row(r):
                return _sf_norm(r.get("title", "") or r.get("name", ""))

            mid = None
            for r in rows:
                if not isinstance(r, dict):
                    continue
                if _norm_row(r) == tl and r.get("movieType", r.get("subjectType", 0)) == want_type:
                    mid = r.get("id")
                    break
            if mid is None:
                for r in rows:
                    if not isinstance(r, dict):
                        continue
                    rt = _norm_row(r)
                    if (tl in rt or rt in tl) and r.get("movieType", r.get("subjectType", 0)) == want_type:
                        mid = r.get("id")
                        break
            if mid is None:
                for r in rows:
                    if not isinstance(r, dict):
                        continue
                    rt = _norm_row(r)
                    if tl in rt or rt in tl:
                        mid = r.get("id")
                        break
            if mid is None and isinstance(rows[0], dict):
                mid = rows[0].get("id")
            if mid is None:
                errors.append("Castle: no match")
                return results, errors

            # 3) details (v1.9.9) -> episodes + seasons + language tracks
            async def fetch_details(movie_id):
                dr = await client.get(f"{CASTLE_BASE}/film-api/v1.9.9/movie", params={
                    "channel": CASTLE_CH, "clientType": CASTLE_CLI, "lang": CASTLE_LANG,
                    "movieId": str(movie_id), "packageName": CASTLE_PKG
                })
                if dr.status_code != 200:
                    return {}
                try:
                    dp = castle_decrypt(dr.text)
                except Exception:
                    return {}
                dd = dp.get("data", dp)
                if isinstance(dd, str):
                    try:
                        dd = json.loads(dd)
                    except Exception:
                        dd = {}
                return dd if isinstance(dd, dict) else {}

            dd = await fetch_details(mid)
            if not dd:
                errors.append("Castle: detail fetch failed")
                return results, errors

            video_movie_id = str(mid)
            ep_id = None
            ep_info = None

            if media_type == "tv" and season and episode:
                # find the season's own movieId ("movieId" field, NOT "id")
                s_mid = None
                for s_item in (dd.get("seasons") or []):
                    if not isinstance(s_item, dict):
                        continue
                    if s_item.get("number") == season or s_item.get("seasonNum") == season:
                        s_mid = s_item.get("movieId") or s_item.get("id")
                        break
                if s_mid and str(s_mid) != str(mid):
                    video_movie_id = str(s_mid)
                    sdd = await fetch_details(s_mid)
                    if sdd.get("episodes"):
                        dd = sdd
                for ep in (dd.get("episodes") or []):
                    if isinstance(ep, dict) and (ep.get("number") == episode or ep.get("episodeNum") == episode):
                        ep_id = str(ep.get("id", ""))
                        ep_info = ep
                        break
                if not ep_id and (dd.get("episodes") or []):
                    # fallback: positional
                    eps = [e for e in dd.get("episodes") if isinstance(e, dict)]
                    if 0 < episode <= len(eps):
                        ep_id = str(eps[episode - 1].get("id", ""))
                        ep_info = eps[episode - 1]
                if not ep_id:
                    errors.append(f"Castle: episode S{season}E{episode} not found")
                    return results, errors
            else:
                eps = [e for e in (dd.get("episodes") or []) if isinstance(e, dict)]
                if eps:
                    ep_id = str(eps[0].get("id", ""))
                    ep_info = eps[0]
                else:
                    ep_id = str(mid)

            # 4) language tracks from the episode payload
            tracks = []
            if isinstance(ep_info, dict):
                tracks = [t for t in (ep_info.get("tracks") or []) if isinstance(t, dict)]

            lang_calls = []
            default_track = next((t for t in tracks if t.get("isDefault")), None)
            if default_track and default_track.get("languageId"):
                lang_calls.append((default_track.get("languageName") or "Default", str(default_track["languageId"])))
            for t in tracks:
                if t.get("existIndividualVideo") and t.get("languageId"):
                    lid = str(t["languageId"])
                    if lid not in [x[1] for x in lang_calls]:
                        lang_calls.append((t.get("languageName") or "Track", lid))

            if not lang_calls:
                lang_calls = [("English", "1003")]

            # TV additionally gets the shared stream (no languageId) - that is
            # what the Nuvio app falls back to when per-language video is absent
            include_shared = media_type == "tv"

            async def get_video2(movie_id: str, episode_id: str, language_id: str = None):
                body = {
                    "mode": "1",
                    "appMarket": "GuanWang",
                    "clientType": CASTLE_CLI,
                    "woolUser": "false",
                    "apkSignKey": CASTLE_SIGN,
                    "androidVersion": "13",
                    "movieId": str(movie_id),
                    "episodeId": str(episode_id),
                    "isNewUser": "true",
                    "resolution": "2",
                    "packageName": CASTLE_PKG,
                }
                if language_id:
                    body["languageId"] = str(language_id)
                vr = await client.post(
                    f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
                    params={"clientType": CASTLE_CLI, "packageName": CASTLE_PKG, "channel": CASTLE_CH, "lang": CASTLE_LANG},
                    json=body,
                    headers={"Content-Type": "application/json"},
                )
                if vr.status_code != 200:
                    return None
                try:
                    vp = castle_decrypt(vr.text)
                except Exception:
                    return None
                vd = vp.get("data", vp)
                if isinstance(vd, str):
                    try:
                        vd = json.loads(vd)
                    except Exception:
                        return None
                return vd if isinstance(vd, dict) else None

            def quality_from(vd: dict, vurl: str) -> str:
                # the real ladder is in the URL path (/720/...) - label from that
                m = re.search(r'/(\d{3,4})/', vurl)
                if m:
                    return f"{m.group(1)}P"
                best = "720P"
                for v in (vd.get("videos") or []):
                    if isinstance(v, dict) and not v.get("premiumProPermission"):
                        q = str(v.get("resolutionDescription", "")).strip()
                        q = re.sub(r'^(SD|HD|FHD|UHD)\s+', '', q).upper()
                        if q:
                            best = q
                return best

            emitted_urls = set()

            async def emit(vd: dict, label: str):
                if not vd:
                    return
                vurl = vd.get("videoUrl", "")
                if not vurl or _sf_url_has_ctrl(vurl) or vurl in emitted_urls:
                    return
                emitted_urls.add(vurl)
                quality = quality_from(vd, vurl)
                subs_out = []
                for sub in (vd.get("subtitles") or []):
                    if isinstance(sub, dict) and sub.get("url"):
                        subs_out.append({"language": sub.get("title") or sub.get("abbreviate") or "Sub",
                                         "url": sub["url"]})
                hdrs = {"User-Agent": CASTLE_UA}
                proxied = _proxy_wrap(vurl, ua=CASTLE_UA)
                results.append(_sf_stream_result(
                    "Castle", f"Castle [{label}] - {quality}", vurl,
                    quality=quality, language=label if label != "Default" else "English",
                    headers=hdrs,
                    subtitles=subs_out or None,
                    direct_url=proxied, proxied_url=proxied))

            for label, lid in lang_calls:
                try:
                    vd = await get_video2(video_movie_id, ep_id, lid)
                    if vd and vd.get("videoUrl"):
                        await emit(vd, label)
                except Exception:
                    continue

            if include_shared:
                try:
                    vd = await get_video2(video_movie_id, ep_id, None)
                    if vd and vd.get("videoUrl"):
                        await emit(vd, "Shared")
                except Exception:
                    pass

        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 v3 (net27.cc embed-tmdb) - mp4 with SOLVED CDN gating =====
# Ported from All-in-One-Nuvio providers/netmirror.js (verified playable 2025-09).
#
# THE 429 MYSTERY, SOLVED: bcdnxw.hakunaymatata.com (the NetMirror CDN) does NOT
# block datacenter IPs. It gates on the REFERER: requests must carry
# "https://videodownloader.site/" (the referer the Nuvio web player uses).
# The v12 scraper sent "https://net27.cc/" and got 429 from every IP - that is
# why MOON appeared dead. With the correct referer:
#   * direct client playback (device IP + Referer/UA headers) -> 206 video/mp4
#   * playback through the Space proxy (which injects those headers) -> 206 too
# Both paths verified from a datacenter IP, all qualities (360/480/720/1080).
#
# Subtitles: movie captions go through net27.cc /api/proxy/video (302 to a
# streamhub worker, serves real SRT - proxied through us). TV captions point
# at an R2 cache (net27-r2-cache...workers.dev) that 403s datacenter IPs, so
# they are returned as direct URLs for the client's own IP to fetch.
#
# Nuvio's "NewTV" platform fallback (mobiledetects.com -> tv.imgcdn.kim) is
# dead upstream ("Page Not Found" even with the app's exact headers) - not ported.

_NETMIRROR_BASE = "https://net27.cc"
_NETMIRROR_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
# the referer the CDN actually requires - NOT net27.cc
_NETMIRROR_CDN_REF = "https://videodownloader.site/"
_NETMIRROR_HEADERS = {
    "Accept": "application/json, text/plain, */*",
    "Referer": "https://net27.cc/",
    "User-Agent": _NETMIRROR_UA,
}


async def scrape_netmirror(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    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

        if data.get("ok") is False or data.get("noSource"):
            errors.append("NetMirror: title not available on NetMirror")
            return results, errors

        # Subtitle tracks
        subs_out = []
        for sub in (data.get("captions") or data.get("subtitles") or []):
            try:
                surl = sub.get("url") if isinstance(sub, dict) else None
                if not surl:
                    continue
                if surl.startswith("/"):
                    surl = _NETMIRROR_BASE + surl
                    # net27.cc's own proxy (movie captions) - verified SRT via our proxy
                    surl = _proxy_wrap(surl, ref="https://net27.cc/", ua=_NETMIRROR_UA)
                # TV captions (absolute workers.dev URLs) stay direct: the R2 cache
                # 403s datacenter IPs, so let the client's own IP try them
                lang = sub.get("lang") or sub.get("language") or "Sub"
                name = sub.get("name") or lang
                subs_out.append({"language": name, "url": surl})
            except Exception:
                continue

        # Streams: "streams" ladder (360/480/720) + "mp4" (top quality)
        entries = []
        for s in (data.get("streams") or []):
            if isinstance(s, dict) and s.get("url"):
                entries.append((s.get("url"), s.get("resolution")))
        if data.get("mp4"):
            entries.append((data.get("mp4"), data.get("resolution", "1080")))

        if not entries:
            errors.append("NetMirror: no streams in response")
            return results, errors

        seen = set()
        for u, res in entries:
            u = str(u or "")
            if not u or u in seen:
                continue
            if u.startswith("/"):
                u = _NETMIRROR_BASE + u
            seen.add(u)
            res = str(res or "").strip()
            quality = {"2160": "4K", "1080": "1080p", "720": "720p", "480": "480p", "360": "360p"}.get(res, res if res else "Auto")
            # CDN requires the videodownloader.site referer - with it, both the
            # direct URL (players that can send headers) and the proxy URL
            # (any player, embedded anywhere) return 206 video/mp4
            proxied = _proxy_wrap(u, ref=_NETMIRROR_CDN_REF, ua=_NETMIRROR_UA)
            results.append(_sf_stream_result(
                "NetMirror", f"NetMirror - {quality}", u,
                quality=quality, language="Multi",
                headers={"Referer": _NETMIRROR_CDN_REF, "User-Agent": _NETMIRROR_UA},
                subtitles=subs_out or None,
                direct_url=proxied, proxied_url=proxied))
    except Exception as ex:
        errors.append(f"NetMirror: {str(ex)}")
    return results, errors
# ===== PlayBox Scraper (streamdata.vaplayer.ru API) =====

_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
            # the m3u8 gateway (onlinevisibilitysystem.site) intermittently gates direct
            # client fetches with a JSON error page (Referer/Origin/rate gating) ->
            # serve through our proxy with exactly the headers the API call used
            pu = _proxy_wrap(u, ref="https://nextgencloudfabric.com/",
                             ua=HEADERS["User-Agent"], origin="https://nextgencloudfabric.com")
            results.append(_sf_stream_result(
                "PlayBox", "PlayBox - m3u8", pu,
                quality="Auto", language="Multi", direct_url=u))
    except Exception as ex:
        errors.append(f"PlayBox: {str(ex)}")
    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


# ===== Movies4u (Nuvio movies4u.js port) =====
# Flow: domains.json -> site search -> post page -> m4uplay packed player (Dean Edwards
# unpack) -> hls2 m3u8 + m4ulinks -> hubcloud -> googleusercontent direct

_PHISHER_DOMAINS = "https://raw.githubusercontent.com/phisher98/TVVVV/refs/heads/main/domains.json"
_M4U_DEFAULT_SITE = "https://new5.movies4u.clinic"

_M4U_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"


def _sf_dean_unpack(html_text: str) -> str:
    """Unpack eval(function(p,a,c,k,e,d){...}('payload',radix,count,'words'.split('|')))"""
    try:
        anchor = re.search(r"eval\(function\(p,a,c,k,e,d\)\{.*?\}\('", html_text, re.DOTALL)
        if not anchor:
            return html_text
        rest = html_text[anchor.end():]
        endm = re.search(r"',(\d+),(\d+),'", rest)
        if not endm:
            return html_text
        payload = rest[:endm.start()]
        radix, count = int(endm.group(1)), int(endm.group(2))
        rest2 = rest[endm.end():]
        wend = rest2.find("'.split(")
        if wend == -1:
            return html_text
        words = rest2[:wend].split('|')

        ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        def enc(i):
            out = ""
            while True:
                out = ALPHABET[i % radix] + out
                i //= radix
                if i == 0:
                    break
            return out

        unpacked = payload
        for c in range(count - 1, -1, -1):
            if c < len(words) and words[c]:
                unpacked = re.sub(r'\b' + re.escape(enc(c)) + r'\b',
                                  words[c].replace('\\', '\\\\'), unpacked)
        return ihtml.unescape(unpacked)
    except Exception:
        return html_text


def _sf_m4uplay_extract(page_html: str, page_url: str) -> list:
    """Extract m3u8 links from an m4uplay player page."""
    out = []
    unpacked = _sf_dean_unpack(page_html)
    # links object: {"hls4": "...", "hls3": "...", "hls2": "https://...master.m3u8?t=..."}
    for m in re.finditer(r'"(hls\d)"\s*:\s*"([^"]+)"', unpacked):
        u = m.group(2)
        if u.startswith("/"):
            u = urljoin(page_url, u)
        if ".m3u8" in u:
            out.append(u)
    # Fallback: any literal m3u8
    if not out:
        for m in re.finditer(r'https?://[^"\'\s]+\.m3u8[^"\'\s]*', unpacked):
            out.append(m.group(0))
    # Deduplicate, keep order (hls4 preferred first like the player)
    seen = set()
    uniq = []
    for u in out:
        if u not in seen:
            seen.add(u)
            uniq.append(u)
    return uniq


async def scrape_movies4u(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 ""
        year = info.get("year") or ""

        site = _M4U_DEFAULT_SITE
        try:
            async with httpx.AsyncClient(timeout=10) as c:
                cfg = (await c.get(_PHISHER_DOMAINS)).json()
            cand = cfg.get("movies4u")
            if isinstance(cand, str) and cand.startswith("http"):
                site = cand.rstrip("/")
            elif isinstance(cand, list) and cand:
                site = str(cand[0]).rstrip("/")
        except Exception:
            pass

        results_all = []
        async with httpx.AsyncClient(timeout=25, follow_redirects=True,
                                     headers={"User-Agent": _M4U_UA, "Referer": site + "/"}) as client:
            # 1) search
            sr = await client.get(f"{site}/?s={quote(title)}")
            if sr.status_code != 200:
                errors.append(f"Movies4u: search HTTP {sr.status_code}")
                return results, errors

            posts = []
            for m in re.finditer(r'<article[^>]+id="post-(\d+)"[^>]*>.*?<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', sr.text, re.DOTALL):
                pid, url, ttl = m.group(1), m.group(2), re.sub(r'<[^>]+>', '', m.group(3))
                posts.append({"id": pid, "url": url, "title": ttl.strip()})
            if not posts:
                # simpler pattern
                for m in re.finditer(r'<h2[^>]*class="[^"]*entry-title[^"]*"[^>]*>\s*<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', sr.text, re.DOTALL):
                    url, ttl = m.group(1), re.sub(r'<[^>]+>', '', m.group(2)).strip()
                    posts.append({"id": None, "url": url, "title": ttl})
            if not posts:
                errors.append("Movies4u: no search results")
                return results, errors

            # 2) pick matching post
            tl_norm = _sf_norm(f"{title} {year}")
            chosen = None
            for p in posts:
                pt = _sf_norm(p["title"])
                if _sf_norm(title) in pt and (not year or year in pt or year in p["url"]):
                    chosen = p
                    break
            if not chosen:
                for p in posts:
                    if _sf_norm(title) in _sf_norm(p["title"]) or _sf_norm(title) in _sf_norm(p["url"]):
                        chosen = p
                        break
            if not chosen:
                chosen = posts[0]

            # episode filter for TV: prefer post with S..E marker
            if media_type == "tv" and season and episode:
                marker = f"s{season:02d}e{episode:02d}"
                marker2 = f"s{season}e{episode}"
                for p in posts:
                    pu = (p["title"] + " " + p["url"]).lower().replace(" ", "")
                    if marker in pu or marker2 in pu:
                        chosen = p
                        break

            pr = await client.get(chosen["url"])
            if pr.status_code != 200:
                errors.append(f"Movies4u: post HTTP {pr.status_code}")
                return results, errors
            post_html = pr.text

            # 3) find m4uplay file link
            m4u_links = re.findall(r'https?://m4uplay\.[a-z.]+/file/[A-Za-z0-9]+', post_html)
            if not m4u_links:
                m4u_links = re.findall(r'https?://[a-z0-9.]*m4uplay[^"\'\s<]*file[^"\'\s<]*', post_html)
            # also quality-labeled anchors
            if not m4u_links:
                m4u_links = re.findall(r'https?://[^"\'\s<]*player[^"\'\s<]*/file/[^"\'\s<]+', post_html)
            m4u_links = list(dict.fromkeys(m4u_links))[:3]

            if not m4u_links:
                errors.append("Movies4u: no m4uplay links")
            else:
                for link in m4u_links:
                    try:
                        lr = await client.get(link, headers={"User-Agent": _M4U_UA, "Referer": site + "/"})
                        if lr.status_code != 200:
                            continue
                        for u in _sf_m4uplay_extract(lr.text, str(lr.url)):
                            results_all.append({"url": u, "label": "M4U Player Direct"})
                    except Exception:
                        continue

            # 4) hubcloud direct fallbacks from post page
            hc_links = re.findall(r'https?://m4ulinks\.[a-z]+/\S+', post_html)[:2]
            resolved = []
            for hl in hc_links:
                try:
                    lp = (await client.get(hl, headers={"User-Agent": _SF_MOBILE_UA, "Referer": site + "/"})).text
                    for hcl in re.findall(r'https?://hubcloud\.[a-z]+/(?:video|drive)/[A-Za-z0-9_]+', lp)[:2]:
                        resolved.extend(await _sf_resolve_hubcloud(client, hcl))
                except Exception:
                    continue
            if resolved:
                results_all.extend(resolved)

        # m4uplay / acek-cdn m3u8 tokens are extremely short-lived and the operator
        # burst-rate-limits by IP (2nd rapid playlist fetch from one IP -> PNG block
        # page). So: NO pre-validation (it burns the token), return exactly ONE fresh
        # m4uplay-hosted token per scrape (m4uplay preferred, longest-lived).
        seen = set()
        cand = []
        for r in results_all:
            u = r["url"]
            if u in seen:
                continue
            seen.add(u)
            cand.append(r)
        m3u8_cands = [c for c in cand if ".m3u8" in c["url"]]
        m3u8_cands.sort(key=lambda c: (0 if "m4uplay" in c["url"] else 1))
        m3u8_cands = m3u8_cands[:1]
        ok_m3u8 = {c["url"] for c in m3u8_cands}

        for r in cand:
            u = r["url"]
            label = r.get("label") or "Direct"
            if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):
                continue
            if ".m3u8" in u:
                if u not in ok_m3u8:
                    continue
                # m4uplay tokens are IP-bound -> serve through our proxy so the
                # playlist AND every segment flow from the API (same IP as the token)
                pu = _proxy_wrap(u, ref="https://m4uplay.store/", ua=_M4U_UA)
                results.append(_sf_stream_result(
                    "Movies4u", f"Movies4u - {label}", pu,
                    quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))
            elif any(u.endswith(ext) or f"{ext}?" in u for ext in (".mkv", ".mp4")) or "googleusercontent" in u:
                results.append(_sf_stream_result(
                    "Movies4u", f"Movies4u - {label}", u,
                    quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))

        if not results:
            errors.append("Movies4u: no playable streams")
    except Exception as ex:
        errors.append(f"Movies4u: {str(ex)}")
    return results, errors


# ===== PersianStremio (stremio addon API, imdb based) =====

_PERSIAN_API = "https://persianstremio.vercel.app"


async def scrape_persianstremio(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("PersianStremio: no imdb id")
            return results, errors

        if media_type == "tv":
            url = f"{_PERSIAN_API}/stream/series/{imdb_id}:{season or 1}:{episode or 1}.json"
        else:
            url = f"{_PERSIAN_API}/stream/movie/{imdb_id}.json"

        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            data = None
            last_status = 0
            # the vercel API intermittently 503s datacenter IPs (HF included) ->
            # retry with real backoff before giving up (1.5s / 3s / 4.5s)
            for attempt in range(4):
                try:
                    resp = await client.get(url, headers={
                        "User-Agent": HEADERS["User-Agent"],
                        "Accept": "application/json, text/plain, */*",
                        "Accept-Language": "en-US,en;q=0.9",
                    })
                    last_status = resp.status_code
                    if resp.status_code == 200:
                        data = resp.json()
                        break
                except Exception:
                    last_status = 0
                if attempt < 3:
                    await asyncio.sleep(1.5 * (attempt + 1))
            if data is None:
                errors.append(f"PersianStremio: API HTTP {last_status}")
                return results, errors

        streams = data.get("streams") or []
        if not streams:
            errors.append("PersianStremio: no streams")
            return results, errors

        seen = set()
        for st in streams:
            if not isinstance(st, dict):
                continue
            u = st.get("url")
            if not u or u in seen:
                continue
            seen.add(u)
            name = re.sub(r'[^\x20-\x7e؀-ۿ]|[🌸]', '', (st.get("name") or ""))
            name = re.sub(r'\s+', ' ', name).strip()
            label = (st.get("title") or name or "Direct")[:90]
            quality = _sf_quality_from_name(label + " " + name)
            results.append(_sf_stream_result(
                "PersianStremio", f"PersianStremio - {label}", u,
                quality=quality, language="Multi"))
    except Exception as ex:
        errors.append(f"PersianStremio: {str(ex)}")
    return results, errors


# ===== UHDMovies (driveseed chain) =====
# uhdmovies site -> post -> cloud gate -> driveseed r?key -> zfile -> direct

_UHD_DEFAULT_SITE = "https://uhdmovies.autos"


async def _sf_resolve_driveseed(client: httpx.AsyncClient, drive_url: str) -> list:
    """Resolve driveseed.org r?key / file links to direct URLs."""
    out = []
    try:
        u = drive_url
        if "/r?key=" in u:
            rp = (await client.get(u, headers={"User-Agent": _SF_MOBILE_UA, "Referer": "https://driveseed.org/"})).text
            m = re.search(r'action="([^"]*/file/[^"]*)"', rp)
            if not m:
                m = re.search(r'href="(https?://driveseed\.org/file/[^"]+)"', rp)
            if m:
                u = ihtml.unescape(m.group(1))
        if "/file/" in u:
            fp = (await client.get(u, headers={"User-Agent": _SF_MOBILE_UA, "Referer": "https://driveseed.org/"})).text
            # zfile / app download links
            zf = re.search(r'href="(https?://[^"]*zfile[^"]*)"', fp)
            direct = re.search(r'href="(https?://[^"]+\.(?:mkv|mp4)[^"]*)"', fp)
            if direct:
                chunk = fp[direct.start():direct.start() + 500]
                fm = re.search(r'download="([^"]{5,110})"', chunk)
                out.append({"url": direct.group(1), "label": fm.group(1) if fm else "Direct"})
            elif zf:
                zp = (await client.get(ihtml.unescape(zf.group(1)), headers={"User-Agent": _SF_MOBILE_UA, "Referer": u})).text
                for b in re.finditer(r'<a[^>]+href="(https?://[^"]+)"[^>]*class="[^"]*btn[^"]*', zp):
                    bu = b.group(1)
                    chunk = zp[b.start():b.start() + 800]
                    fm = re.search(r'download="([^"]{5,110})"', chunk)
                    fname = fm.group(1) if fm else "Direct"
                    if "googleusercontent" in bu or ".mkv" in bu or ".mp4" in bu or "workers.dev" in bu or "video-gen" in bu:
                        out.append({"url": bu, "label": fname})
                        break
    except Exception:
        pass
    return out


async def scrape_uhdmovies(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 ""
        year = info.get("year") or ""

        site = _UHD_DEFAULT_SITE
        try:
            async with httpx.AsyncClient(timeout=10) as c:
                cfg = (await c.get(_PHISHER_DOMAINS)).json()
            cand = cfg.get("uhdmovies")
            if isinstance(cand, str) and cand.startswith("http"):
                site = cand.rstrip("/")
        except Exception:
            pass

        async with httpx.AsyncClient(timeout=30, follow_redirects=True,
                                     headers={"User-Agent": _SF_MOBILE_UA, "Referer": site + "/"}) as client:
            sr = await client.get(f"{site}/?s={quote(title)}")
            if sr.status_code != 200:
                errors.append(f"UHDMovies: search HTTP {sr.status_code}")
                return results, errors

            posts = []
            for m in re.finditer(r'href="(https?://[^"]*uhdmovies[^"]*/download-[^"\s<>]+)"[^>]*>([^<]{4,150})', sr.text):
                url, ttl = m.group(1), m.group(2).strip()
                posts.append({"url": url, "title": ttl})
            if not posts:
                # bare download- links (title from slug)
                for m in re.finditer(r'https?://[a-z0-9.]*uhdmovies[a-z0-9.]*/download-([a-z0-9\-]+)/?', sr.text):
                    slug = m.group(1)
                    posts.append({"url": f"{site}/download-{slug}/", "title": slug.replace('-', ' ')})
            if not posts:
                errors.append("UHDMovies: no search results")
                return results, errors

            tl_norm = _sf_norm(title)
            chosen = None
            for p in posts:
                pt = _sf_norm(p["title"])
                if tl_norm in pt and (not year or year in p["title"] or year in p["url"]):
                    chosen = p
                    break
            if not chosen:
                for p in posts:
                    if tl_norm in _sf_norm(p["url"]):
                        chosen = p
                        break
            if not chosen and media_type == "movie":
                # movies often have "Season 1" style posts; prefer plain movie posts
                for p in posts:
                    if "season" not in p["title"].lower():
                        chosen = p
                        break
            if not chosen:
                chosen = posts[0]

            pr = await client.get(chosen["url"])
            if pr.status_code != 200:
                errors.append(f"UHDMovies: post HTTP {pr.status_code}")
                return results, errors
            post_html = pr.text

            # drive links (driveseed / workers gate)
            resolved = []
            drive_links = re.findall(r'https?://[^\s"\'<>]*(?:driveseed\.org/[^\s"\'<>]+|cloud\.unblockedgames\.world/[^\s"\'<>]+)', post_html)
            seen_links = list(dict.fromkeys(drive_links))[:4]
            for dl in seen_links:
                resolved.extend(await _sf_resolve_driveseed(client, dl))

            # episode filter for TV
            seen = set()
            for r in resolved:
                u, label = r["url"], r["label"]
                if u in seen:
                    continue
                seen.add(u)
                if media_type == "tv" and not _sf_episode_matches(label, season or 1, episode or 1):
                    continue
                results.append(_sf_stream_result(
                    "UHDMovies", f"UHDMovies - {label or 'Direct'}", u,
                    quality=_sf_quality_from_name(label), language=_sf_lang_from_name(label)))

            if not results:
                errors.append("UHDMovies: no resolvable streams")
    except Exception as ex:
        errors.append(f"UHDMovies: {str(ex)}")
    return results, errors


# ---------- VegaMovies (search.php?q=imdb -> wp-json -> nexdrive -> vcloud/hubcloud) ----------

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:
    out = []
    try:
        page = (await client.get(vcloud_url, headers={
            "User-Agent": _SF_MOBILE_UA, "Referer": referer, "Cookie": "xla=s4t"})).text
        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
        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 or "googleusercontent" 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

        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:
            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

            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

            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

            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:
                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
                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))
                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


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


# =====================================================================
# Vyla SDK ports (github.com/vyla-entertainment/sdk) — v14 additions.
# Tested one-by-one from a datacenter IP with playlist+segment verification.
# =====================================================================

_ENC_DEC = "https://enc-dec.app/api"


def _b64url_bytes(v: str) -> bytes:
    pad = "=" * (-len(v) % 4)
    return base64.urlsafe_b64decode(v + pad)


# ===== VidRock (Vyla vidrock.js): vidrock.ru/api + AES-GCM =====

_VIDROCK_GCM_KEY = "7f3e9c2a8b5d1f4e6a9c3b7d2e5f8a1c4b6d9e2f5a8c1b4d7e9f2a5c8b1d4e7f"
_VIDROCK_PROXY_PREFIX = "https://proxy.vidrock.store/"


def _vidrock_decrypt(value: str):
    try:
        from Crypto.Cipher import AES
        data = _b64url_bytes(value)
        if len(data) < 28:
            return None
        iv, ct = data[:12], data[12:]
        key = bytes.fromhex(_VIDROCK_GCM_KEY)
        cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
        try:
            return cipher.decrypt_and_verify(ct[:-16], ct[-16:]).decode()
        except Exception:
            out = cipher.decrypt(ct).decode(errors="ignore")
            return out.split("\x00")[0].strip()
    except Exception:
        return None


async def scrape_vidrock(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    try:
        async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
            path = f"tv/{tmdb_id}/{season or 1}/{episode or 1}" if media_type == "tv" else f"movie/{tmdb_id}"
            resp = await client.get(f"https://vidrock.ru/api/{path}", headers={
                "User-Agent": HEADERS["User-Agent"], "Referer": "https://vidrock.ru/",
                "Origin": "https://vidrock.ru"})
            if resp.status_code != 200:
                errors.append(f"VidRock: API HTTP {resp.status_code}")
                return results, errors
            data = resp.json()

        for provider, info in (data or {}).items():
            try:
                enc_url = (info or {}).get("url") if isinstance(info, dict) else None
                if not enc_url:
                    continue
                url = _vidrock_decrypt(enc_url)
                if not url or not url.startswith("http"):
                    continue
                if url.startswith(_VIDROCK_PROXY_PREFIX):
                    url = unquote(url[len(_VIDROCK_PROXY_PREFIX):].lstrip("/"))
                is_xpass = "xpass.top" in url
                vheaders = {
                    "User-Agent": HEADERS["User-Agent"],
                    "Referer": "https://play.xpass.top/" if is_xpass else "https://vidrock.ru/",
                    "Origin": "https://play.xpass.top" if is_xpass else "https://vidrock.ru",
                }
                results.append(_sf_stream_result(
                    f"VidRock/{provider}", f"VidRock - {provider}", url,
                    quality=info.get("type") or "Auto", language="English", headers=vheaders))
            except Exception:
                continue

        if not results:
            errors.append("VidRock: no streams")
    except Exception as ex:
        errors.append(f"VidRock: {str(ex)}")
    return results, errors


# ===== VidFast + VidUp (Vyla vidfast.js / vidup.js): enc-dec.app protocol =====

async def _vidfamily_scrape(domain: str, enc_path: str, dec_path: str, label: str,
                            tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    try:
        async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
            if media_type == "tv":
                embed_url = f"{domain}/tv/{tmdb_id}/{season or 1}/{episode or 1}/"
            else:
                embed_url = f"{domain}/movie/{tmdb_id}/"
            resp = await client.get(embed_url, headers={"User-Agent": HEADERS["User-Agent"]})
            html = resp.text
            m = (re.search(r'\\"(?:en|token)\\":\\"(.*?)\\"', html)
                 or re.search(r'"(?:en|token)":"(.*?)"', html))
            if not m:
                errors.append(f"{label}: no token in embed")
                return results, errors

            resp = await client.get(f"{_ENC_DEC}/{enc_path}", params={"text": m.group(1)})
            enc = resp.json()
            if enc.get("status") != 200 or not enc.get("result"):
                errors.append(f"{label}: enc failed")
                return results, errors
            meta = enc["result"]
            req_headers = {
                "User-Agent": HEADERS["User-Agent"],
                "Referer": f"{domain}/",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": meta["token"],
            }

            resp = await client.post(meta["servers"], headers=req_headers)
            resp = await client.post(f"{_ENC_DEC}/{dec_path}", json={"text": resp.text})
            dec = resp.json()
            if dec.get("status") != 200 or not dec.get("result"):
                errors.append(f"{label}: servers decrypt failed")
                return results, errors
            servers = dec["result"]

            for srv in servers:
                try:
                    resp = await client.post(f"{meta['stream']}/{srv['data']}", headers=req_headers)
                    resp = await client.post(f"{_ENC_DEC}/{dec_path}", json={"text": resp.text})
                    sd = resp.json()
                    sres = (sd.get("result") or {}) if sd.get("status") == 200 else {}
                    surl = sres.get("url")
                    if not surl:
                        continue
                    subs = []
                    for cap in (sres.get("captions") or []):
                        if cap.get("file"):
                            subs.append({"language": cap.get("label") or "Sub", "url": cap["file"]})
                    vheaders = {
                        "User-Agent": HEADERS["User-Agent"],
                        "Referer": f"{domain}/",
                        "Origin": domain,
                    }
                    results.append(_sf_stream_result(
                        f"{label}/{srv.get('name') or 'Server'}", f"{label} - {srv.get('name') or 'Server'}",
                        surl, quality="Auto", language="English", headers=vheaders,
                        subtitles=subs or None))
                except Exception:
                    continue

        if not results:
            errors.append(f"{label}: no playable servers")
    except Exception as ex:
        errors.append(f"{label}: {str(ex)}")
    return results, errors


async def scrape_vidfast(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    return await _vidfamily_scrape("https://vidfast.vc", "enc-vidfast", "dec-vidfast",
                                   "VidFast", tmdb_id, media_type, season, episode)


async def scrape_vidup(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    return await _vidfamily_scrape("https://vidup.to", "enc-vidup", "dec-vidup",
                                   "VidUp", tmdb_id, media_type, season, episode)


# ===== MeowTV (Vyla meowtv.js): api.meowtv.ru + enc-dec.app (castle-CDN family) =====

async def scrape_meowtv(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    try:
        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            for srv in ["tik", "hindiv3"]:
                try:
                    if media_type == "tv":
                        path = f"/streams/tv/{tmdb_id}/{season or 1}/{episode or 1}?s={srv}"
                    else:
                        path = f"/streams/movie/{tmdb_id}?s={srv}"
                    resp = await client.get(f"https://api.meowtv.ru{path}", headers={
                        "User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
                        "Referer": "https://meowtv.ru/", "Origin": "https://meowtv.ru",
                        "Accept-Language": "en-US,en;q=0.9"})
                    payload = resp.json()
                    resp = await client.post(f"{_ENC_DEC}/dec-meowtv", json={"data": payload})
                    dec = resp.json()
                    if dec.get("status") != 200 or not dec.get("result"):
                        continue
                    res = dec["result"]
                    if isinstance(res, str):
                        res = json.loads(res)
                    vheaders = {
                        "User-Agent": HEADERS["User-Agent"],
                        "Referer": "https://meowtv.ru/",
                        "Origin": "https://meowtv.ru",
                    }
                    if str(res.get("url") or "").startswith("http"):
                        results.append(_sf_stream_result(
                            f"MeowTV/{srv}", f"MeowTV - {srv}", res["url"],
                            quality="Auto", language="Multi", headers=vheaders))
                    for st in (res.get("streams") or []):
                        if str(st.get("url") or "").startswith("http"):
                            results.append(_sf_stream_result(
                                f"MeowTV/{srv}", f"MeowTV - {srv} ({st.get('language') or 'Multi'})",
                                st["url"], quality="Auto",
                                language=st.get("language") or "Multi", headers=vheaders))
                except Exception:
                    continue

        if not results:
            errors.append("MeowTV: no streams")
    except Exception as ex:
        errors.append(f"MeowTV: {str(ex)}")
    return results, errors


# ===== LookMovie (Vyla lookmovie.js): title search + security access =====

async def scrape_lookmovie(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, year = info.get("title"), info.get("year")
        if not title:
            errors.append("LookMovie: no TMDB title")
            return results, errors
        is_tv = media_type == "tv"
        typestr = "shows" if is_tv else "movies"
        async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
            base = match = None
            for b in ["https://www.lookmovie2.to", "https://lookmovie2.to"]:
                try:
                    resp = await client.get(f"{b}/api/v1/{typestr}/do-search/", params={"q": title},
                                            headers={"User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
                                                     "Referer": f"{b}/", "X-Requested-With": "XMLHttpRequest"})
                    res = (resp.json() or {}).get("result") or []
                    if res:
                        match = next((x for x in res if str(x.get("year")) == str(year)), None) \
                                or next((x for x in res if _sf_norm(x.get("title")) == _sf_norm(title)), None) \
                                or res[0]
                        base = b
                        break
                except Exception:
                    continue
            if not match:
                errors.append("LookMovie: title not in catalog")
                return results, errors

            resp = await client.get(f"{base}/{typestr}/play/{match['slug']}", headers={
                "User-Agent": HEADERS["User-Agent"], "Referer": f"{base}/", "Accept": "text/html"})
            html = resp.text
            storage = re.search(r"window\[['\"](?:movie|show)_storage['\"]\]\s*=\s*\{(.+?)\};", html, re.S)
            if not storage:
                errors.append("LookMovie: no storage block")
                return results, errors
            block = storage.group(1)
            hm = re.search(r"hash\s*:\s*['\"]([^'\"]+)['\"]", block)
            em = re.search(r"expires\s*:\s*(\d+)", block)
            if not (hm and em):
                errors.append("LookMovie: no hash/expires")
                return results, errors

            stream_id = match.get("id_movie") or match.get("id")
            if is_tv:
                sid = None
                parts = re.split(r"id_episode['\"]?\s*[:=]\s*['\"]?(\d+)['\"]?", html)
                for i in range(1, len(parts) - 1, 2):
                    ctx = parts[i - 1][-300:] + parts[i + 1][:300]
                    if re.search(rf"['\"]?episode['\"]?\s*[:=]\s*['\"]?{episode}['\"]?", ctx) and \
                       re.search(rf"['\"]?season['\"]?\s*[:=]\s*['\"]?{season}['\"]?", ctx):
                        sid = parts[i]
                        break
                if not sid:
                    am = re.search(rf'data-season=["\']{season}["\'][^>]*?data-episode=["\']{episode}["\'][^>]*?data-id=["\'](\d+)["\']', html) or \
                         re.search(rf'data-episode=["\']{episode}["\'][^>]*?data-season=["\']{season}["\'][^>]*?data-id=["\'](\d+)["\']', html)
                    sid = am.group(1) if am else None
                if not sid:
                    errors.append(f"LookMovie: episode S{season}E{episode} not found")
                    return results, errors
                stream_id = sid

            kind = "episode" if is_tv else "movie"
            resp = await client.get(f"{base}/api/v1/security/{kind}-access", params={
                f"id_{kind}": stream_id, "hash": hm.group(1), "expires": em.group(1)},
                headers={"User-Agent": HEADERS["User-Agent"], "Accept": "application/json",
                         "Referer": f"{base}/", "X-Requested-With": "XMLHttpRequest"})
            d = resp.json()
            streams = d.get("streams") or (d.get("result") or {}).get("streams") \
                      or (d.get("data") or {}).get("streams") or d
            if isinstance(streams, dict):
                for quality, u in streams.items():
                    if isinstance(u, str) and ".m3u8" in u:
                        results.append(_sf_stream_result(
                            "LookMovie", f"LookMovie - {quality}", u,
                            quality=str(quality), language="English"))
            if not results:
                errors.append("LookMovie: no m3u8 streams")
    except Exception as ex:
        errors.append(f"LookMovie: {str(ex)}")
    return results, errors


# ===== LMScript (Vyla lmscript.js): lmscript.xyz JSON API =====

async def scrape_lmscript(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    if media_type == "tv":
        errors.append("LMScript: movies only")
        return results, errors
    try:
        info = await get_tmdb_info(tmdb_id, media_type)
        title = info.get("title")
        if not title:
            errors.append("LMScript: no TMDB title")
            return results, errors
        async with httpx.AsyncClient(timeout=20, follow_redirects=True) as client:
            resp = await client.get("https://lmscript.xyz/v1/movies",
                                    params={"filters[q]": title, "expand": "streams"})
            d = resp.json()
        movie = next((it for it in (d.get("items") or [])
                      if str(it.get("tmdb_id")) == str(tmdb_id)
                      or str(it.get("tmdb_prefix")) == str(tmdb_id)), None)
        if not movie:
            errors.append("LMScript: title not in catalog")
            return results, errors
        order = {"1080p": 0, "720p": 1, "480p": 2, "360p": 3}
        for quality in sorted((movie.get("streams") or {}).keys(),
                               key=lambda q: order.get(q, 9)):
            u = (movie.get("streams") or {})[quality]
            if isinstance(u, str) and u.startswith("http"):
                results.append(_sf_stream_result(
                    "LMScript", f"LMScript - {quality}", u,
                    quality=str(quality), language="English"))
        if not results:
            errors.append("LMScript: no streams")
    except Exception as ex:
        errors.append(f"LMScript: {str(ex)}")
    return results, errors


# ===== Fsonic (Vyla fsonic.js): fsonic.net search + fsharetv.co mp4 =====

async def scrape_fsonic(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    if media_type == "tv":
        errors.append("Fsonic: movies only")
        return results, errors
    try:
        info = await get_tmdb_info(tmdb_id, media_type)
        title, year = info.get("title"), str(info.get("year") or "")
        if not title:
            errors.append("Fsonic: no TMDB title")
            return results, errors
        H = {"User-Agent": HEADERS["User-Agent"],
             "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
             "Accept-Language": "en-US,en;q=0.9"}
        watch_slug = None
        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            resp = await client.get(f"https://www.fsonic.net/movie/search/{quote(title)}", headers=H)
            for m in re.finditer(r'href="(/watch/[^"]+)"', resp.text):
                if year and year in m.group(1):
                    watch_slug = m.group(1)
                    break
                if not watch_slug:
                    watch_slug = m.group(1)
            if not watch_slug:
                errors.append("Fsonic: title not in catalog")
                return results, errors

            resp = await client.get(f"https://www.fsonic.net{watch_slug}", headers=H)
            m = re.search(r"init\('([^']+)',\s*(?:'[^']*',\s*)?'([^']+)'", resp.text)
            if not m:
                errors.append("Fsonic: no init token")
                return results, errors
            resp = await client.get(f"https://www.fsonic.net/api/source/{m.group(1)}",
                                    params={"trailer": m.group(2), "type": "watch"},
                                    headers={**H, "Accept": "application/json",
                                             "Referer": f"https://www.fsonic.net{watch_slug}"})
            j = resp.json()
        if j.get("status") != "ok":
            errors.append("Fsonic: source API error")
            return results, errors
        f = (j.get("data") or {}).get("file") or {}
        groups = [f.get("sources") or []] + [g for g in (f.get("alternatives") or []) if g]
        vheaders = {"User-Agent": HEADERS["User-Agent"], "Referer": "https://fsharetv.co/"}
        seen = set()
        for g in groups:
            best = sorted([x for x in g if x.get("src")],
                          key=lambda x: int(re.sub(r"\D", "", str(x.get("quality") or "0")) or 0),
                          reverse=True)
            if not best:
                continue
            src = best[0]["src"]
            if not src.startswith("http"):
                src = f"https://fsharetv.co{src}"
            if src in seen:
                continue
            seen.add(src)
            results.append(_sf_stream_result(
                "Fsonic", f"Fsonic - {best[0].get('quality') or 'Auto'} MP4", src,
                quality=str(best[0].get("quality") or "Auto"), language="English", headers=vheaders))
        if not results:
            errors.append("Fsonic: no streams")
    except Exception as ex:
        errors.append(f"Fsonic: {str(ex)}")
    return results, errors


# ===== Hexa (Vyla hexa.js): theemoviedb.hexa.su + enc-dec.app =====

async def scrape_hexa(tmdb_id: int, media_type: str, season: int = None, episode: int = None):
    results, errors = [], []
    try:
        async with httpx.AsyncClient(timeout=25, follow_redirects=True) as client:
            resp = await client.get(f"{_ENC_DEC}/enc-hexa")
            j = resp.json()
            if j.get("status") != 200:
                errors.append("Hexa: challenge failed")
                return results, errors
            cap_token = (j.get("result") or {}).get("token")
            api_key = "%064x" % random.getrandbits(256)
            decrypted = None
            for domain in ["hexa.su", "flixer.su"]:
                try:
                    if media_type == "tv":
                        url = f"https://theemoviedb.{domain}/api/tmdb/tv/{tmdb_id}/season/{season or 1}/episode/{episode or 1}/images"
                    else:
                        url = f"https://theemoviedb.{domain}/api/tmdb/movie/{tmdb_id}/images"
                    resp = await client.get(url, headers={
                        "User-Agent": HEADERS["User-Agent"], "Referer": f"https://{domain}/",
                        "Accept": "text/plain", "X-Fingerprint-Lite": "e9136c41504646444",
                        "X-Api-Key": api_key, "X-Cap-Token": cap_token})
                    if not resp.text:
                        continue
                    resp = await client.post(f"{_ENC_DEC}/dec-hexa",
                                             json={"text": resp.text, "key": api_key})
                    j = resp.json()
                    if j.get("status") == 200 and (j.get("result") or {}).get("sources"):
                        decrypted = j["result"]
                        break
                except Exception:
                    continue
            if not decrypted:
                errors.append("Hexa: no sources")
                return results, errors
            subs = [{"language": s.get("label") or s.get("lang") or "Sub", "url": s.get("url")}
                    for s in (decrypted.get("subtitles") or []) if s.get("url")]
            for src in decrypted.get("sources") or []:
                u = src.get("url")
                if u and u.startswith("http"):
                    results.append(_sf_stream_result(
                        f"Hexa/{src.get('name') or 'Server'}", f"Hexa - {src.get('name') or 'Server'}",
                        u, quality=str(src.get("quality") or "Auto"), language="English",
                        subtitles=subs or None))
        if not results:
            errors.append("Hexa: no streams")
    except Exception as ex:
        errors.append(f"Hexa: {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", "Multi"], "reliability": "high",
               "note": "hlowb.com API v2.0.1 getVideo2 (Nuvio castle.js port), AES-CBC, per-language m3u8 + TV shared stream. TS segments arrive disguised as image/jpeg (upstream obfuscation) - players handle them, and the proxy rewrites playlists end-to-end"},
    "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),
                  "languages": ["English", "Multi"], "reliability": "high",
                  "note": "net27.cc embed-tmdb, mp4 360p-1080p + subtitles (Nuvio netmirror.js port). CDN requires Referer https://videodownloader.site/ (the v12 429s were wrong-referer 429s, NOT IP blocks). Primary: play url + returned headers from the viewer device (Nuvio-app model, verified 206). proxied_url works on non-blocked hosts; bcdnxw additionally 426-range-blocks HF Spaces IPs"},
    "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"},
    "movies4u": {"name": "Movies4u", "fn": lambda tid, mt, s, e: scrape_movies4u(tid, mt, s, e),
                 "languages": ["Hindi", "English", "Multi"], "reliability": "medium",
                 "note": "m4uplay packed player -> acek-cdn m3u8 + HubCloud/Google direct, movie+TV"},
    "persianstremio": {"name": "PersianStremio", "fn": lambda tid, mt, s, e: scrape_persianstremio(tid, mt, s, e),
                       "languages": ["Multi", "Persian"], "reliability": "high",
                       "note": "stremio-style API (imdb based), direct MKV up to 2160p, movie+TV"},
    "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"},
    # --- v14: Vyla SDK ports (tested one-by-one from datacenter + HF) ---
    "vidfast": {"name": "VidFast", "fn": lambda tid, mt, s, e: scrape_vidfast(tid, mt, s, e),
                "languages": ["English"], "reliability": "high",
                "note": "vidfast.vc embed + enc-dec.app crypto relay (Vyla vidfast.js port). fMP4 HLS up to 2160p, multi-server, movie+TV, subtitles"},
    "vidup": {"name": "VidUp", "fn": lambda tid, mt, s, e: scrape_vidup(tid, mt, s, e),
              "languages": ["English"], "reliability": "high",
              "note": "vidup.to embed + enc-dec.app (Vyla vidup.js port). Same peakstorm CDN family as VidFast via a different upstream - complementary coverage, movie+TV"},
    "meowtv": {"name": "MeowTV", "fn": lambda tid, mt, s, e: scrape_meowtv(tid, mt, s, e),
               "languages": ["Hindi", "Multi", "English"], "reliability": "high",
               "note": "api.meowtv.ru + enc-dec.app dec-meowtv (Vyla meowtv.js port). Castle-CDN m3u8 (hindiv3), movie+TV"},
    "lookmovie": {"name": "LookMovie", "fn": lambda tid, mt, s, e: scrape_lookmovie(tid, mt, s, e),
                 "languages": ["English"], "reliability": "medium",
                 "note": "lookmovie2.to title search + security access API (Vyla lookmovie.js port). undersel.buzz HLS, movie+TV"},
    "lmscript": {"name": "LMScript", "fn": lambda tid, mt, s, e: scrape_lmscript(tid, mt, s, e),
                "languages": ["English"], "reliability": "medium",
                "note": "lmscript.xyz/v1/movies JSON API (Vyla lmscript.js port). undersel.buzz HLS 360-1080p, movies only"},
    "fsonic": {"name": "Fsonic", "fn": lambda tid, mt, s, e: scrape_fsonic(tid, mt, s, e),
               "languages": ["English"], "reliability": "medium",
               "note": "fsonic.net search + fsharetv.co direct MP4 720/1080 (Vyla fsonic.js port). Movies only"},
    "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e),
               "languages": ["English"], "reliability": "medium",
               "note": "vidrock.ru/api + AES-GCM decrypt (Vyla vidrock.js port). ngcorp.dad/flamingo workers m3u8. Movies verified playable; TV episodes route segments via ByteDance ipstatp CDN that 403s datacenter IPs"},
    "hexa": {"name": "Hexa", "fn": lambda tid, mt, s, e: scrape_hexa(tid, mt, s, e),
             "languages": ["English"], "reliability": "low",
             "note": "theemoviedb.hexa.su + enc-dec.app (Vyla hexa.js port). dragonballzfans CDNs, movie+TV, intermittent"},
}

DEFAULT_SOURCES = ["castle", "netmirror", "playbox", "movix", "vidfast", "vidup",
                   "meowtv", "lookmovie", "lmscript", "fsonic", "vidrock", "hexa",
                   "movies4u", "persianstremio"]


# ===== 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=60)
            return r, e
        except asyncio.TimeoutError:
            return [], [f"{src['name']}: Timeout (60s)"]
        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 = []
    base = _get_base()
    for r in all_results:
        r["url"] = re.sub(r'[\x00-\x1f\x7f]', '', r.get("url") or "")
        for fld in ("direct_url", "proxied_url"):
            if r.get(fld):
                r[fld] = re.sub(r'[\x00-\x1f\x7f]', '', r[fld])
                if r[fld].startswith("/"):
                    r[fld] = f"{base}{r[fld]}"
        if r.get("subtitles"):
            for sub in r["subtitles"]:
                if isinstance(sub, dict) and isinstance(sub.get("url"), str) and sub["url"].startswith("/"):
                    sub["url"] = f"{base}{sub['url']}"
        if r["url"] not in seen_urls:
            seen_urls.add(r["url"])
            # make absolute proxy URLs
            if r["url"].startswith("/"):
                r["url"] = f"{base}{r['url']}"
            # every stream gets an absolute proxied fallback (header injection,
            # IP-pinned tokens and missing CORS are all solved by playing via the API)
            if not r.get("proxied_url") and not r.get("direct_url"):
                hdrs = r.get("headers") or {}
                r["proxied_url"] = _proxy_wrap(r["url"],
                                               ref=hdrs.get("Referer"),
                                               ua=hdrs.get("User-Agent"),
                                               origin=hdrs.get("Origin"))
            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": "13.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"},
            "proxy": {"path": "/proxy_range?u=<url>&ref=<referer>&ua=<user-agent>&origin=<origin>",
                      "note": "Range-capable stream proxy with header injection + m3u8 rewriting. ALL proxied stream URLs returned by this API are ABSOLUTE - use them as-is in any player"},
            "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_v12": {
            "fixed": [
                "Proxy URLs are ABSOLUTE now - v11 returned relative /proxy_range?... URLs which players cannot resolve (the reason NetMirror 'loaded but wouldn't play' and several servers showed red)",
                "Proxy engine v2: Range passthrough on both /proxy and /proxy_range, HEAD support, Origin injection, content-sniffed m3u8 detection, absolute-rewritten playlists",
                "PlayBox: m3u8 now served through the proxy with Referer+Origin+UA (its gateway intermittently serves a JSON error page to direct client fetches = red tests)",
                "Movies4u: candidate m3u8s validated at scrape time - PNG block pages / dead tokens are dropped, only verified playlists returned",
                "Every stream carries an absolute proxied_url fallback; Castle/Movix direct URLs unchanged (verified playable)",
            ],
            "notes": [
                "NetMirror/MOON: bcdnxw CDN 429-blocks ALL datacenter IPs (HF included). Primary = direct mp4 + Referer/UA headers (plays from the viewing device's IP, like the Nuvio app). If your player cannot send headers and the device IP is blocked, NetMirror cannot play - that is a CDN-level block, not a scraper bug.",
                "PersianStremio: direct MKV links are Range-capable (verified 206); 4K/HEVC entries need a player with HEVC support (not browser-native)",
            ],
        },
        "changelog_v11": {
            "fixed": [
                "NetMirror: returns direct mp4 + required headers (Referer/UA) + subtitles; its CDN 429-blocks ALL datacenter IPs so server-side proxying is impossible - the client (device IP) must play with the returned headers, exactly like the Nuvio app does. proxied_url kept as fallback.",
            ],
            "added": [
                "Movies4u - m4uplay packed-player unpack -> acek-cdn m3u8 + HubCloud/Google direct",
                "PersianStremio - stremio-style imdb API, direct MKV up to 2160p, movie+TV",
                "UHDMovies - works in Nuvio (node) but its unblockedgames gate fingerprint-blocks the final hop from Python/httpx - noted, not added",
                "/proxy_range - Range-capable stream proxy with header injection + m3u8 rewriting",
            ],
            "removed": [
                "VidLove - api.shows.st 403 'Website Access Blocked' for all datacenter IPs (dead for server-side use)",
            ],
            "kept": ["Castle, PlayBox, Movix (verified playable), VegaMovies (registered)"],
        },
        "source_repos": ["github.com/D3adlyRocket/All-in-One-Nuvio", "github.com/yogesh-hacker/MediaVanced"],
        "tips": [
            "No source = default sources (castle, netmirror, playbox, movix, movies4u, persianstremio)",
            "Every stream includes an ABSOLUTE proxied_url fallback - if direct playback fails, play proxied_url (works from any client IP, CORS-safe)",
            "NetMirror: play url WITH its headers (Referer+UA) from the device IP; proxied_url exists but the CDN 429-blocks datacenter IPs (HF included)",
            "Castle: multi-language m3u8 (English/Tamil/Telugu)",
            "Movix/PlayBox/Movies4u: m3u8; PersianStremio/UHDMovies/VegaMovies: direct MKV (VLC/mpv/exoplayer)",
            "Each result may include: headers (native playback), direct_url (raw URL), proxied_url (absolute proxy URL), subtitles (proxied VTT)",
        ],
    }


# ===== 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)