"""Debug: inspect the Vidalytics player on the ClickFunnels members page."""
import asyncio
import json
import sys
import re
sys.stdout.reconfigure(encoding="utf-8")
from playwright.async_api import async_playwright
from pathlib import Path

SCRIPTS_DIR = Path(__file__).parent
COOKIES_FILE = SCRIPTS_DIR / ".course_cookies.json"
MEMBERS_URL = "https://kaleanders.clickfunnels.com/members-raio"

async def main():
    cookies = json.loads(COOKIES_FILE.read_text(encoding="utf-8"))

    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},
        )
        await ctx.add_cookies(cookies)
        page = await ctx.new_page()

        all_urls = []

        async def on_req(req):
            url = req.url
            if any(x in url for x in ["vidalytics", ".m3u8", ".mp4", "fast.", "video"]):
                all_urls.append(f"REQ: {url[:150]}")

        async def on_resp(resp):
            url = resp.url
            ctype = resp.headers.get("content-type", "")
            if any(x in url for x in ["vidalytics", ".m3u8", ".mp4", "fast."]) or \
               any(x in ctype for x in ["video", "mpegurl"]):
                all_urls.append(f"RESP[{resp.status}][{ctype[:20]}]: {url[:150]}")

        page.on("request", on_req)
        page.on("response", on_resp)

        print(f"Cargando {MEMBERS_URL}")
        await page.goto(MEMBERS_URL, wait_until="domcontentloaded", timeout=30000)
        await page.wait_for_timeout(5000)

        print("\n--- Frames en la pagina ---")
        for i, frame in enumerate(page.frames):
            print(f"  [{i}] {frame.url[:100]}")

        print("\n--- Estructura del player (frame principal) ---")
        info = await page.evaluate("""() => {
            const embed = document.querySelector('[id^="vidalytics_embed_"]');
            const video = document.querySelector('video');
            const iframes = [...document.querySelectorAll('iframe')].map(f => f.src || f.srcdoc?.substring(0,50) || 'about:blank');
            return {
                hasEmbed: !!embed,
                embedId: embed?.id || '',
                hasVideo: !!video,
                videoSrc: video?.src || '',
                videoCurrentSrc: video?.currentSrc || '',
                iframes: iframes,
                embedHTML: embed?.innerHTML?.substring(0, 200) || ''
            };
        }""")
        print(f"  embed ID: {info['embedId']}")
        print(f"  has video: {info['hasVideo']}")
        print(f"  video src: {info['videoSrc']}")
        print(f"  iframes: {info['iframes']}")
        print(f"  embed innerHTML: {info['embedHTML'][:100]}")

        print("\n--- Clickeando play (todos los frames) ---")
        for i, frame in enumerate(page.frames):
            try:
                result = await frame.evaluate("""() => {
                    const v = document.querySelector('video');
                    if (v) {
                        const wasPaused = v.paused;
                        v.play().catch(() => {});
                        return 'video src=' + v.src + ' wasPaused=' + wasPaused;
                    }
                    // Buscar elementos clickeables
                    const all = [...document.querySelectorAll('*')].filter(el => {
                        const cls = (el.className?.toString() || '').toLowerCase();
                        const id = (el.id || '').toLowerCase();
                        return (cls.includes('play') || id.includes('play')) &&
                               el.offsetWidth > 0 && el.offsetHeight > 0;
                    });
                    if (all.length > 0) {
                        all[0].click();
                        return 'clicked: ' + all[0].tagName + ' ' + all[0].className?.toString().substring(0,50);
                    }
                    return null;
                }""")
                if result:
                    print(f"  frame[{i}] {frame.url[:40]}: {result}")
            except Exception as e:
                print(f"  frame[{i}] error: {e}")

        # Click fisico
        await page.mouse.click(640, 400)
        print("\nEsperando 15s despues del click...")
        await page.wait_for_timeout(15000)

        print("\n--- URLs capturadas despues del click ---")
        for u in all_urls[-30:]:
            print(f"  {u[:160]}")

        print("\n--- Video src despues del click ---")
        for i, frame in enumerate(page.frames):
            try:
                v = await frame.evaluate("""() => {
                    const v = document.querySelector('video');
                    if (!v) return null;
                    return {src: v.src, cs: v.currentSrc, rs: v.readyState};
                }""")
                if v:
                    print(f"  frame[{i}] {frame.url[:50]}: {v}")
            except Exception:
                pass

        await browser.close()

asyncio.run(main())
