"""Debug v2: captura prefetch.json y espera mas tiempo para el video."""
import asyncio
import sys
import json
sys.stdout.reconfigure(encoding="utf-8")
from playwright.async_api import async_playwright

VID_ID = "wihR3kVLVbphHxSJ"

async def main():
    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",
            viewport={"width": 1280, "height": 800},
        )
        page = await ctx.new_page()

        captured = {"prefetch": None, "video_urls": []}

        async def on_response(resp):
            url = resp.url
            ctype = resp.headers.get("content-type", "")
            if "prefetch.json" in url:
                try:
                    body = await resp.text()
                    captured["prefetch"] = {"url": url, "body": body[:3000]}
                    print(f"\n[PREFETCH] {url[:100]}")
                    print(f"  Body: {body[:500]}")
                except Exception as e:
                    print(f"  Error reading prefetch: {e}")
            if ".mp4" in url or ".m3u8" in url or "mpegurl" in ctype or "video/mp4" in ctype:
                captured["video_urls"].append(f"[{resp.status}] {url[:120]}")
                print(f"  VIDEO URL: {url[:120]}")
            if "vidalytics" in url and resp.status == 200 and "json" in ctype:
                try:
                    body = await resp.text()
                    if any(x in body for x in [".mp4", ".m3u8", "cdn", "storage"]):
                        print(f"\n[JSON with video?] {url[:80]}")
                        print(f"  {body[:400]}")
                except Exception:
                    pass

        page.on("response", on_response)

        embed_url = f"https://vidalytics.com/embed/{VID_ID}"
        print(f"Cargando: {embed_url}")
        await page.goto(embed_url, wait_until="domcontentloaded", timeout=25000)
        await page.wait_for_timeout(4000)

        # Click play en todos los frames
        print("\nClickeando play en todos los frames...")
        for frame in page.frames:
            try:
                result = await frame.evaluate("""() => {
                    // Buscar video
                    const v = document.querySelector('video');
                    if (v) { v.play(); return 'video.play()'; }
                    // Buscar overlay de play
                    const overlays = document.querySelectorAll('[class*=play], [class*=Play], [id*=play]');
                    for (const o of overlays) {
                        if (o.style.display !== 'none' && o.offsetParent !== null) {
                            o.click();
                            return 'clicked: ' + o.tagName + '.' + o.className.substring(0,50);
                        }
                    }
                    return 'nada';
                }""")
                if result != 'nada':
                    print(f"  {frame.url[:60]}: {result}")
            except Exception as e:
                print(f"  Frame error: {e}")

        # Click fisico en el centro
        await page.mouse.click(640, 360)
        print("Esperando 15s para que el video cargue...")
        await page.wait_for_timeout(15000)

        print("\n=== RESUMEN ===")
        print(f"Prefetch: {'SI' if captured['prefetch'] else 'NO'}")
        print(f"Video URLs: {captured['video_urls']}")

        # Revisar src del video en todos los frames
        print("\n--- Video src ---")
        for frame in page.frames:
            try:
                info = await frame.evaluate("""() => {
                    const v = document.querySelector('video');
                    if (!v) return null;
                    const sources = [...v.querySelectorAll('source')].map(s => s.src);
                    return {
                        src: v.src || '',
                        currentSrc: v.currentSrc || '',
                        sources: sources,
                        readyState: v.readyState,
                        paused: v.paused
                    };
                }""")
                if info:
                    print(f"  Frame {frame.url[:50]}: {json.dumps(info, indent=2)}")
            except Exception:
                pass

        await browser.close()

asyncio.run(main())
