"""
inspect_lesson_dom.py
Abre el browser, va a lección 1 y 2, guarda el HTML y texto completo
para identificar los selectores correctos del contenido de la lección.
"""
import asyncio
import json
import sys
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"
DEBUG_DIR    = SCRIPTS_DIR / "debug_content"
MEMBERS_URL  = "https://kaleanders.clickfunnels.com/members-raio"

DEBUG_DIR.mkdir(exist_ok=True)


async def dump_page(page, label: str):
    """Save full HTML + inner text + all text blocks with selectors."""
    # Full HTML
    html = await page.content()
    (DEBUG_DIR / f"{label}_full.html").write_text(html, encoding="utf-8")

    # Full inner text of body
    body_text = await page.evaluate("() => document.body.innerText")
    (DEBUG_DIR / f"{label}_body.txt").write_text(body_text, encoding="utf-8")

    # Current URL
    url = page.url

    # Structured analysis: all elements with text > 30 chars, unique
    analysis = await page.evaluate(r"""
        () => {
            const result = {
                url: window.location.href,
                title: document.title,
                allSelectors: [],
                uniqueTextBlocks: [],
            };

            // Check specific selectors
            const toCheck = [
                'main', 'article', 'section',
                '[data-page-element]',
                '[data-page-element="Paragraph/V1"]',
                '[data-page-element="Content/V1"]',
                '[data-page-element="Headline/V2"]',
                '.elContent', '.elParagraphText',
                '.cf-lesson-description', '.lesson-content', '.lesson-body',
                '.lesson-description', '[data-lesson-content]',
                '.cf-page-content', '.page-content',
                '.container', '.row', '.col',
                '.members-area', '.course-content', '.lesson-text',
                'div[class*="lesson"]', 'div[class*="content"]',
                'div[class*="story"]', 'div[class*="text"]',
            ];

            for (const sel of toCheck) {
                const els = document.querySelectorAll(sel);
                if (els.length) {
                    const first = els[0];
                    const text = (first.innerText || '').trim();
                    result.allSelectors.push({
                        sel,
                        count: els.length,
                        textLen: text.length,
                        preview: text.substring(0, 120).replace(/\n/g, '↵'),
                        dataAttrs: JSON.stringify(Object.fromEntries(
                            Object.entries(first.dataset || {}).slice(0, 5)
                        )),
                    });
                }
            }

            // Get all leaf elements with unique text
            const seen = new Set();
            const walker = document.createTreeWalker(
                document.body,
                NodeFilter.SHOW_ELEMENT,
            );
            let node;
            while ((node = walker.nextNode())) {
                const text = (node.innerText || '').trim();
                if (text.length > 40 && text.length < 5000 && !seen.has(text)) {
                    const children = node.querySelectorAll('*');
                    const childTexts = Array.from(children).map(c => (c.innerText || '').trim());
                    const isLeaf = !childTexts.some(ct => ct.length >= text.length * 0.85);
                    if (isLeaf) {
                        seen.add(text);
                        result.uniqueTextBlocks.push({
                            tag: node.tagName.toLowerCase(),
                            id: node.id || '',
                            classes: (node.className || '').substring(0, 80),
                            dataElem: (node.dataset || {}).pageElement || '',
                            textLen: text.length,
                            preview: text.substring(0, 150).replace(/\n/g, '↵'),
                        });
                    }
                }
            }

            return result;
        }
    """)

    (DEBUG_DIR / f"{label}_analysis.json").write_text(
        json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    print(f"\n{'='*60}")
    print(f"Lesson: {label} | URL: {url}")
    print(f"Selectores con texto:")
    for s in analysis.get("allSelectors", []):
        if s["textLen"] > 50:
            print(f"  [{s['sel']}] ×{s['count']} | {s['textLen']}ch | {s['preview'][:80]}")
    print(f"\nBloques únicos de texto ({len(analysis.get('uniqueTextBlocks', []))}):")
    for b in analysis.get("uniqueTextBlocks", [])[:20]:
        print(f"  <{b['tag']}> id={b['id']!r} cls={b['classes']!r} data={b['dataElem']!r} | {b['textLen']}ch | {b['preview'][:80]}")
    print(f"\nArchivos guardados en: {DEBUG_DIR}")
    return analysis


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

        print("Cargando lección 1...")
        await page.goto(MEMBERS_URL, wait_until="domcontentloaded", timeout=45000)
        await page.wait_for_timeout(10000)  # 10s para que todo cargue

        print("Inspeccionando lección 1...")
        await dump_page(page, "lesson01")

        # Navigate to next
        print("\nNavegando a lección 2...")
        clicked = False
        for sel in [
            "a[href='#next-lesson']", "#next-lesson",
            "a:has-text('Siguiente')", "a:has-text('Next')",
            "button:has-text('Siguiente')", "button:has-text('Next')",
        ]:
            try:
                btn = await page.query_selector(sel)
                if btn and await btn.is_visible():
                    print(f"  Clickeando: {sel}")
                    await btn.click()
                    clicked = True
                    break
            except Exception as e:
                pass

        if not clicked:
            print("  [!!] No se encontró botón de siguiente!")
            print("  Buscando todos los links/botones en la página:")
            links = await page.evaluate(r"""
                () => {
                    const els = [...document.querySelectorAll('a, button')];
                    return els
                        .filter(e => (e.innerText || '').trim().length > 0)
                        .slice(0, 30)
                        .map(e => ({
                            tag: e.tagName.toLowerCase(),
                            text: (e.innerText || '').trim().substring(0, 50),
                            href: e.href || '',
                            cls: (e.className || '').substring(0, 60),
                        }));
                }
            """)
            for l in links:
                print(f"  <{l['tag']}> text={l['text']!r} href={l['href']!r} cls={l['cls']!r}")
        else:
            await page.wait_for_timeout(10000)  # 10s para que cargue lección 2
            print("Inspeccionando lección 2...")
            await dump_page(page, "lesson02")

        print("\nInspección completa. Navegador permanece abierto 30s...")
        await page.wait_for_timeout(30000)
        await browser.close()


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