"""
Průzkumný skript: připojí se na solitaire.org/daily-kakuro/ 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-kakuro/"


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
        print("\n=== gameLevels ===")
        game_levels = await game_page.evaluate("""() => {
            if (typeof gameLevels !== 'undefined') return JSON.stringify(gameLevels, null, 2);
            return null;
        }""")
        if game_levels:
            print(game_levels[:5000])
            if len(game_levels) > 5000:
                print(f"... (celkem {len(game_levels)} znaků)")
        else:
            print("  gameLevels není definováno")

        # 2) 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")

        # 3) Game — datové vlastnosti
        print("\n=== Game — datové vlastnosti ===")
        game_data = await game_page.evaluate("""() => {
            if (typeof Game === 'undefined') return null;
            const result = {};
            for (const key of Object.keys(Game)) {
                const val = Game[key];
                if (typeof val !== 'function') {
                    try { result[key] = JSON.parse(JSON.stringify(val)); }
                    catch(e) { result[key] = String(val); }
                }
            }
            return result;
        }""")
        if game_data:
            txt = json.dumps(game_data, indent=2, ensure_ascii=False)
            print(txt[:3000])
        else:
            print("  žádná data")

        # 4) Další globální proměnné
        print("\n=== Další globální proměnné ===")
        globals_check = await game_page.evaluate("""() => {
            const names = ['puzzleData', 'dailyPuzzle', 'gameData', 'levels',
                           'puzzle', 'boardData', 'board', 'grid', 'cells',
                           'kakuroData', 'kakuroLevels'];
            const found = {};
            for (const name of names) {
                if (typeof window[name] !== 'undefined') {
                    found[name] = typeof window[name];
                }
            }
            return found;
        }""")
        print(json.dumps(globals_check, indent=2))

        # 5) Game.printDaily zdrojový kód
        print("\n=== Game.printDaily — zdrojový kód ===")
        print_src = await game_page.evaluate("""() => {
            if (typeof Game !== 'undefined' && typeof Game.printDaily === 'function') {
                return Game.printDaily.toString();
            }
            return null;
        }""")
        if print_src:
            print(print_src[:3000])
        else:
            print("  Game.printDaily neexistuje")

        # 6) Dnešní data — zkus první záznam
        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")

        await browser.close()


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