import json
import time
from playwright.sync_api import sync_playwright

SESSION_DIR = "./snapchat_session"

with sync_playwright() as p:
    context = p.chromium.launch_persistent_context(
        user_data_dir=SESSION_DIR,
        channel="chrome",
        headless=False,
        viewport={"width": 1280, "height": 720},
        args=["--disable-blink-features=AutomationControlled"],
        ignore_default_args=["--enable-automation"],
        user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
    )

    page = context.pages[0] if context.pages else context.new_page()
    
    try:
        page.goto("https://web.snapchat.com/", timeout=60000, wait_until="domcontentloaded")
    except Exception as e:
        print(f"[!] Erreur navigation: {e}")
    
    time.sleep(10)
    
    debug_js = """
    () => {
        let results = [];
        let allLis = document.querySelectorAll('li');
        allLis.forEach((li, idx) => {
            let rect = li.getBoundingClientRect();
            let text = li.innerText.trim().substring(0, 100);
            let imgCount = li.querySelectorAll('img').length;
            if (text.length > 0 || imgCount > 0) {
                results.push({
                    index: idx,
                    x: Math.round(rect.left),
                    y: Math.round(rect.top),
                    width: Math.round(rect.width),
                    height: Math.round(rect.height),
                    text: text,
                    imgCount: imgCount
                });
            }
        });
        return results;
    }
    """
    
    items = page.evaluate(debug_js)
    with open('debug_output.json', 'w') as f:
        json.dump(items, f, indent=2, ensure_ascii=False)
        
    context.close()
