"""
Průzkumný skript: připojí se na solitaire.org/daily-sudoku/ a vytáhne
surová JS data o puzzle (gameLevels, Game objekt).
"""

import asyncio
import json
import sys

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

from playwright.async_api import async_playwright

URL = "https://www.solitaire.org/daily-sudoku/"


async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(viewport={"width": 1280, "height": 900})

        page = await context.new_page()
        print(f"Načítám {URL} ...")
        await page.goto(URL, wait_until="networkidle", timeout=60_000)

        game_url = None
        for frame in page.frames:
            if frame.url != page.url and frame.url.strip() not in ("", "about:blank"):
                game_url = frame.url
                print(f"  Nalezen iframe: {game_url}")
                break

        if not game_url:
            iframe_src = await page.get_attribute("iframe", "src")
            if iframe_src:
                game_url = iframe_src if iframe_src.startswith("http") else f"https://www.solitaire.org{iframe_src}"
                print(f"  Iframe src z DOM: {game_url}")

        await page.close()

        game_page = await context.new_page()
        target_url = game_url if game_url else URL
        print(f"Načítám hru: {target_url} ...")
        await game_page.goto(target_url, wait_until="networkidle", timeout=60_000)

        # 1) gameLevels — struktura
        print("\n=== gameLevels — struktura ===")
        structure = await game_page.evaluate("""() => {
            if (typeof gameLevels === 'undefined') return null;
            const result = {};
            for (const diff of Object.keys(gameLevels)) {
                const keys = Object.keys(gameLevels[diff]);
                result[diff] = {
                    count: keys.length,
                    first_keys: keys.slice(0, 3),
                    last_keys: keys.slice(-3),
                    sample_value: gameLevels[diff][keys[0]]
                };
            }
            return result;
        }""")
        if structure:
            print(json.dumps(structure, indent=2, ensure_ascii=False)[:5000])
        else:
            print("  gameLevels není definováno")

        # 2) Dnešní data
        print("\n=== Dnešní data (05-08) ===")
        today_data = await game_page.evaluate("""() => {
            const key = '05-08';
            const result = {};
            if (typeof gameLevels === 'undefined') return null;
            for (const diff of Object.keys(gameLevels)) {
                if (gameLevels[diff] && gameLevels[diff][key]) {
                    result[diff] = gameLevels[diff][key];
                }
            }
            return result;
        }""")
        if today_data:
            print(json.dumps(today_data, indent=2, ensure_ascii=False)[:5000])
        else:
            print("  žádná data pro dnešek")

        # 3) Game objekt — klíče
        print("\n=== Game objekt — klíče ===")
        game_keys = await game_page.evaluate("""() => {
            if (typeof Game !== 'undefined') return Object.keys(Game);
            return null;
        }""")
        if game_keys:
            print(json.dumps(game_keys, indent=2))
        else:
            print("  Game není definováno")

        await browser.close()


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