File size: 114,901 Bytes
a330af4
cb18578
93094bf
cb18578
 
 
a330af4
 
 
 
 
 
 
 
 
699389b
a330af4
 
900c3a8
a330af4
 
 
93094bf
2e4071e
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a330af4
0334f45
 
 
 
 
 
 
 
 
 
 
 
a330af4
93094bf
a330af4
 
900c3a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a330af4
 
cb18578
d59d8ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
5bf3320
1d6e15b
 
 
 
 
900c3a8
 
1d6e15b
 
900c3a8
 
f0eee2c
1d6e15b
 
900c3a8
cb18578
 
f0eee2c
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
f0eee2c
 
900c3a8
cb18578
f0eee2c
 
 
cb18578
1d6e15b
cb18578
 
e6abf12
f0eee2c
cb18578
f0eee2c
 
cb18578
f0eee2c
 
 
 
cb18578
 
f0eee2c
5bf3320
f0eee2c
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf3320
f0eee2c
cb18578
 
 
 
 
 
 
f0eee2c
 
 
cb18578
f0eee2c
 
 
900c3a8
1d6e15b
5bf3320
cb18578
5bf3320
f0eee2c
900c3a8
1d6e15b
f0eee2c
cb18578
5bf3320
 
f0eee2c
 
cb18578
 
 
 
30720b7
5bf3320
30720b7
5bf3320
900c3a8
cb18578
f0eee2c
cb18578
 
 
 
f0eee2c
cb18578
 
 
 
 
f0eee2c
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30720b7
 
cb18578
f0eee2c
 
900c3a8
f0eee2c
900c3a8
cb18578
f0eee2c
 
 
 
 
 
900c3a8
cb18578
5bf3320
cb18578
 
f0eee2c
cb18578
f0eee2c
 
cb18578
 
 
 
 
 
f0eee2c
30720b7
 
5bf3320
f0eee2c
 
cb18578
 
 
 
 
f0eee2c
 
 
 
 
 
 
cb18578
f0eee2c
cb18578
 
 
 
5bf3320
f0eee2c
 
cb18578
 
5bf3320
f0eee2c
5bf3320
f0eee2c
900c3a8
cb18578
f0eee2c
 
 
900c3a8
cb18578
30720b7
e6abf12
f0eee2c
cb18578
 
 
 
 
 
 
 
 
 
 
5bf3320
f0eee2c
cb18578
 
 
 
5bf3320
ad20b55
 
 
cb18578
e6abf12
cb18578
ad20b55
 
 
cb18578
f0eee2c
 
cb18578
 
 
 
ad20b55
cb18578
ad20b55
cb18578
f0eee2c
ad20b55
47f0671
ad20b55
f0eee2c
30720b7
 
 
 
f0eee2c
 
 
cb18578
 
f0eee2c
30720b7
f0eee2c
cb18578
 
 
 
30720b7
 
f0eee2c
30720b7
f0eee2c
 
cb18578
 
 
 
5bf3320
 
30720b7
 
 
 
f0eee2c
 
5bf3320
30720b7
cb18578
 
1d6e15b
30720b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
 
30720b7
 
 
 
 
cb18578
30720b7
 
cb18578
 
30720b7
 
cb18578
 
 
f0eee2c
 
cb18578
 
 
 
 
 
30720b7
cb18578
 
30720b7
 
 
 
 
 
 
 
cb18578
 
1d6e15b
900c3a8
f0eee2c
 
1d6e15b
f0eee2c
 
 
 
1d6e15b
 
f0eee2c
1d6e15b
900c3a8
 
1d6e15b
f0eee2c
1d6e15b
 
 
cb18578
 
1d6e15b
900c3a8
1d6e15b
 
 
 
cb18578
900c3a8
cb18578
1d6e15b
900c3a8
 
 
 
 
 
 
 
 
1d6e15b
900c3a8
cb18578
 
 
 
 
900c3a8
1d6e15b
cb18578
900c3a8
 
 
 
 
1d6e15b
 
900c3a8
 
cb18578
 
 
 
 
 
900c3a8
 
 
 
 
1d6e15b
900c3a8
 
 
 
 
 
cb18578
 
 
900c3a8
cb18578
 
900c3a8
 
 
cb18578
 
900c3a8
cb18578
900c3a8
 
 
 
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
 
cb18578
900c3a8
 
 
 
 
 
 
 
 
 
 
 
cb18578
900c3a8
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
 
cb18578
 
900c3a8
 
 
 
1d6e15b
900c3a8
 
 
 
1d6e15b
 
900c3a8
 
1d6e15b
 
 
900c3a8
 
 
 
 
cb18578
 
900c3a8
cb18578
 
 
 
 
 
 
 
1d6e15b
cb18578
 
900c3a8
 
1d6e15b
 
900c3a8
 
1d6e15b
 
 
900c3a8
1d6e15b
 
 
900c3a8
1d6e15b
 
900c3a8
1d6e15b
 
 
 
cb18578
1d6e15b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
 
 
 
 
 
 
 
 
 
1d6e15b
 
 
 
 
 
 
 
900c3a8
1d6e15b
 
900c3a8
 
 
 
1d6e15b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
 
1d6e15b
 
cb18578
1d6e15b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
1d6e15b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
ad34132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
ad34132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
ad34132
 
 
0db2d27
 
 
 
ad34132
59763d4
 
0db2d27
 
 
 
 
cb18578
0db2d27
cb18578
0db2d27
ad34132
 
7e9b9b2
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
7e9b9b2
cb18578
7e9b9b2
 
 
 
cb18578
7e9b9b2
 
 
 
cb18578
7e9b9b2
 
cb18578
7e9b9b2
 
cb18578
7e9b9b2
 
 
 
 
 
 
 
 
 
 
cb18578
7e9b9b2
cb18578
7e9b9b2
cb18578
7e9b9b2
 
 
 
 
cb18578
7e9b9b2
 
0db2d27
ad34132
 
 
cb18578
7e9b9b2
 
cb18578
0db2d27
 
900c3a8
cb18578
0db2d27
 
 
 
 
ad34132
cb18578
0db2d27
900c3a8
cb18578
0db2d27
 
 
 
 
 
 
cb18578
0db2d27
 
 
 
 
 
 
 
 
cb18578
0db2d27
 
900c3a8
cb18578
0db2d27
 
cb18578
0db2d27
7e9b9b2
 
 
 
ad34132
 
 
 
 
 
 
cb18578
ad34132
 
 
 
 
 
0334f45
 
 
 
 
cb18578
0334f45
 
ad34132
 
 
 
 
 
0334f45
 
 
 
 
 
 
 
 
 
 
 
 
 
ad34132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
561be79
cb18578
86ad7da
 
 
 
 
 
 
cb18578
86ad7da
 
 
 
 
 
 
cb18578
86ad7da
 
 
 
2c8dab3
 
 
 
86ad7da
2c8dab3
cb18578
2c8dab3
 
 
86ad7da
 
 
 
 
 
 
2c8dab3
 
 
86ad7da
cb18578
2c8dab3
86ad7da
 
 
 
 
 
 
2c8dab3
86ad7da
 
 
 
 
2c8dab3
 
cb18578
2c8dab3
 
86ad7da
 
2c8dab3
86ad7da
 
 
 
 
 
2c8dab3
86ad7da
2c8dab3
 
 
cb18578
2c8dab3
 
 
 
 
 
 
 
86ad7da
 
 
 
 
 
2c8dab3
86ad7da
 
2c8dab3
 
 
 
 
 
 
 
86ad7da
 
 
 
2c8dab3
86ad7da
2c8dab3
 
86ad7da
cb18578
86ad7da
 
2c8dab3
 
 
86ad7da
2c8dab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86ad7da
2c8dab3
cb18578
2c8dab3
 
 
 
 
 
 
 
 
cb18578
2c8dab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86ad7da
 
 
 
 
 
2c8dab3
cb18578
900c3a8
 
 
 
 
 
 
 
cb18578
 
 
 
 
 
 
 
 
900c3a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
900c3a8
 
 
cb18578
900c3a8
cb18578
900c3a8
 
 
 
 
 
 
 
cb18578
900c3a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb18578
 
900c3a8
d722b8e
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
 
 
 
 
 
 
 
cb18578
 
900c3a8
 
 
905e847
900c3a8
 
 
905e847
900c3a8
905e847
d722b8e
cb18578
 
d722b8e
905e847
900c3a8
 
 
 
 
 
 
 
 
 
cb18578
 
900c3a8
 
905e847
 
900c3a8
905e847
 
900c3a8
905e847
 
 
 
cb18578
900c3a8
cb18578
900c3a8
 
 
 
cb18578
 
900c3a8
cb18578
 
900c3a8
 
cb18578
 
 
 
900c3a8
 
 
 
cb18578
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
 
cb18578
 
 
900c3a8
cb18578
 
 
 
 
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
 
 
 
900c3a8
cb18578
 
 
900c3a8
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
 
 
 
 
 
900c3a8
cb18578
 
 
900c3a8
cb18578
 
900c3a8
cb18578
 
900c3a8
cb18578
 
 
900c3a8
cb18578
 
 
900c3a8
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900c3a8
cb18578
900c3a8
 
cb18578
900c3a8
 
 
 
cb18578
900c3a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d722b8e
 
cb18578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
 
d59d8ea
 
1d6e15b
cb18578
 
900c3a8
cb18578
 
86ad7da
 
ad34132
 
1d6e15b
 
905e847
cb18578
 
900c3a8
cb18578
 
900c3a8
 
cb18578
 
 
 
 
 
 
 
 
426e8e9
 
2e4071e
426e8e9
 
93094bf
426e8e9
 
 
 
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
1d6e15b
426e8e9
 
1d6e15b
426e8e9
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
 
 
1d6e15b
 
 
 
 
 
 
426e8e9
1d6e15b
426e8e9
 
93094bf
 
1d6e15b
93094bf
426e8e9
 
 
93094bf
a330af4
 
426e8e9
93094bf
 
cb18578
93094bf
 
 
 
 
 
900c3a8
93094bf
 
 
 
 
cb18578
93094bf
 
 
 
 
 
 
 
 
 
 
 
 
4303eeb
 
93094bf
 
cb18578
 
 
 
 
 
 
93094bf
cb18578
 
 
 
ad34132
cb18578
 
900c3a8
cb18578
 
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
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
"""
StreamForge API v8 - Multi-Language Stream Scraper
Scrapes direct m3u8 URLs from multiple sources
Updated: MovieBox, Castle, VidLink, VidSrc, NetMirror
Added: VidFast, ShowBox, GoatAPI
Removed: CineSu (dead), PrimeSrc (Cloudflare), DooFlix (API key revoked)
"""

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

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

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

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

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


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

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


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

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


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


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


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


def cryptojs_aes_decrypt(ciphertext_b64: str, passphrase: str) -> str:
    """Decrypt CryptoJS.AES.encrypt output (OpenSSL format with Salted__ prefix)."""
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import unpad

    raw = base64.b64decode(ciphertext_b64)
    if raw[:8] != b"Salted__":
        cipher = AES.new(passphrase.encode()[:32], AES.MODE_CBC, passphrase.encode()[:16])
        return unpad(cipher.decrypt(raw), AES.block_size).decode("utf-8", errors="ignore")

    salt = raw[8:16]
    ct = raw[16:]
    key, iv = evp_bytes_to_key(passphrase.encode(), salt)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(ct), AES.block_size).decode("utf-8", errors="ignore")


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


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


def parse_m3u8_quality(m3u8_content: str, base_url: str = "") -> list:
    """Parse m3u8 master playlist and extract quality variants."""
    variants = []
    if "#EXT-X-STREAM-INF" in m3u8_content:
        lines = m3u8_content.split("\n")
        for i, line in enumerate(lines):
            if line.startswith("#EXT-X-STREAM-INF:"):
                resolution = re.search(r'RESOLUTION=(\d+x\d+)', line)
                name = re.search(r'NAME="([^"]+)"', line)
                quality = resolution.group(1) if resolution else "Auto"
                label = name.group(1) if name else quality
                if i + 1 < len(lines) and lines[i + 1].strip():
                    variant_url = lines[i + 1].strip()
                    if not variant_url.startswith("http") and base_url:
                        variant_url = f"{base_url}/{variant_url}"
                    variants.append({"label": label, "quality": quality, "url": variant_url})
    return variants


def detect_quality_from_label(label: str) -> str:
    """Detect quality from stream label text."""
    lower = label.lower()
    if "4k" in lower or "2160" in lower:
        return "4K"
    if "1080" in lower or "fhd" in lower:
        return "1080p FHD"
    if "720" in lower or "hd" in lower:
        return "720p HD"
    if "480" in lower or "sd" in lower:
        return "480p SD"
    return "Auto"


# ===== VidRock Scraper (AES-encrypted API) - KEEP AS-IS =====

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

    try:
        from Crypto.Cipher import AES as CryptoAES
        from Crypto.Util.Padding import pad as crypto_pad

        passphrase = b"x7k9mPqT2rWvY8zA5bC3nF6hJ2lK4mN9"
        aes_key = passphrase[:32]
        aes_iv = passphrase[:16]

        if media_type == "tv":
            s = season or 1
            e = episode or 1
            item_id = f"{tmdb_id}_{s}_{e}"
            api_type = "tv"
        else:
            item_id = str(tmdb_id)
            api_type = "movie"

        cipher = CryptoAES.new(aes_key, CryptoAES.MODE_CBC, aes_iv)
        ct = cipher.encrypt(crypto_pad(item_id.encode(), CryptoAES.block_size))
        encoded = base64.b64encode(ct).decode().replace("+", "-").replace("/", "_").replace("=", "")

        async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:
            resp = await client.get(f"https://vidrock.net/api/{api_type}/{encoded}")
            if resp.status_code != 200:
                errors.append(f"VidRock: HTTP {resp.status_code}")
                return results, errors

            data = resp.json()
            for server_name, server_data in data.items():
                if isinstance(server_data, dict) and server_data.get("url"):
                    url = server_data["url"]
                    lang = server_data.get("language", "English")
                    stream_type = server_data.get("type", "hls")
                    s_type = "m3u8" if stream_type == "hls" or ".m3u8" in url else "direct"

                    results.append({
                        "source": f"VidRock/{server_name}",
                        "title": f"{server_name} - {lang}",
                        "quality": "Auto",
                        "language": detect_language(lang),
                        "url": url,
                        "type": s_type,
                    })

            if not results:
                errors.append("VidRock: No streams found")

    except ImportError:
        errors.append("VidRock: pycryptodome not installed")
    except Exception as e:
        errors.append(f"VidRock: {str(e)}")

    return results, errors


# ===== Castle Scraper (hlowb.com API with AES-CBC) - COMPLETE REWRITE =====

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            # Step 4: Get video via getVideo2
            for resolution in [3, 2, 1]:  # Try 1080p, 720p, 480p
                try:
                    body = {
                        "mode": "1",
                        "appMarket": "google_play",
                        "clientType": CLI,
                        "woolUser": "0",
                        "apkSignKey": SIGN,
                        "androidVersion": "13",
                        "movieId": mid,
                        "episodeId": str(ep_id),
                        "isNewUser": "1",
                        "resolution": str(resolution),
                        "packageName": PKG,
                    }
                    vr = await client.post(
                        f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
                        params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},
                        json=body,
                        headers={"Content-Type": "application/json"}
                    )
                    if vr.status_code != 200:
                        errors.append(f"Castle: video HTTP {vr.status_code} res={resolution}")
                        continue

                    try:
                        vp = castle_decrypt(vr.text)
                    except Exception as vde:
                        errors.append(f"Castle: video decrypt fail res={resolution}: {vde}")
                        continue

                    vd = vp.get("data", vp)
                    if isinstance(vd, str):
                        try:
                            vd = json.loads(vd)
                        except Exception:
                            continue
                    if not isinstance(vd, dict):
                        errors.append(f"Castle: video not dict res={resolution}")
                        continue

                    vurl = vd.get("videoUrl", "")
                    if not vurl:
                        errors.append(f"Castle: video API error res={resolution}: code={vd.get('code')}, msg={vd.get('msg')}")
                        continue

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

                    # Check for quality variants in videos array
                    vids = vd.get("videos", [])
                    if vids and isinstance(vids, list):
                        for v in vids:
                            if not isinstance(v, dict):
                                continue
                            vu = v.get("url", vurl)
                            q = v.get("resolutionDescription", v.get("resolution", quality))
                            q = re.sub(r'^(SD|HD|FHD)\s+', '', str(q))
                            # Extract subtitles if present
                            subs = v.get("subtitles", [])

                            result_item = {
                                "source": "Castle",
                                "title": f"Castle - {q}",
                                "quality": q,
                                "language": "English",
                                "url": vu,
                                "type": "m3u8" if ".m3u8" in vu else "direct",
                            }
                            if subs:
                                result_item["subtitles"] = subs
                            results.append(result_item)
                    else:
                        results.append({
                            "source": "Castle",
                            "title": f"Castle - {quality}",
                            "quality": quality,
                            "language": "English",
                            "url": vurl,
                            "type": "m3u8" if ".m3u8" in vurl else "direct",
                        })
                    break  # Got a stream, stop trying lower resolutions
                except Exception:
                    continue

            # Also try per-language tracks
            langs = dd.get("languages", dd.get("languageList", []))
            if isinstance(langs, list):
                for lt in langs:
                    lid = None
                    ln = ""
                    if isinstance(lt, dict):
                        lid = lt.get("languageId", lt.get("id"))
                        ln = lt.get("name", lt.get("languageName", ""))
                    elif isinstance(lt, str):
                        ln = lt
                        ll = dd.get("languageList", [])
                        for lli in ll:
                            if isinstance(lli, dict) and lli.get("name", "").lower() == lt.lower():
                                lid = lli.get("languageId", lli.get("id"))
                                break
                    if not lid:
                        continue
                    try:
                        body = {
                            "mode": "1", "appMarket": "google_play", "clientType": CLI,
                            "woolUser": "0", "apkSignKey": SIGN, "androidVersion": "13",
                            "movieId": mid, "episodeId": str(ep_id), "languageId": str(lid),
                            "isNewUser": "1", "resolution": "3", "packageName": PKG,
                        }
                        vr = await client.post(
                            f"{CASTLE_BASE}/film-api/v2.0.1/movie/getVideo2",
                            params={"clientType": CLI, "packageName": PKG, "channel": CH, "lang": LANG},
                            json=body, headers={"Content-Type": "application/json"}
                        )
                        if vr.status_code != 200:
                            continue
                        vp = castle_decrypt(vr.text)
                        vd = vp.get("data", vp)
                        if isinstance(vd, str):
                            try:
                                vd = json.loads(vd)
                            except Exception:
                                continue
                        if not isinstance(vd, dict):
                            continue
                        vurl = vd.get("videoUrl", "")
                        if not vurl:
                            continue
                        results.append({
                            "source": f"Castle [{ln}]",
                            "title": f"Castle {ln} - 1080p",
                            "quality": "1080p",
                            "language": detect_language(ln) if ln else "English",
                            "url": vurl,
                            "type": "m3u8" if ".m3u8" in vurl else "direct",
                        })
                    except Exception:
                        continue

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

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

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

    return results, errors


# ===== MovieBox Scraper (themoviebox.org) - UPDATED =====

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

    try:
        MOVIEBOX_SITE = "https://themoviebox.org"
        MOVIEBOX_BASE = "https://h5-api.aoneroom.com"
        MOVIEBOX_TMDB_KEY = "d131017ccc6e5462a81c9304d21476de"

        def generate_moviebox_token() -> str:
            ts = str(int(time.time()))
            reversed_ts = ts[::-1]
            md5_hash = hashlib.md5(reversed_ts.encode()).hexdigest()
            return f"{ts}.{md5_hash}"

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:
            token = generate_moviebox_token()
            mb_headers = {
                "Accept": "application/json",
                "token": token,
                "x-client-info": json.dumps({"timezone": "Asia/Calcutta"}),
                "x-request-lang": "en",
                "X-Client-Token": token,
                "Origin": MOVIEBOX_SITE,
                "Referer": f"{MOVIEBOX_SITE}/",
            }

            # Step 1: Search for the movie/TV show
            info = await get_tmdb_info(tmdb_id, media_type)
            title = info.get("title", "")
            year = info.get("year", "")
            if not title:
                errors.append("MovieBox: Could not get title from TMDB")
                return results, errors

            search_resp = await client.post(
                f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/search",
                json={
                    "keyword": title,
                    "page": 1,
                    "perPage": 28,
                    "subjectType": 0,  # 0 = all, 1 = movie, 2 = tv
                },
                headers=mb_headers,
            )
            if search_resp.status_code != 200:
                errors.append(f"MovieBox: Search failed HTTP {search_resp.status_code}")
                return results, errors

            search_data = search_resp.json()
            search_items = search_data.get("data", {}).get("items", [])
            if not search_items:
                errors.append("MovieBox: No search results")
                return results, errors

            # Step 2: Match by normalized title + year, with subjectType filtering
            title_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(title).lower())
            target_subject_type = 1 if media_type == "movie" else 2
            matched_item = None

            # First: exact title match + correct subjectType + year
            for item in search_items:
                item_title = item.get("title", "") or item.get("name", "")
                item_year = str(item.get("year", "") or item.get("releaseYear", ""))
                item_type = item.get("subjectType", item.get("type", 0))
                item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower())

                if item_norm == title_norm and item_type == target_subject_type:
                    if year and item_year and year == item_year:
                        matched_item = item
                        break
                    elif not year or not item_year:
                        matched_item = item
                        break

            # Second: substring match + correct subjectType
            if not matched_item:
                for item in search_items:
                    item_title = item.get("title", "") or item.get("name", "")
                    item_type = item.get("subjectType", item.get("type", 0))
                    item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower())

                    if (title_norm in item_norm or item_norm in title_norm) and item_type == target_subject_type:
                        matched_item = item
                        break

            # Third: match without subjectType filter
            if not matched_item:
                for item in search_items:
                    item_title = item.get("title", "") or item.get("name", "")
                    item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower())
                    if item_norm == title_norm:
                        matched_item = item
                        break

            # Fourth: substring without type filter
            if not matched_item:
                for item in search_items:
                    item_title = item.get("title", "") or item.get("name", "")
                    item_norm = re.sub(r'[^a-zA-Z0-9]', '', normalize_title(item_title).lower())
                    if title_norm in item_norm or item_norm in title_norm:
                        matched_item = item
                        break

            if not matched_item and search_items:
                matched_item = search_items[0]

            if not matched_item:
                errors.append("MovieBox: No matching title found")
                return results, errors

            subject_id = matched_item.get("id")
            detail_path = matched_item.get("detailPath", "")
            if not subject_id:
                errors.append("MovieBox: No subject ID in matched item")
                return results, errors

            # Step 3: Get detail using detailPath (new API)
            token = generate_moviebox_token()
            mb_headers["token"] = token
            mb_headers["X-Client-Token"] = token

            if detail_path:
                detail_resp = await client.get(
                    f"{MOVIEBOX_BASE}/wefeed-h5api-bff/detail",
                    params={"detailPath": detail_path},
                    headers=mb_headers,
                )
            else:
                detail_resp = await client.get(
                    f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/detail",
                    params={"subjectId": subject_id},
                    headers=mb_headers,
                )

            detail_data = {}
            if detail_resp.status_code == 200:
                detail_data = detail_resp.json().get("data", {})

            # Step 4: Get download URLs
            token = generate_moviebox_token()
            mb_headers["token"] = token
            mb_headers["X-Client-Token"] = token

            dp = detail_path or f"/subject/{subject_id}"

            # For TV: find season/episode, then get download for specific episode
            dl_subject_id = subject_id
            if media_type == "tv":
                s = season or 1
                e = episode or 1

                episodes = detail_data.get("episodes", [])
                target_ep = None
                for ep_item in episodes:
                    ep_season = ep_item.get("seasonNumber", ep_item.get("season", 0))
                    ep_num = ep_item.get("episodeNumber", ep_item.get("episode", 0))
                    if int(ep_season) == s and int(ep_num) == e:
                        target_ep = ep_item
                        break

                if target_ep and target_ep.get("id"):
                    dl_subject_id = target_ep["id"]
                    ep_dp = target_ep.get("detailPath", "")
                    if ep_dp:
                        dp = ep_dp

            dl_resp = await client.get(
                f"{MOVIEBOX_BASE}/wefeed-h5api-bff/subject/download",
                params={"subjectId": dl_subject_id, "ep": str(dl_subject_id)},
                headers={**mb_headers, "Referer": f"{MOVIEBOX_SITE}/play/{dp}"},
            )
            if dl_resp.status_code != 200:
                errors.append(f"MovieBox: Download request failed HTTP {dl_resp.status_code}")
                return results, errors

            dl_data = dl_resp.json()
            dl_items = dl_data.get("data", {}).get("items", [])
            if not dl_items:
                errors.append("MovieBox: No download items found")
                return results, errors

            for dl_item in dl_items:
                stream_url = dl_item.get("url") or dl_item.get("downloadUrl") or dl_item.get("playUrl", "")
                if not stream_url:
                    continue

                quality = dl_item.get("quality") or dl_item.get("resolution") or "Auto"
                q_match = re.search(r'(\d{3,4})p', str(quality))
                if q_match:
                    quality = q_match.group(1) + "p"

                # Extract language from title brackets or from language field
                dl_name = dl_item.get("name") or dl_item.get("title") or dl_item.get("serverName", "")
                lang = dl_item.get("language") or dl_item.get("audio", "")
                if lang:
                    lang = detect_language(lang)
                else:
                    bracket_lang = extract_language_from_title(dl_name)
                    if bracket_lang:
                        lang = bracket_lang
                    else:
                        lang = "English"

                name = dl_name or "MovieBox Stream"
                name = normalize_title(name) if name else "MovieBox Stream"

                s_type = "m3u8" if ".m3u8" in stream_url else ("direct" if ".mp4" in stream_url or ".mkv" in stream_url else "m3u8")

                results.append({
                    "source": "MovieBox",
                    "title": name,
                    "quality": quality,
                    "language": lang,
                    "url": stream_url,
                    "type": s_type,
                })

            if not results:
                errors.append("MovieBox: No streams found")

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

    return results, errors


# ===== Videasy Scraper (Multi-server encrypted API) - KEEP AS-IS =====

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

    try:
        VIDEASY_HEADERS = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
            "Accept": "application/json, text/plain, */*",
            "Origin": "https://player.videasy.net",
            "Referer": "https://player.videasy.net/",
        }
        DECRYPT_API = "https://enc-dec.app/api/dec-videasy"

        SERVERS = {
            "Neon": {"url": "https://api.videasy.net/myflixerzupcloud/sources-with-title"},
            "Cypher": {"url": "https://api.videasy.net/moviebox/sources-with-title"},
            "Reyna": {"url": "https://api.videasy.net/primewire/sources-with-title"},
            "Omen": {"url": "https://api.videasy.net/onionplay/sources-with-title"},
            "Breach": {"url": "https://api.videasy.net/m4uhd/sources-with-title"},
            "Ghost": {"url": "https://api.videasy.net/primesrcme/sources-with-title"},
            "Sage": {"url": "https://api.videasy.net/1movies/sources-with-title"},
            "Vyse": {"url": "https://api.videasy.net/hdmovie/sources-with-title"},
            "Raze": {"url": "https://api.videasy.net/superflix/sources-with-title"},
            "Yoru": {"url": "https://api.videasy.net/cdn/sources-with-title", "moviesOnly": True},
            "SuperFlix": {"url": "https://api.videasy.net/superflix/sources-with-title"},
        }

        info = await get_tmdb_info(tmdb_id, media_type)
        title = info.get("title", "")
        year = info.get("year", "")
        imdb_id = info.get("imdb_id", "")

        async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=VIDEASY_HEADERS) as client:
            async def fetch_server(name: str, config: dict):
                server_results = []
                try:
                    if config.get("moviesOnly") and media_type == "tv":
                        return server_results, f"{name}: Movies only"

                    endpoint = config["url"]
                    url = f"{endpoint}?title={title}&mediaType={media_type}&year={year}&tmdbId={tmdb_id}&imdbId={imdb_id or ''}"
                    if media_type == "tv":
                        s = season or 1
                        e = episode or 1
                        url += f"&seasonId={s}&episodeId={e}"

                    resp = await client.get(url)
                    encrypted_text = resp.text

                    if not encrypted_text or len(encrypted_text) < 20 or encrypted_text.startswith("<!"):
                        return server_results, f"{name}: No data or blocked"

                    dec_resp = await client.post(
                        DECRYPT_API,
                        json={"text": encrypted_text, "id": str(tmdb_id)},
                        headers={"Content-Type": "application/json"},
                    )

                    if dec_resp.status_code != 200:
                        return server_results, f"{name}: Decrypt failed"

                    decrypted = dec_resp.json()
                    res_data = decrypted.get("result") or decrypted

                    if not res_data or not res_data.get("sources"):
                        return server_results, f"{name}: No sources"

                    for s_item in res_data["sources"]:
                        stream_url = s_item.get("url", "")
                        if not stream_url:
                            continue
                        quality = s_item.get("quality", "Auto")

                        server_results.append({
                            "source": f"Videasy/{name}",
                            "title": f"Videasy {name}",
                            "quality": quality,
                            "language": "English",
                            "url": stream_url,
                            "type": "m3u8",
                            "headers": {
                                "Referer": "https://player.videasy.net/",
                                "Origin": "https://player.videasy.net",
                                "User-Agent": VIDEASY_HEADERS["User-Agent"],
                            },
                        })

                except Exception as e:
                    return server_results, f"{name}: {str(e)}"

                return server_results, None

            tasks = [fetch_server(name, config) for name, config in SERVERS.items()]
            task_results = await asyncio.gather(*tasks, return_exceptions=True)

            for result in task_results:
                if isinstance(result, Exception):
                    errors.append(f"Videasy: {str(result)}")
                else:
                    server_results, error = result
                    results.extend(server_results)
                    if error:
                        errors.append(f"Videasy {error}")

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

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

    return results, errors


# ===== NetMirror Scraper (Netflix/PrimeVideo/Hotstar via API) - UPDATED TMDB KEY =====

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

    try:
        CONFIG_URL = "https://raw.githubusercontent.com/SaurabhKaperwan/Utils/refs/heads/main/urls.json"
        FALLBACK_API = "https://tv.imgcdn.kim/newtv"
        OTT_SERVICES = [
            {"code": "nf", "name": "Netflix"},
            {"code": "pv", "name": "PrimeVideo"},
            {"code": "hs", "name": "Hotstar"},
        ]

        NETMIRROR_HEADERS = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0 /OS.GatuNewTV v1.0",
            "x-requested-with": "NetmirrorNewTV v1.0",
        }

        api_base = FALLBACK_API
        try:
            async with httpx.AsyncClient(timeout=10) as cfg_client:
                cfg_resp = await cfg_client.get(CONFIG_URL)
                cfg_data = cfg_resp.json()
                api_base = cfg_data.get("nfmirror", FALLBACK_API)
        except Exception:
            pass

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

        async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:
            async def fetch_service(service: dict):
                service_results = []
                service_errors = []
                try:
                    svc_code = service["code"]
                    svc_name = service["name"]
                    headers = {**NETMIRROR_HEADERS, "ott": svc_code}

                    search_url = f"{api_base}/search.php?s={title}"
                    search_resp = await client.get(search_url, headers=headers)

                    if search_resp.status_code != 200:
                        return service_results, [f"{svc_name}: Search HTTP {search_resp.status_code}"]

                    try:
                        search_data = search_resp.json()
                    except Exception:
                        return service_results, [f"{svc_name}: Search returned non-JSON"]

                    search_results = search_data.get("searchResult", [])
                    title_lower = title.lower().strip()
                    exact_matches = []
                    starts_matches = []
                    contains_matches = []
                    for item in search_results:
                        item_title = item.get("t", "").strip().lower()
                        if item_title == title_lower:
                            exact_matches.append(item)
                        elif item_title.startswith(title_lower) or title_lower.startswith(item_title):
                            starts_matches.append(item)
                        elif title_lower in item_title or item_title in title_lower:
                            contains_matches.append(item)

                    all_matches = exact_matches + starts_matches + contains_matches

                    if not all_matches:
                        return service_results, [f"{svc_name}: No match found"]

                    tmdb_year = info.get("year", "")
                    expected_type = "t" if media_type == "tv" else "m"

                    scored_matches = []
                    for match_item in all_matches[:6]:
                        net_id = match_item.get("id")
                        if not net_id:
                            continue
                        try:
                            post_resp = await client.get(f"{api_base}/post.php?id={net_id}", headers=headers)
                            if post_resp.status_code != 200:
                                continue
                            post_data = post_resp.json()
                        except Exception:
                            continue

                        score = 0
                        nm_type = post_data.get("type", "")
                        nm_year = post_data.get("year", "")
                        nm_rating = 0

                        for detail in post_data.get("moredetails", []):
                            if detail.get("k") == "IMDB Rating":
                                try:
                                    nm_rating = float(detail.get("v", "0").replace("/10", ""))
                                except Exception:
                                    nm_rating = 0
                                break

                        if nm_type == expected_type:
                            score += 50

                        try:
                            if tmdb_year and nm_year:
                                year_diff = abs(int(tmdb_year) - int(nm_year))
                                if year_diff == 0:
                                    score += 30
                                elif year_diff == 1:
                                    score += 20
                                elif year_diff <= 3:
                                    score += 10
                                elif year_diff <= 5:
                                    score += 5
                        except Exception:
                            pass

                        score += nm_rating

                        scored_matches.append({
                            "match": match_item,
                            "post_data": post_data,
                            "score": score,
                        })

                    scored_matches.sort(key=lambda x: x["score"], reverse=True)

                    final_id = None
                    if media_type == "tv":
                        s = season or 1
                        e = episode or 1

                        for scored in scored_matches:
                            post_data = scored["post_data"]

                            seasons = post_data.get("season", [])
                            if not seasons:
                                continue

                            target_term = f"Season {s}"
                            season_entry = None
                            for se in seasons:
                                if target_term in se.get("s", "").__str__():
                                    season_entry = se
                                    break

                            if not season_entry or not season_entry.get("id"):
                                continue

                            season_id = season_entry["id"]
                            episode_id = None
                            page = 1
                            while not episode_id and page < 10:
                                ep_resp = await client.get(f"{api_base}/episodes.php?id={season_id}&page={page}", headers=headers)
                                try:
                                    ep_data = ep_resp.json()
                                except Exception:
                                    break
                                episodes = ep_data.get("episodes", [])
                                for ep_item in episodes:
                                    if str(ep_item.get("ep", "")) == str(e):
                                        episode_id = ep_item.get("id")
                                        break
                                if int(ep_data.get("nextPageShow", 0)) != 1:
                                    break
                                page += 1

                            if episode_id:
                                final_id = episode_id
                                break

                        if not final_id:
                            return service_results, [f"{svc_name}: No match with Season {s} Episode {e}"]

                    else:
                        if scored_matches:
                            final_id = scored_matches[0]["match"].get("id")
                        else:
                            final_id = all_matches[0].get("id")

                    player_resp = await client.get(f"{api_base}/player.php?id={final_id}", headers=headers)
                    if player_resp.status_code != 200:
                        return service_results, [f"{svc_name}: Player HTTP {player_resp.status_code}"]

                    try:
                        player_data = player_resp.json()
                    except Exception:
                        return service_results, [f"{svc_name}: Player returned non-JSON"]

                    video_link = player_data.get("video_link", "")
                    if not video_link:
                        return service_results, [f"{svc_name}: No video link"]

                    if ".m3u8" in video_link:
                        try:
                            verify_resp = await client.get(video_link, headers=headers)
                            if "#EXTM3U" not in verify_resp.text:
                                return service_results, [f"{svc_name}: Master playlist unreachable"]
                        except Exception:
                            pass

                    s_type = "m3u8" if ".m3u8" in video_link else ("direct" if ".mp4" in video_link or ".mkv" in video_link else "m3u8")
                    quality = "Auto"
                    q_match = re.search(r'(\d{3,4})p', video_link)
                    if q_match:
                        quality = q_match.group(1) + "p"

                    lang = detect_language(svc_name + " " + video_link)

                    service_results.append({
                        "source": f"NetMirror/{svc_name}",
                        "title": f"{svc_name} Stream",
                        "quality": quality,
                        "language": lang,
                        "url": video_link,
                        "type": s_type,
                        "headers": {
                            "Referer": player_data.get("referer", ""),
                            "User-Agent": NETMIRROR_HEADERS["user-agent"],
                        },
                    })

                except Exception as ex:
                    service_errors.append(f"{service['name']}: {str(ex)}")

                return service_results, service_errors

            tasks = [fetch_service(svc) for svc in OTT_SERVICES]
            task_results = await asyncio.gather(*tasks, return_exceptions=True)

            for result in task_results:
                if isinstance(result, Exception):
                    errors.append(f"NetMirror: {str(result)}")
                else:
                    r, e = result
                    results.extend(r)
                    errors.extend(e)

            if not results:
                errors.append("NetMirror: No streams found")

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

    return results, errors


# ===== AllMovieLand Scraper (Hindi/Tamil/Multi via allmovieland.one) - KEEP AS-IS =====

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

    try:
        UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"

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

        async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers={"User-Agent": UA}, http2=False) as client:

            search_resp = await client.get(
                "https://allmovieland.one/index.php",
                params={"story": title, "do": "search", "subaction": "search"}
            )
            if search_resp.status_code != 200:
                errors.append(f"AllMovieLand: Search HTTP {search_resp.status_code}")
                return results, errors

            search_html = search_resp.text
            articles = re.findall(r'<article[^>]*>(.*?)</article>', search_html, re.DOTALL)

            if not articles:
                errors.append("AllMovieLand: No search results")
                return results, errors

            movie_url = None
            title_lower = title.lower()
            for article in articles:
                link_m = re.search(r'href="([^"]+)"', article)
                h3_m = re.search(r'<h3[^>]*>(.*?)</h3>', article)
                if link_m and h3_m:
                    item_title = h3_m.group(1).strip().lower()
                    if item_title == title_lower or title_lower in item_title:
                        movie_url = link_m.group(1)
                        break

            if not movie_url:
                for article in articles:
                    link_m = re.search(r'href="([^"]+)"', article)
                    if link_m:
                        movie_url = link_m.group(1)
                        break

            if not movie_url:
                errors.append("AllMovieLand: Could not find movie URL")
                return results, errors

            movie_resp = await client.get(movie_url, headers={"Referer": "https://allmovieland.one/"})
            movie_html = movie_resp.text

            domain_match = re.search(r"AwsIndStreamDomain\s*=\s*['\"]([^'\"]+)['\"]", movie_html)
            player_domain = domain_match.group(1).rstrip("/") if domain_match else None

            id_match = re.search(r"src:\s*['\"]([^'\"]+)['\"]", movie_html)
            media_id = id_match.group(1) if id_match else None

            if not player_domain or not media_id:
                errors.append(f"AllMovieLand: No player info (domain={player_domain}, id={media_id})")
                return results, errors

            embed_url = f"{player_domain}/play/{media_id}"
            embed_resp = await client.get(embed_url, headers={"Referer": movie_url})
            embed_html = embed_resp.text

            p3_m = re.search(r'let\s+p3\s*=\s*(\{.*?\})\s*;', embed_html)
            if not p3_m:
                p3_m = re.search(r'p3\s*=\s*(\{[^;]+\})\s*;', embed_html)
            if not p3_m:
                p3_m = re.search(r'(\{"file".*?"key".*?\})', embed_html)

            if not p3_m:
                errors.append("AllMovieLand: Could not find player data in embed")
                return results, errors

            try:
                p3 = json.loads(p3_m.group(1))
            except json.JSONDecodeError:
                errors.append(f"AllMovieLand: Invalid p3 JSON: {p3_m.group(1)[:80]}")
                return results, errors

            file_url = p3.get("file", "").replace("\\/", "/")
            csrf_key = p3.get("key", "")

            if not file_url or not csrf_key:
                errors.append("AllMovieLand: Missing file URL or CSRF key in p3")
                return results, errors

            file_list = None
            post_headers = {
                "X-CSRF-TOKEN": csrf_key,
                "Referer": embed_url,
                "Origin": player_domain,
                "Accept": "application/json, text/plain, */*",
                "User-Agent": UA,
            }

            for attempt in range(7):
                try:
                    async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client:
                        resp = await fresh_client.post(file_url, headers=post_headers)
                        text = resp.text.strip()
                        if text != "7" and text.startswith("["):
                            file_list = json.loads(text.replace(",]", "]"))
                            break
                except Exception:
                    pass

            if not file_list:
                errors.append("AllMovieLand: Could not get file list (7 attempts)")
                return results, errors

            target_files = []
            if media_type == "movie":
                target_files = [f for f in file_list if f.get("file")]
            else:
                s = season or 1
                e = episode or 1
                for item in file_list:
                    item_title = item.get("title", "")
                    s_m = re.search(r'Season\s*(\d+)', item_title, re.I)
                    if s_m and int(s_m.group(1)) == s:
                        if item.get("folder"):
                            for ep_item in item["folder"]:
                                ep_title = ep_item.get("title", "")
                                e_m = re.search(r'Episode\s*(\d+)', ep_title, re.I)
                                if e_m and int(e_m.group(1)) == e:
                                    if ep_item.get("folder"):
                                        target_files = [f for f in ep_item["folder"] if f.get("file")]
                                        break
                        break

            if not target_files:
                target_files = [f for f in file_list if f.get("file")][:3]

            for file_obj in target_files:
                file_path = file_obj.get("file", "").lstrip("~")
                stream_title = file_obj.get("title", "Stream")
                if not file_path:
                    continue

                playlist_url = f"{player_domain}/playlist/{file_path}.txt"

                m3u8_url = None
                for attempt in range(7):
                    try:
                        async with httpx.AsyncClient(timeout=10, follow_redirects=True, http2=False) as fresh_client:
                            resp = await fresh_client.post(playlist_url, headers=post_headers)
                            text = resp.text.strip()
                            if text != "7" and text.startswith("http"):
                                m3u8_url = text
                                break
                    except Exception:
                        pass

                if m3u8_url:
                    lang = detect_language(stream_title)
                    quality = "Auto"
                    q_m = re.search(r'(\d{3,4})p', stream_title)
                    if q_m:
                        quality = q_m.group(1) + "p"

                    results.append({
                        "source": "AllMovieLand",
                        "title": f"AllMovieLand - {stream_title}",
                        "quality": quality,
                        "language": lang,
                        "url": m3u8_url,
                        "type": "m3u8",
                        "headers": {
                            "Referer": f"{player_domain}/",
                            "Origin": player_domain,
                            "User-Agent": UA,
                        },
                    })

            if not results:
                errors.append("AllMovieLand: Could not resolve any m3u8 URLs")

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

    return results, errors


# ===== VidLink Scraper (vidlink.pro with encrypted ID) - REWRITTEN =====

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

    try:
        ENCRYPT_API = "https://enc-dec.app/api/enc-vidlink"
        VIDLINK_BASE = "https://vidlink.pro"
        VIDLINK_TMDB_KEY = "68e094699525b18a70bab2f86b1fa706"

        VIDLINK_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",
            "Connection": "keep-alive",
            "Referer": "https://vidlink.pro/",
            "Origin": "https://vidlink.pro",
            "Accept": "application/json",
        }

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:
            # Step 1: Get encrypted ID
            enc_resp = await client.get(
                ENCRYPT_API,
                params={"text": str(tmdb_id)},
                headers={"Accept": "application/json"}
            )
            if enc_resp.status_code != 200:
                errors.append(f"VidLink: Encrypt API failed HTTP {enc_resp.status_code}")
                return results, errors

            enc_data = enc_resp.json()
            encrypted_id = enc_data.get("result") or enc_data.get("encrypted") or enc_data.get("data", "")
            if not encrypted_id:
                errors.append("VidLink: No encrypted ID returned")
                return results, errors

            # Step 2: Get stream URL
            if media_type == "movie":
                stream_api = f"{VIDLINK_BASE}/api/b/movie/{encrypted_id}"
            else:
                s = season or 1
                e = episode or 1
                stream_api = f"{VIDLINK_BASE}/api/b/tv/{encrypted_id}/{s}/{e}"

            stream_resp = await client.get(stream_api, headers=VIDLINK_HEADERS)

            if stream_resp.status_code != 200:
                errors.append(f"VidLink: Stream API failed HTTP {stream_resp.status_code}")
                return results, errors

            stream_data = stream_resp.json()
            playlist_url = None

            # Extract playlist URL from response - primary: stream.playlist
            if stream_data.get("stream"):
                playlist_url = stream_data["stream"].get("playlist") or stream_data["stream"].get("url", "")

            if not playlist_url:
                for key in ["playlist", "url", "file", "source"]:
                    if stream_data.get(key):
                        playlist_url = stream_data[key]
                        break

            if not playlist_url:
                errors.append("VidLink: No playlist URL in response")
                return results, errors

            # Step 3: Parse M3U8 master playlist for quality variants
            if playlist_url.endswith(".m3u8") or "m3u8" in playlist_url:
                try:
                    m3u8_resp = await client.get(playlist_url, headers={
                        "Referer": "https://vidlink.pro/",
                        "Origin": "https://vidlink.pro",
                    })

                    if "#EXT-X-STREAM-INF" in m3u8_resp.text:
                        base_url = playlist_url.rsplit("/", 1)[0]
                        variants = parse_m3u8_quality(m3u8_resp.text, base_url)

                        for variant in variants:
                            quality = detect_quality_from_label(variant["label"])
                            if quality == "Auto":
                                res_match = re.search(r'(\d+)x(\d+)', variant["quality"])
                                if res_match:
                                    height = int(res_match.group(2))
                                    if height >= 2160:
                                        quality = "4K"
                                    elif height >= 1440:
                                        quality = "1440p"
                                    elif height >= 1080:
                                        quality = "1080p FHD"
                                    elif height >= 720:
                                        quality = "720p HD"
                                    elif height >= 480:
                                        quality = "480p SD"

                            results.append({
                                "source": "VidLink",
                                "title": variant["label"],
                                "quality": quality,
                                "language": "English",
                                "url": variant["url"],
                                "type": "m3u8",
                                "headers": {
                                    "Referer": "https://vidlink.pro/",
                                    "Origin": "https://vidlink.pro",
                                },
                            })
                    else:
                        results.append({
                            "source": "VidLink",
                            "title": "VidLink Stream",
                            "quality": "Auto",
                            "language": "English",
                            "url": playlist_url,
                            "type": "m3u8",
                            "headers": {
                                "Referer": "https://vidlink.pro/",
                                "Origin": "https://vidlink.pro",
                            },
                        })
                except Exception:
                    results.append({
                        "source": "VidLink",
                        "title": "VidLink Stream",
                        "quality": "Auto",
                        "language": "English",
                        "url": playlist_url,
                        "type": "m3u8",
                        "headers": {
                            "Referer": "https://vidlink.pro/",
                            "Origin": "https://vidlink.pro",
                        },
                    })
            else:
                s_type = "direct" if ".mp4" in playlist_url else "m3u8"
                results.append({
                    "source": "VidLink",
                    "title": "VidLink Stream",
                    "quality": "Auto",
                    "language": "English",
                    "url": playlist_url,
                    "type": s_type,
                    "headers": {
                        "Referer": "https://vidlink.pro/",
                        "Origin": "https://vidlink.pro",
                    },
                })

            if not results:
                errors.append("VidLink: No streams found")

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

    return results, errors


# ===== VidSrc Scraper (cloudnestra approach) - REWRITTEN =====

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

    try:
        VIDSRC_TMDB_KEY = "439c478a771f35c05022f9feabcca01c"
        DECRYPT_API = "https://enc-dec.app/api/dec-cloudnestra"

        # Get IMDB ID using the VidSrc-specific TMDB key
        info = await get_tmdb_info_with_key(tmdb_id, media_type, VIDSRC_TMDB_KEY)
        imdb_id = info.get("imdb_id")
        if not imdb_id:
            info = await get_tmdb_info(tmdb_id, media_type)
            imdb_id = info.get("imdb_id")
        if not imdb_id:
            errors.append("VidSrc: Could not get IMDB ID from TMDB")
            return results, errors

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:

            # Step 1: Fetch embed page from vsrc.su
            if media_type == "tv":
                s = season or 1
                e = episode or 1
                embed_url = f"https://vsrc.su/embed/tv?imdb={imdb_id}&season={s}&episode={e}"
            else:
                embed_url = f"https://vsrc.su/embed/movie?imdb={imdb_id}"

            embed_resp = await client.get(embed_url)
            embed_html = embed_resp.text

            # Step 2: Parse iframe src from HTML
            iframe_src = None
            iframe_m = re.search(r'<iframe[^>]+src="([^"]+)"', embed_html)
            if iframe_m:
                iframe_src = iframe_m.group(1)
                if iframe_src.startswith("//"):
                    iframe_src = f"https:{iframe_src}"
                elif iframe_src.startswith("/"):
                    iframe_src = f"https://vsrc.su{iframe_src}"

            if not iframe_src:
                iframe_m = re.search(r'src=["\x27]([^"\x27]+)["\x27]', embed_html)
                if iframe_m:
                    iframe_src = iframe_m.group(1)
                    if iframe_src.startswith("//"):
                        iframe_src = f"https:{iframe_src}"

            if not iframe_src:
                errors.append("VidSrc: No iframe found in embed page")
                return results, errors

            # Step 3: Fetch iframe page, extract JS src pattern
            iframe_resp = await client.get(iframe_src, headers={"Referer": "https://vsrc.su/"})
            iframe_html = iframe_resp.text

            # Look for src: "..." pattern in JS
            js_src = None
            src_match = re.search(r'src:\s*["\x27](/[^"\x27]+)["\x27]', iframe_html)
            if not src_match:
                src_match = re.search(r'file:\s*["\x27](https?://[^"\x27]+\.m3u8[^"\x27]*)["\x27]', iframe_html)

            if src_match:
                js_src = src_match.group(1)
                # If it's a direct m3u8 URL, return it
                if js_src.startswith("http") and ".m3u8" in js_src:
                    quality = "Auto"
                    if "2160" in js_src or "4k" in js_src.lower():
                        quality = "4K"
                    elif "1080" in js_src:
                        quality = "1080p"
                    elif "720" in js_src:
                        quality = "720p"

                    results.append({
                        "source": "VidSrc",
                        "title": "VidSrc Stream",
                        "quality": quality,
                        "language": "English",
                        "url": js_src,
                        "type": "m3u8",
                        "headers": {
                            "Referer": "https://cloudnestra.com/",
                        },
                    })
                    return results, errors

            # Step 4: Fetch cloudnestra page with the src path
            if js_src and not js_src.startswith("http"):
                cloudnestra_url = f"https://cloudnestra.com{js_src}"
            elif js_src:
                cloudnestra_url = js_src
            else:
                cloud_m = re.search(r'(https?://cloudnestra\.com[^\s"\'<>]+)', iframe_html)
                if cloud_m:
                    cloudnestra_url = cloud_m.group(1)
                else:
                    errors.append("VidSrc: Could not find cloudnestra source path")
                    return results, errors

            cloud_resp = await client.get(cloudnestra_url, headers={
                "Referer": "https://vsrc.su/",
                "Origin": "https://vsrc.su",
            })

            if cloud_resp.status_code == 403 or "Cloudflare" in cloud_resp.text:
                errors.append("VidSrc: Cloudflare blocked on cloudnestra")
                return results, errors

            cloud_html = cloud_resp.text

            # Step 5: Parse HTML for hidden div
            div_id = None
            div_text = None
            hidden_pattern = r'<div\s+id="([^"]+)"[^>]*style=["\x27][^"\x27]*display\s*:\s*none[^"\x27]*["\x27][^>]*>([\s\S]*?)</div>'
            hidden_m = re.search(hidden_pattern, cloud_html)
            if hidden_m:
                div_id = hidden_m.group(1)
                div_text = hidden_m.group(2).strip()

            if not div_text:
                hidden_pattern2 = r'<div\s+id="([^"]+)"[^>]*style=["\x27]display\s*:\s*none;?["\x27][^>]*>([a-zA-Z0-9:/.,{}_=+ \-]+)</div>'
                hidden_m2 = re.search(hidden_pattern2, cloud_html)
                if hidden_m2:
                    div_id = hidden_m2.group(1)
                    div_text = hidden_m2.group(2).strip()

            if not div_text or not div_id:
                errors.append("VidSrc: Could not find hidden div for decryption")
                return results, errors

            # Step 6: Decrypt via enc-dec.app
            dec_resp = await client.post(
                DECRYPT_API,
                json={"text": div_text, "div_id": div_id},
                headers={"Content-Type": "application/json"},
            )

            if dec_resp.status_code != 200:
                errors.append(f"VidSrc: Decrypt API failed HTTP {dec_resp.status_code}")
                return results, errors

            dec_data = dec_resp.json()
            stream_urls = dec_data.get("result", [])

            if isinstance(stream_urls, str):
                stream_urls = [stream_urls]

            if not stream_urls:
                errors.append("VidSrc: No streams from decryption")
                return results, errors

            # Step 7: Parse decrypted m3u8 URLs and detect quality
            for idx, stream_url in enumerate(stream_urls):
                if not stream_url or not isinstance(stream_url, str):
                    continue

                quality = "Auto"
                url_lower = stream_url.lower()
                if "2160" in url_lower or "4k" in url_lower:
                    quality = "4K"
                elif "1440" in url_lower:
                    quality = "1440p"
                elif "1080" in url_lower:
                    quality = "1080p"
                elif "720" in url_lower:
                    quality = "720p"
                elif "480" in url_lower:
                    quality = "480p"
                else:
                    # Try fetching the m3u8 to detect max quality
                    try:
                        m3u8_resp = await client.get(stream_url, headers={
                            "Referer": "https://cloudnestra.com/",
                        })
                        m3u8_content = m3u8_resp.text
                        if "#EXT-X-STREAM-INF" in m3u8_content:
                            resolutions = re.findall(r'RESOLUTION=\d+x(\d+)', m3u8_content)
                            if resolutions:
                                max_h = max(int(r) for r in resolutions)
                                if max_h >= 2160:
                                    quality = "4K"
                                elif max_h >= 1440:
                                    quality = "1440p"
                                elif max_h >= 1080:
                                    quality = "1080p"
                                elif max_h >= 720:
                                    quality = "720p"
                                elif max_h >= 480:
                                    quality = "480p"
                    except Exception:
                        pass

                results.append({
                    "source": f"VidSrc{idx + 1 if len(stream_urls) > 1 else ''}",
                    "title": f"VidSrc Server {idx + 1}" if len(stream_urls) > 1 else "VidSrc Stream",
                    "quality": quality,
                    "language": "English",
                    "url": stream_url,
                    "type": "m3u8",
                    "headers": {
                        "Referer": "https://cloudnestra.com/",
                        "Origin": "https://cloudnestra.com",
                    },
                })

            if not results:
                errors.append("VidSrc: No streams found")

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

    return results, errors


# ===== M4UHD Scraper (m4uhd.vip with CryptoJS-compatible AES-CBC) - KEEP AS-IS =====

async def scrape_m4uhd(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 pad as crypto_pad, unpad

        M4UHD_BASE = "https://m4uhd.vip"
        FILE_ID_SECRET = "jcLycoRJT6OWjoWspgLMOZwS3aSS0lEn"
        USER_ID_SECRET = "PZZ3J3LDbLT0GY7qSA5wW5vchqgpO36O"
        ENCRYPT_PAYLOAD_SECRET = "vlVbUQhkOhoSfyteyzGeeDzU0BHoeTyZ"
        DECRYPT_RESPONSE_SECRET = "oJwmvmVBajMaRCTklxbfjavpQO7SZpsL"
        HMAC_KEY = "KRWN3AdgmxEMcd2vLN1ju9qKe8Feco5h"
        PLAY_API = "https://api-play-270325.ppzj-youtube.cfd/api/tp1rd/playiframe"

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

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:
            # Step 1: Search for the movie
            search_resp = await client.get(f"{M4UHD_BASE}/search/{title.replace(' ', '-')}.html")
            if search_resp.status_code != 200:
                errors.append(f"M4UHD: Search failed HTTP {search_resp.status_code}")
                return results, errors

            search_html = search_resp.text

            movie_blocks = re.findall(
                r'<div[^>]*class="[^"]*item[^"]*"[^>]*>.*?<a[^>]*href="([^"]+)"[^>]*>.*?(?:<img[^>]*alt="([^"]*)")?',
                search_html, re.DOTALL
            )

            if not movie_blocks:
                movie_links = re.findall(r'href="(/movie/\d+/[^"]+\.html)"', search_html)
                movie_titles = re.findall(r'alt="([^"]+)"', search_html)
                movie_blocks = [(link, title) for link, title in zip(movie_links, movie_titles)]

            if not movie_blocks:
                errors.append("M4UHD: No search results found")
                return results, errors

            movie_page_url = None
            title_lower = title.lower()
            for link, mtitle in movie_blocks:
                if mtitle and (title_lower in mtitle.lower() or mtitle.lower() in title_lower):
                    movie_page_url = link if link.startswith("http") else f"{M4UHD_BASE}{link}"
                    break

            if not movie_page_url and movie_blocks:
                link = movie_blocks[0][0]
                movie_page_url = link if link.startswith("http") else f"{M4UHD_BASE}{link}"

            if not movie_page_url:
                errors.append("M4UHD: Could not find movie page")
                return results, errors

            movie_resp = await client.get(movie_page_url)
            if movie_resp.status_code != 200:
                errors.append(f"M4UHD: Movie page HTTP {movie_resp.status_code}")
                return results, errors

            movie_html = movie_resp.text

            csrf_match = re.search(r'name="csrf[_-]token"\s+(?:value|content)="([^"]+)"', movie_html, re.I)
            if not csrf_match:
                csrf_match = re.search(r'(?:value|content)="([^"]+)"[^>]*name="csrf[_-]token"', movie_html, re.I)
            if not csrf_match:
                csrf_match = re.search(r'csrf[_-]?token["\s:=]+["\']?([a-fA-F0-9]+)', movie_html, re.I)
            csrf_token = csrf_match.group(1) if csrf_match else ""

            servers = re.findall(r'data-id="(\d+)"[^>]*>([^<]+)', movie_html)
            if not servers:
                servers = re.findall(r'class="[^"]*server[^"]*"[^>]*data-id="(\d+)"[^>]*>([^<]*)', movie_html)
            if not servers:
                servers = re.findall(r'href="([^"]*ajax[^"]*)"[^>]*>([^<]+)', movie_html)

            if not servers:
                errors.append("M4UHD: No servers found on movie page")
                return results, errors

            for server_id, server_name in servers[:3]:
                try:
                    ajax_data = {
                        "id": server_id,
                        "csrf_token": csrf_token,
                    }
                    if media_type == "tv":
                        s = season or 1
                        e = episode or 1
                        ajax_data["season"] = str(s)
                        ajax_data["episode"] = str(e)

                    ajax_resp = await client.post(
                        f"{M4UHD_BASE}/ajax",
                        data=ajax_data,
                        headers={
                            "X-Requested-With": "XMLHttpRequest",
                            "Content-Type": "application/x-www-form-urlencoded",
                            "Referer": movie_page_url,
                        }
                    )

                    if ajax_resp.status_code != 200:
                        continue

                    ajax_result = ajax_resp.json()
                    embed_url = ajax_result.get("url") or ajax_result.get("link") or ajax_result.get("data", "")
                    if not embed_url:
                        embed_m = re.search(r'(https?://[^"\'<>\s]+)', ajax_resp.text)
                        embed_url = embed_m.group(1) if embed_m else ""

                    if not embed_url:
                        continue

                    if not embed_url.startswith("http"):
                        embed_url = f"{M4UHD_BASE}{embed_url}"

                    embed_resp = await client.get(embed_url, headers={"Referer": movie_page_url})
                    embed_html = embed_resp.text

                    idfile_match = re.search(r'idfile_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html)
                    iduser_match = re.search(r'idUser_enc["\s:=]+["\']?([a-zA-Z0-9+/=]+)', embed_html)

                    idfile_enc = idfile_match.group(1) if idfile_match else ""
                    iduser_enc = iduser_match.group(1) if iduser_match else ""

                    if not idfile_enc:
                        errors.append(f"M4UHD/{server_name}: No encrypted file ID found")
                        continue

                    def m4uhd_decrypt(ciphertext_b64: str, secret: str) -> str:
                        raw = base64.b64decode(ciphertext_b64)
                        if raw[:8] == b"Salted__":
                            salt = raw[8:16]
                            ct = raw[16:]
                        else:
                            salt = b""
                            ct = raw
                        key, iv = evp_bytes_to_key(secret.encode(), salt)
                        cipher = AES.new(key, AES.MODE_CBC, iv)
                        return unpad(cipher.decrypt(ct), AES.block_size).decode("utf-8", errors="ignore")

                    def m4uhd_encrypt(plaintext: str, secret: str) -> str:
                        import os
                        salt = os.urandom(8)
                        key, iv = evp_bytes_to_key(secret.encode(), salt)
                        cipher = AES.new(key, AES.MODE_CBC, iv)
                        ct = cipher.encrypt(crypto_pad(plaintext.encode(), AES.block_size))
                        return base64.b64encode(b"Salted__" + salt + ct).decode()

                    idfile = m4uhd_decrypt(idfile_enc, FILE_ID_SECRET)
                    iduser = m4uhd_decrypt(iduser_enc, USER_ID_SECRET) if iduser_enc else ""

                    payload_data = {
                        "idfile": idfile,
                        "idUser": iduser,
                    }
                    payload_json = json.dumps(payload_data)
                    encrypted_payload = m4uhd_encrypt(payload_json, ENCRYPT_PAYLOAD_SECRET)

                    hmac_val = hashlib.md5((encrypted_payload + HMAC_KEY).encode()).hexdigest()

                    play_resp = await client.post(
                        PLAY_API,
                        json={"data": encrypted_payload, "hmac": hmac_val},
                        headers={
                            "Content-Type": "application/json",
                            "Referer": embed_url,
                            "Origin": M4UHD_BASE,
                        }
                    )

                    if play_resp.status_code != 200:
                        continue

                    play_data = play_resp.json()
                    encrypted_response = play_data.get("data") or play_data.get("encrypted") or play_data.get("url", "")

                    if not encrypted_response:
                        continue

                    try:
                        decrypted_response = m4uhd_decrypt(encrypted_response, DECRYPT_RESPONSE_SECRET)

                        try:
                            dec_json = json.loads(decrypted_response)
                            video_url = dec_json.get("url") or dec_json.get("source") or dec_json.get("file") or dec_json.get("link", "")
                        except json.JSONDecodeError:
                            url_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', decrypted_response)
                            if not url_match:
                                url_match = re.search(r'https?://[^\s"\'<>]+', decrypted_response)
                            video_url = url_match.group(0) if url_match else ""

                        if not video_url or not video_url.startswith("http"):
                            continue

                        s_type = "m3u8" if ".m3u8" in video_url else "direct"
                        quality = "Auto"
                        q_match = re.search(r'(\d{3,4})p', video_url)
                        if q_match:
                            quality = q_match.group(1) + "p"

                        lang = detect_language(server_name)

                        results.append({
                            "source": f"M4UHD/{server_name.strip()}",
                            "title": f"M4UHD - {server_name.strip()}",
                            "quality": quality,
                            "language": lang,
                            "url": video_url,
                            "type": s_type,
                        })

                    except Exception as dec_err:
                        errors.append(f"M4UHD/{server_name}: Response decrypt failed - {str(dec_err)}")
                        continue

                except Exception as srv_err:
                    errors.append(f"M4UHD/{server_name}: {str(srv_err)}")
                    continue

            if not results:
                errors.append("M4UHD: No streams found")

    except ImportError:
        errors.append("M4UHD: pycryptodome not installed")
    except Exception as e:
        errors.append(f"M4UHD: {str(e)}")

    return results, errors


# ===== VidFast Scraper (vidfast.pro with encrypted ID) - NEW =====

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

    try:
        ENCRYPT_API = "https://enc-dec.app/api/enc-vidfast"
        VIDFAST_BASE = "https://vidfast.pro"

        VIDFAST_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",
            "Referer": "https://vidfast.pro/",
            "X-Requested-With": "XMLHttpRequest",
            "Accept": "application/json",
        }

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:
            # Step 1: Get encrypted ID
            enc_resp = await client.get(
                ENCRYPT_API,
                params={"text": str(tmdb_id)},
                headers={"Accept": "application/json"}
            )
            if enc_resp.status_code != 200:
                errors.append(f"VidFast: Encrypt API failed HTTP {enc_resp.status_code}")
                return results, errors

            enc_data = enc_resp.json()
            encrypted_id = enc_data.get("result") or enc_data.get("encrypted") or enc_data.get("data", "")
            if not encrypted_id:
                errors.append("VidFast: No encrypted ID returned")
                return results, errors

            # Step 2: Get stream URL
            if media_type == "movie":
                stream_api = f"{VIDFAST_BASE}/api/movie/{encrypted_id}"
            else:
                s = season or 1
                e = episode or 1
                stream_api = f"{VIDFAST_BASE}/api/tv/{encrypted_id}/{s}/{e}"

            stream_resp = await client.get(stream_api, headers=VIDFAST_HEADERS)

            if stream_resp.status_code != 200:
                errors.append(f"VidFast: Stream API failed HTTP {stream_resp.status_code}")
                return results, errors

            stream_data = stream_resp.json()

            # Extract stream data - check various response structures
            playlist_url = None
            streams = []

            # Try stream.playlist pattern (like VidLink)
            if stream_data.get("stream"):
                playlist_url = stream_data["stream"].get("playlist") or stream_data["stream"].get("url", "")

            # Try direct sources array
            if not playlist_url and stream_data.get("sources"):
                for source in stream_data["sources"]:
                    if isinstance(source, dict) and source.get("url"):
                        streams.append(source)
                    elif isinstance(source, str) and source.startswith("http"):
                        streams.append({"url": source})

            # Try direct URL fields
            if not playlist_url and not streams:
                for key in ["url", "file", "source", "playlist", "link"]:
                    if stream_data.get(key):
                        val = stream_data[key]
                        if isinstance(val, str):
                            playlist_url = val
                            break
                        elif isinstance(val, dict) and val.get("url"):
                            playlist_url = val["url"]
                            break

            # Process direct streams
            if streams:
                for source in streams:
                    url = source.get("url", "")
                    if not url:
                        continue
                    quality = source.get("quality", "Auto")
                    name = source.get("name", "VidFast Stream")

                    if quality == "Auto":
                        quality = detect_quality_from_label(name + " " + url)

                    s_type = "m3u8" if ".m3u8" in url else "direct"

                    results.append({
                        "source": "VidFast",
                        "title": name,
                        "quality": quality,
                        "language": "English",
                        "url": url,
                        "type": s_type,
                        "headers": {
                            "Referer": "https://vidfast.pro/",
                            "Origin": "https://vidfast.pro",
                        },
                    })

            elif playlist_url:
                if ".m3u8" in playlist_url:
                    try:
                        m3u8_resp = await client.get(playlist_url, headers={
                            "Referer": "https://vidfast.pro/",
                            "Origin": "https://vidfast.pro",
                        })

                        if "#EXT-X-STREAM-INF" in m3u8_resp.text:
                            base_url = playlist_url.rsplit("/", 1)[0]
                            variants = parse_m3u8_quality(m3u8_resp.text, base_url)

                            for variant in variants:
                                quality = detect_quality_from_label(variant["label"])
                                if quality == "Auto":
                                    res_match = re.search(r'(\d+)x(\d+)', variant["quality"])
                                    if res_match:
                                        height = int(res_match.group(2))
                                        if height >= 2160:
                                            quality = "4K"
                                        elif height >= 1080:
                                            quality = "1080p FHD"
                                        elif height >= 720:
                                            quality = "720p HD"
                                        elif height >= 480:
                                            quality = "480p SD"

                                results.append({
                                    "source": "VidFast",
                                    "title": variant["label"],
                                    "quality": quality,
                                    "language": "English",
                                    "url": variant["url"],
                                    "type": "m3u8",
                                    "headers": {
                                        "Referer": "https://vidfast.pro/",
                                        "Origin": "https://vidfast.pro",
                                    },
                                })
                        else:
                            results.append({
                                "source": "VidFast",
                                "title": "VidFast Stream",
                                "quality": "Auto",
                                "language": "English",
                                "url": playlist_url,
                                "type": "m3u8",
                                "headers": {
                                    "Referer": "https://vidfast.pro/",
                                    "Origin": "https://vidfast.pro",
                                },
                            })
                    except Exception:
                        results.append({
                            "source": "VidFast",
                            "title": "VidFast Stream",
                            "quality": "Auto",
                            "language": "English",
                            "url": playlist_url,
                            "type": "m3u8",
                            "headers": {
                                "Referer": "https://vidfast.pro/",
                                "Origin": "https://vidfast.pro",
                            },
                        })
                else:
                    s_type = "direct" if ".mp4" in playlist_url else "m3u8"
                    results.append({
                        "source": "VidFast",
                        "title": "VidFast Stream",
                        "quality": "Auto",
                        "language": "English",
                        "url": playlist_url,
                        "type": s_type,
                        "headers": {
                            "Referer": "https://vidfast.pro/",
                            "Origin": "https://vidfast.pro",
                        },
                    })

            if not results:
                errors.append("VidFast: No streams found")

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

    return results, errors


# ===== ShowBox Scraper (nuvioapp.space API) - NEW =====

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

    try:
        SHOWBOX_API = "https://febapi.nuvioapp.space/api/media"
        SHOWBOX_TMDB_KEY = "439c478a771f35c05022f9feabcca01c"

        SHOWBOX_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",
            "Referer": "https://showbox.6hprojin7o.com/",
        }

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=SHOWBOX_HEADERS) as client:
            # ShowBox requires a uiToken cookie from the app settings
            # Try without token first - some content may be accessible
            ui_token = ""

            if media_type == "movie":
                url = f"{SHOWBOX_API}/movie/{tmdb_id}"
                if ui_token:
                    url += f"?cookie={ui_token}"
            else:
                s = season or 1
                e = episode or 1
                # For TV, need ossGroup from the movie endpoint first
                base_url = f"{SHOWBOX_API}/tv/{tmdb_id}"
                if ui_token:
                    base_url += f"?cookie={ui_token}"

                base_resp = await client.get(base_url)
                oss_group = ""

                if base_resp.status_code == 200:
                    try:
                        base_data = base_resp.json()
                        versions = base_data.get("versions", [])
                        if versions and isinstance(versions, list):
                            first_version = versions[0] if isinstance(versions[0], dict) else {}
                            oss_group = first_version.get("ossGroup", "")
                    except Exception:
                        pass

                url = f"{SHOWBOX_API}/tv/{tmdb_id}/{oss_group}/{s}/{e}"
                if ui_token:
                    url += f"?cookie={ui_token}"

            resp = await client.get(url)

            if resp.status_code == 401:
                errors.append("ShowBox: Requires uiToken cookie (not available server-side)")
                return results, errors

            if resp.status_code != 200:
                errors.append(f"ShowBox: API failed HTTP {resp.status_code}")
                return results, errors

            data = resp.json()

            # Process versions -> sources
            versions = data.get("versions", [])
            if not versions:
                # Try direct sources
                sources = data.get("sources", [])
                for source in sources:
                    if isinstance(source, dict) and source.get("url"):
                        quality = source.get("quality", "Auto")
                        name = source.get("name", "ShowBox Stream")
                        s_url = source["url"]
                        s_type = "m3u8" if ".m3u8" in s_url else "direct"

                        results.append({
                            "source": "ShowBox",
                            "title": name,
                            "quality": quality,
                            "language": "English",
                            "url": s_url,
                            "type": s_type,
                        })

            for version in versions:
                if not isinstance(version, dict):
                    continue

                version_name = version.get("name", "Server")
                sources = version.get("sources", [])

                for source in sources:
                    if not isinstance(source, dict):
                        continue

                    s_url = source.get("url", "")
                    if not s_url:
                        continue

                    quality = source.get("quality", "Auto")
                    name = source.get("name", version_name)

                    if quality == "Auto":
                        quality = detect_quality_from_label(name)

                    s_type = "m3u8" if ".m3u8" in s_url else "direct"
                    lang = detect_language(name)

                    results.append({
                        "source": f"ShowBox/{version_name}",
                        "title": name,
                        "quality": quality,
                        "language": lang,
                        "url": s_url,
                        "type": s_type,
                    })

            if not results:
                errors.append("ShowBox: No streams found")

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

    return results, errors


# ===== GoatAPI Scraper (goatapi workers) - NEW =====

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

    try:
        GOAT_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",
        }

        # For TV shows, use a different endpoint pattern
        if media_type == "tv":
            s = season or 1
            e = episode or 1
            api_url = f"https://goatapi.imreallydagoatt.workers.dev/api/downloader/tv/{tmdb_id}/{s}/{e}"
        else:
            api_url = f"https://goatapi.imreallydagoatt.workers.dev/api/downloader/movie/{tmdb_id}"

        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=GOAT_HEADERS) as client:
            resp = await client.get(api_url)

            if resp.status_code != 200:
                errors.append(f"GoatAPI: API failed HTTP {resp.status_code}")
                return results, errors

            data = resp.json()

            # Process streams array
            streams = data.get("streams", [])
            for stream in streams:
                if not isinstance(stream, dict):
                    continue

                url = stream.get("url", "")
                if not url:
                    continue

                name = stream.get("name", "GoatAPI Stream")
                label = stream.get("label", "")
                quality = "Auto"

                if label:
                    quality = detect_quality_from_label(label)
                if quality == "Auto":
                    quality = detect_quality_from_label(name)
                if quality == "Auto":
                    quality = detect_quality_from_label(url)

                s_type = "m3u8" if ".m3u8" in url else "direct"
                lang = detect_language(name + " " + label)

                results.append({
                    "source": "GoatAPI",
                    "title": label or name,
                    "quality": quality,
                    "language": lang,
                    "url": url,
                    "type": s_type,
                })

            # Process downloads array
            downloads = data.get("downloads", [])
            for dl in downloads:
                if not isinstance(dl, dict):
                    continue

                dl_sources = dl.get("sources", [])
                for source in dl_sources:
                    if not isinstance(source, dict):
                        continue

                    url = source.get("url", "")
                    if not url:
                        continue

                    name = source.get("name", dl.get("name", "GoatAPI Download"))
                    quality = source.get("quality", "Auto")

                    if quality == "Auto":
                        quality = detect_quality_from_label(name + " " + url)

                    s_type = "m3u8" if ".m3u8" in url else "direct"
                    lang = detect_language(name)

                    results.append({
                        "source": "GoatAPI",
                        "title": name,
                        "quality": quality,
                        "language": lang,
                        "url": url,
                        "type": s_type,
                    })

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

            if not results:
                errors.append("GoatAPI: No streams found")

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

    return results, errors


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

SOURCE_MAP = {
    "vidrock": {"name": "VidRock", "fn": lambda tid, mt, s, e: scrape_vidrock(tid, mt, s, e),
                "languages": ["English"], "reliability": "high"},
    "castle": {"name": "Castle", "fn": lambda tid, mt, s, e: scrape_castle(tid, mt, s, e),
               "languages": ["English", "Hindi", "Multi"], "reliability": "medium",
               "note": "hlowb.com API with AES-CBC encryption, channel IndiaA"},
    "moviebox": {"name": "MovieBox", "fn": lambda tid, mt, s, e: scrape_moviebox(tid, mt, s, e),
                 "languages": ["Hindi", "English", "Multi"], "reliability": "high",
                 "note": "themoviebox.org API with detailPath support"},
    "allmovieland": {"name": "AllMovieLand", "fn": lambda tid, mt, s, e: scrape_allmovieland(tid, mt, s, e),
                "languages": ["Hindi", "Tamil", "Telugu", "English", "Multi"], "reliability": "medium"},
    "netmirror": {"name": "NetMirror", "fn": lambda tid, mt, s, e: scrape_netmirror(tid, mt, s, e),
                "languages": ["Hindi", "English", "Multi"], "reliability": "high"},
    "videasy": {"name": "Videasy", "fn": lambda tid, mt, s, e: scrape_videasy(tid, mt, s, e),
                "languages": ["English", "Multi"], "reliability": "medium"},
    "vidsrc": {"name": "VidSrc", "fn": lambda tid, mt, s, e: scrape_vidsrc(tid, mt, s, e),
               "languages": ["English"], "reliability": "medium",
               "note": "vsrc.su + cloudnestra via enc-dec.app decryption"},
    "vidlink": {"name": "VidLink", "fn": lambda tid, mt, s, e: scrape_vidlink(tid, mt, s, e),
                "languages": ["English"], "reliability": "medium",
                "note": "vidlink.pro with encrypted TMDB ID via enc-dec.app"},
    "m4uhd": {"name": "M4UHD", "fn": lambda tid, mt, s, e: scrape_m4uhd(tid, mt, s, e),
              "languages": ["English", "Hindi", "Multi"], "reliability": "medium"},
    "vidfast": {"name": "VidFast", "fn": lambda tid, mt, s, e: scrape_vidfast(tid, mt, s, e),
                "languages": ["English"], "reliability": "medium",
                "note": "vidfast.pro with encrypted TMDB ID via enc-dec.app"},
    "showbox": {"name": "ShowBox", "fn": lambda tid, mt, s, e: scrape_showbox(tid, mt, s, e),
                "languages": ["English", "Hindi", "Multi"], "reliability": "low",
                "note": "Requires uiToken cookie for full access, limited without it"},
    "goatapi": {"name": "GoatAPI", "fn": lambda tid, mt, s, e: scrape_goatapi(tid, mt, s, e),
                "languages": ["English"], "reliability": "medium",
                "note": "TMDB ID only, no IMDB support"},
}

DEFAULT_SOURCES = ["vidrock", "vidlink", "goatapi", "netmirror", "moviebox", "m4uhd", "castle"]


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

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

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

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

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

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

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

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


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

@app.get("/")
async def root():
    return {
        "api": "StreamForge",
        "version": "8.0.0",
        "description": "Multi-language m3u8 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/vidlink",
            },
            "search": {
                "path": "/search/{query}",
                "example": "/search/Venom",
            },
            "api_endpoints": {
                "health": "GET /api/health",
                "sources": "GET /api/sources",
                "search": "GET /api/search?q={query}",
                "scrape": "POST /api/scrape",
                "scrape_all": "POST /api/scrape/all",
            },
        },
        "sources": {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_sources": DEFAULT_SOURCES,
        "changelog_v8": {
            "updated": ["MovieBox (themoviebox.org, detailPath)", "Castle (IndiaA channel, getVideo2)",
                        "VidLink (enc-dec.app)", "VidSrc (cloudnestra approach)", "NetMirror (TMDB key)"],
            "added": ["VidFast", "ShowBox", "GoatAPI"],
            "removed": ["CineSu (dead/404)", "PrimeSrc (Cloudflare blocked)", "DooFlix (API key revoked)",
                        "VixSrc (Cloudflare blocked)"],
        },
        "tips": [
            "No source = default sources (vidrock, moviebox, netmirror, vidlink, vidfast, castle, videasy)",
            "Best for Hindi: /movie/ID/allmovieland or /movie/ID/moviebox or /movie/ID/castle",
            "Best for English: /movie/ID/vidrock or /movie/ID/vidlink or /movie/ID/vidfast or /movie/ID/videasy",
            "Castle: hlowb.com API with AES-CBC encryption, channel IndiaA, multi-language + multi-quality",
            "NetMirror: Searches Netflix, PrimeVideo, Hotstar via API - great for Hindi/English",
            "VidLink/VidFast: Use enc-dec.app for ID encryption, supports M3U8 quality variants",
            "VidSrc: vsrc.su + cloudnestra.com decryption via enc-dec.app",
            "M4UHD: m4uhd.vip with CryptoJS-compatible AES-CBC (EVP_BytesToKey key derivation)",
            "ShowBox: Requires uiToken for full access - limited without it",
            "GoatAPI: TMDB ID only, returns streams + downloads arrays",
            "m3u8 links work in VLC, mpv, or any HLS player",
        ],
    }


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

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

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

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

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

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

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

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


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

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



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

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

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

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


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