"""
Extrae URLs de video de Vidalytics interceptando requests de red con Playwright.
"""
import asyncio
import json
import re
import sys
import subprocess
from pathlib import Path

from playwright.async_api import async_playwright

sys.stdout.reconfigure(encoding="utf-8")

SCRIPTS_DIR = Path(__file__).parent
COOKIES_FILE = SCRIPTS_DIR / ".course_cookies.json"


async def extract_video_url(vidalytics_id: str, cookies: list) -> dict:
    """Abre el embed de Vidalytics e intercepta la URL del video."""
    embed_url = f"https://vidalytics.com/embed/{vidalytics_id}"
    print(f"  Abriendo: {embed_url}")

    video_info = {"id": vidalytics_id, "stream_url": None, "mp4_urls": [], "m3u8_urls": [], "all_requests": []}

    async with async_playwright() as pw:
        browser = await pw.chromium.launch(headless=True)
        ctx = await browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36",
        )
        if cookies:
            await ctx.add_cookies(cookies)

        page = await ctx.new_page()

        # Interceptar todas las requests de red
        async def on_request(request):
            url = request.url
            if any(ext in url.lower() for ext in [".mp4", ".m3u8", ".ts", "video", "stream", "manifest"]):
                video_info["all_requests"].append(url)
                if ".mp4" in url.lower():
                    video_info["mp4_urls"].append(url)
                if ".m3u8" in url.lower():
                    video_info["m3u8_urls"].append(url)

        async def on_response(response):
            url = response.url
            ctype = response.headers.get("content-type", "")
            if "video" in ctype or "stream" in ctype or "m3u8" in ctype:
                video_info["all_requests"].append(f"[RESP] {url} ({ctype})")

        page.on("request", on_request)
        page.on("response", on_response)

        try:
            await page.goto(embed_url, wait_until="domcontentloaded", timeout=20000)
            await page.wait_for_timeout(5000)  # esperar que el player cargue

            # Intentar hacer click en play para iniciar el video
            play_btn = await page.query_selector("button.play, .play-button, [aria-label='Play'], video")
            if play_btn:
                await play_btn.click()
                await page.wait_for_timeout(3000)

        except Exception as e:
            print(f"  Error: {e}")

        # Buscar URLs en el HTML renderizado
        html = await page.content()
        mp4_in_html = re.findall(r'https?://[^"\'<>\s]+\.mp4[^"\'<>\s]*', html)
        m3u8_in_html = re.findall(r'https?://[^"\'<>\s]+\.m3u8[^"\'<>\s]*', html)
        cdns = re.findall(r'https?://[^"\'<>\s]*(?:cdn|storage|media|video)[^"\'<>\s]*\.(?:mp4|m3u8)[^"\'<>\s]*', html)

        video_info["mp4_urls"].extend(mp4_in_html)
        video_info["m3u8_urls"].extend(m3u8_in_html)
        video_info["mp4_urls"].extend(cdns)

        # Buscar config JSON de Vidalytics en scripts
        scripts_text = "\n".join(s.get_text() for s in __import__("bs4").BeautifulSoup(html, "html.parser").find_all("script"))
        json_blocks = re.findall(r'\{[^{}]*(?:url|src|source|videoUrl)[^{}]*\}', scripts_text)
        for block in json_blocks[:5]:
            urls = re.findall(r'https?://[^"\']+', block)
            for u in urls:
                if any(ext in u for ext in [".mp4", ".m3u8"]):
                    video_info["mp4_urls" if ".mp4" in u else "m3u8_urls"].append(u)

        await browser.close()

    # Elegir la mejor URL
    video_info["mp4_urls"] = list(dict.fromkeys(video_info["mp4_urls"]))
    video_info["m3u8_urls"] = list(dict.fromkeys(video_info["m3u8_urls"]))
    video_info["stream_url"] = (video_info["m3u8_urls"] or video_info["mp4_urls"] or [None])[0]

    return video_info


async def main():
    test_ids = ["wihR3kVLVbphHxSJ", "tzRWrTefukz6FKVn"]

    cookies = []
    if COOKIES_FILE.exists():
        cookies = json.loads(COOKIES_FILE.read_text())

    for vid_id in test_ids:
        print(f"\nID: {vid_id}")
        info = await extract_video_url(vid_id, cookies)
        print(f"  MP4 URLs:  {info['mp4_urls'][:2]}")
        print(f"  M3U8 URLs: {info['m3u8_urls'][:2]}")
        print(f"  Otras requests: {len(info['all_requests'])}")
        for r in info['all_requests'][:10]:
            print(f"    {r[:120]}")
        if info["stream_url"]:
            print(f"  -> STREAM: {info['stream_url']}")
        else:
            print("  -> Sin URL de stream encontrada")


if __name__ == "__main__":
    asyncio.run(main())
