File size: 27,609 Bytes
a330af4
93094bf
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
 
 
 
 
 
 
a330af4
 
 
93094bf
 
 
 
 
 
 
 
a330af4
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
 
93094bf
85d7261
 
 
 
 
 
a330af4
 
 
 
 
93094bf
a330af4
93094bf
85d7261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a330af4
 
93094bf
85d7261
 
93094bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85d7261
93094bf
 
 
 
 
 
 
 
 
85d7261
a330af4
 
93094bf
85d7261
 
93094bf
 
a330af4
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
93094bf
a330af4
93094bf
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
 
 
 
 
 
 
 
a330af4
93094bf
 
 
 
 
 
 
 
a330af4
93094bf
 
 
 
 
 
 
 
 
a330af4
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
 
 
 
 
 
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
 
 
 
 
 
 
a330af4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
a330af4
 
 
 
 
 
 
 
 
426e8e9
 
 
93094bf
 
 
4303eeb
 
93094bf
 
 
 
426e8e9
 
4303eeb
426e8e9
 
93094bf
426e8e9
 
 
 
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
93094bf
426e8e9
 
93094bf
426e8e9
93094bf
426e8e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93094bf
 
 
 
426e8e9
 
 
93094bf
a330af4
 
426e8e9
93094bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4303eeb
 
93094bf
 
 
4303eeb
93094bf
 
 
4303eeb
93094bf
 
 
 
 
 
426e8e9
 
93094bf
 
426e8e9
 
93094bf
426e8e9
 
93094bf
 
426e8e9
 
93094bf
 
426e8e9
 
93094bf
426e8e9
 
93094bf
 
426e8e9
 
 
 
 
 
 
 
 
 
8b468c1
93094bf
426e8e9
 
 
 
 
93094bf
 
 
 
 
 
 
 
 
 
 
 
 
426e8e9
 
93094bf
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
"""
StreamForge API v4 - Multi-Language Stream Scraper
Scrapes direct m3u8 URLs from multiple sources
"""

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 time
import asyncio

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

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

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

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


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

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


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

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


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


# ===== CineSu Scraper =====

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

    try:
        async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client:
            if media_type == "movie":
                url = f"https://cine.su/v1/stream/master/movie/{tmdb_id}.m3u8"
            else:
                s = season or 1
                e = episode or 1
                url = f"https://cine.su/v1/stream/master/tv/{tmdb_id}/{s}/{e}.m3u8"

            resp = await client.get(url, headers={
                "Referer": "https://cine.su/en/watch",
                "Origin": "https://cine.su",
            })

            if resp.status_code == 404:
                errors.append("CineSu: Content not available")
                return results, errors

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

            content = resp.text
            if "#EXT-X-STREAM-INF" in content:
                lines = 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].startswith("http"):
                            results.append({
                                "source": "CineSu",
                                "title": label,
                                "quality": quality,
                                "language": "English",
                                "url": lines[i + 1].strip(),
                                "type": "m3u8",
                            })
            elif ".m3u8" in content:
                m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content)
                if m3u8_match:
                    results.append({
                        "source": "CineSu",
                        "title": "English Stream",
                        "quality": "Auto",
                        "language": "English",
                        "url": m3u8_match.group(0),
                        "type": "m3u8",
                    })

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

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

    return results, errors


# ===== VixSrc Scraper (Fixed: uses window.masterPlaylist) =====

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

    try:
        async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client:
            # Step 1: Get embed path
            if media_type == "movie":
                api_url = f"https://vixsrc.to/api/movie/{tmdb_id}"
            else:
                s = season or 1
                e = episode or 1
                api_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}"

            api_resp = await client.get(api_url)

            try:
                api_data = api_resp.json()
            except:
                errors.append("VixSrc: API returned non-JSON (possible Cloudflare block)")
                return results, errors

            src_path = api_data.get("src", "")
            if not src_path:
                errors.append("VixSrc: No embed path returned")
                return results, errors

            # Step 2: Fetch embed HTML
            embed_resp = await client.get(f"https://vixsrc.to{src_path}")

            if embed_resp.status_code == 410:
                # Token expired, retry once
                api_resp2 = await client.get(api_url)
                try:
                    api_data2 = api_resp2.json()
                except:
                    errors.append("VixSrc: API retry failed")
                    return results, errors
                src_path2 = api_data2.get("src", "")
                if not src_path2:
                    errors.append("VixSrc: No embed path on retry")
                    return results, errors
                embed_resp = await client.get(f"https://vixsrc.to{src_path2}")
                src_path = src_path2

            html = embed_resp.text

            # Step 3: Extract from window.masterPlaylist
            token = None
            expires = None
            playlist_url = None

            mp_match = re.search(r'window\.masterPlaylist\s*=\s*(\{[\s\S]*?\})\s*\n', html)
            if mp_match:
                mp_text = mp_match.group(1)
                token_m = re.search(r"'token'\s*:\s*'([^']+)'", mp_text)
                expires_m = re.search(r"'expires'\s*:\s*'([^']+)'", mp_text)
                url_m = re.search(r"url\s*:\s*'([^']+)'", mp_text)

                if token_m:
                    token = token_m.group(1)
                if expires_m:
                    expires = expires_m.group(1)
                if url_m:
                    playlist_url = url_m.group(1)

            # Fallback: try old patterns
            if not token:
                token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html)
                if token_match:
                    token = token_match.group(1)
            if not playlist_url:
                url_match = re.search(r'url\s*:\s*["\']([^"\']+playlist[^"\']*)', html)
                if url_match:
                    playlist_url = url_match.group(1)

            if not (token and playlist_url):
                errors.append("VixSrc: Could not extract stream parameters from embed")
                return results, errors

            # Step 4: Build master URL and fetch
            if not expires:
                expires = str(int(time.time()) + 86400)
            sep = "&" if "?" in playlist_url else "?"
            master_url = f"{playlist_url}{sep}token={token}&expires={expires}&h=1"

            pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"})
            pl_content = pl_resp.text

            if "#EXTM3U" in pl_content:
                # Parse audio tracks
                audio_tracks = []
                lines = pl_content.split("\n")
                for line in lines:
                    if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"):
                        name_match = re.search(r'NAME="([^"]+)"', line)
                        lang_match = re.search(r'LANGUAGE="([^"]+)"', line)
                        uri_match = re.search(r'URI="([^"]+)"', line)
                        if name_match and uri_match:
                            audio_tracks.append({
                                "language": name_match.group(1),
                                "lang_code": lang_match.group(1) if lang_match else name_match.group(1),
                                "uri": uri_match.group(1),
                            })

                # Parse video streams
                for i, line in enumerate(lines):
                    if line.startswith("#EXT-X-STREAM-INF:"):
                        resolution = re.search(r'RESOLUTION=(\d+x\d+)', line)
                        quality = resolution.group(1) if resolution else "Auto"
                        if i + 1 < len(lines) and lines[i + 1].startswith("http"):
                            video_url = lines[i + 1].strip()
                            if audio_tracks:
                                for track in audio_tracks:
                                    results.append({
                                        "source": "VixSrc",
                                        "title": f"{track['language']} Audio",
                                        "quality": quality,
                                        "language": detect_language(track["language"]),
                                        "url": video_url,
                                        "audio_url": track["uri"],
                                        "type": "m3u8",
                                    })
                            else:
                                results.append({
                                    "source": "VixSrc",
                                    "title": "English Stream",
                                    "quality": quality,
                                    "language": "English",
                                    "url": video_url,
                                    "type": "m3u8",
                                })
            else:
                # Return master URL as-is if we can't parse
                results.append({
                    "source": "VixSrc",
                    "title": "Stream",
                    "quality": "Auto",
                    "language": "Multi",
                    "url": master_url,
                    "type": "m3u8",
                })

            if not results:
                errors.append("VixSrc: No streams found in playlist")

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

    return results, errors


# ===== VidNest Scraper =====

VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="

def vidnest_b64_decode(input_str: str) -> str:
    lookup = {c: i for i, c in enumerate(VIDNEST_ALPHABET)}
    mod = len(input_str) % 4
    if mod:
        input_str += "=" * (4 - mod)
    result = bytearray()
    for i in range(0, len(input_str), 4):
        chunk = input_str[i:i+4]
        c0 = lookup.get(chunk[0], 64)
        c1 = lookup.get(chunk[1], 64)
        c2 = 64 if chunk[2] == "=" else lookup.get(chunk[2], 64)
        c3 = 64 if chunk[3] == "=" else lookup.get(chunk[3], 64)
        result.append(((c0 << 2) | (c1 >> 4)) & 0xff)
        if c2 != 64:
            result.append((((c1 & 0x0f) << 4) | (c2 >> 2)) & 0xff)
        if c3 != 64:
            result.append((((c2 & 0x03) << 6) | c3) & 0xff)
    return bytes(result).decode("utf-8", errors="ignore")


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

    servers = {
        "purstream": "French",
        "klikxxi": "English",
        "hollymoviehd": "English",
        "moviebox": "Multi",
        "allmovies": "Multi",
        "vidlink": "English",
        "onehd": "English",
        "flixhq": "English",
    }

    try:
        async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client:
            async def fetch_server(server_name: str, language: str):
                server_results = []
                try:
                    if media_type == "movie":
                        url = f"https://new.vidnest.fun/{server_name}/movie/{tmdb_id}"
                    else:
                        s = season or 1
                        e = episode or 1
                        url = f"https://new.vidnest.fun/{server_name}/tv/{tmdb_id}/{s}/{e}"

                    resp = await client.get(url)
                    if resp.status_code != 200:
                        return server_results, f"{server_name}: HTTP {resp.status_code}"

                    data = resp.json()
                    encoded_data = data.get("data", "")
                    if not encoded_data:
                        return server_results, f"{server_name}: No data"

                    decoded = vidnest_b64_decode(encoded_data)
                    parsed = json.loads(decoded)

                    sources = parsed.get("sources", [])
                    title = parsed.get("title", "")

                    for source in sources:
                        url_key = None
                        for key in ["url", "file", "stream", "src", "link"]:
                            if key in source:
                                url_key = key
                                break
                        if not url_key:
                            continue

                        stream_url = source[url_key]
                        quality = source.get("quality") or source.get("label") or source.get("name", "Auto")
                        source_name = source.get("name", source.get("label", ""))
                        stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"

                        lang = detect_language(source_name) if source_name else language

                        server_results.append({
                            "source": f"VidNest/{server_name}",
                            "title": source_name or title,
                            "quality": quality,
                            "language": lang,
                            "url": stream_url,
                            "type": stream_type,
                        })

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

                return server_results, None

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

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

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

    return results, errors


# ===== Popr Scraper (Improved dedup) =====

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

    servers = ["default", "catflix", "hexa", "Gama", "Liligoon", "Sigma", "Prime", "Alfa", "Lamda"]

    try:
        async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client:
            async def fetch_server(server: str):
                server_results = []
                try:
                    if media_type == "movie":
                        url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=movie&server={server}"
                    else:
                        s = season or 1
                        e = episode or 1
                        url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=tv&server={server}&season={s}&episode={e}"

                    resp = await client.get(url)
                    if resp.status_code != 200:
                        return server_results, f"{server}: HTTP {resp.status_code}"

                    data = resp.json()
                    if not data.get("success"):
                        return server_results, None

                    for r in data.get("results", []):
                        for stream in r.get("streams", []):
                            stream_url = stream.get("url", "")
                            quality = stream.get("quality", "Auto")
                            is_m3u8 = stream.get("isM3U8", False)
                            stream_type = "m3u8" if is_m3u8 else "direct"

                            lang = detect_language(quality)

                            server_results.append({
                                "source": f"Popr/{server}",
                                "title": quality,
                                "quality": quality,
                                "language": lang,
                                "url": stream_url,
                                "type": stream_type,
                            })

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

                return server_results, None

            tasks = [fetch_server(s) for s in servers]
            task_results = await asyncio.gather(*tasks, return_exceptions=True)

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

            # Deduplicate by URL
            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"Popr: {str(e)}")

    return results, errors


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

SOURCE_MAP = {
    "cinesu": {"name": "CineSu", "fn": lambda tid, mt, s, e: scrape_cinesu(tid, mt, s, e),
               "languages": ["English"], "reliability": "high"},
    "vixsrc": {"name": "VixSrc", "fn": lambda tid, mt, s, e: scrape_vixsrc(tid, mt, s, e),
               "languages": ["English", "Italian", "Multi"], "reliability": "low",
               "note": "Cloudflare-blocked from datacenter IPs, works from residential only"},
    "vidnest": {"name": "VidNest", "fn": lambda tid, mt, s, e: scrape_vidnest(tid, mt, s, e),
                "languages": ["French", "English", "Multi"], "reliability": "medium"},
    "popr": {"name": "Popr", "fn": lambda tid, mt, s, e: scrape_popr(tid, mt, s, e),
             "languages": ["Hindi", "Tamil", "Telugu", "English", "French"], "reliability": "high"},
}

DEFAULT_SOURCES = ["cinesu", "popr"]


# ===== 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=30)
            return r, e
        except asyncio.TimeoutError:
            return [], [f"{src['name']}: Timeout (30s)"]
        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)

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


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

@app.get("/")
async def root():
    return {
        "api": "StreamForge",
        "version": "4.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/popr",
            },
            "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/cinesu",
            },
            "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,
        "tips": [
            "No source = default sources (cinesu, popr)",
            "Best for Hindi: /movie/ID/popr",
            "Best for English: /movie/ID/cinesu",
            "Best for French: /movie/ID/vidnest",
            "VixSrc (Italian) blocked from cloud IPs, works residential only",
            "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)