"""
Průzkumný skript v3: dekóduje board_base64 a solution_base64
z dailykillersudoku.com — zjistí formát dat.
"""

import asyncio
import json
import sys

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

from playwright.async_api import async_playwright

URL = "https://www.dailykillersudoku.com/puzzle/376"


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)

        # 1) Vytáhni JSON puzzle dat
        print("\n=== Puzzle JSON ===")
        puzzle_json = await page.evaluate("""() => {
            return DKS.puzzle._json;
        }""")
        print(json.dumps(puzzle_json, indent=2))

        # 2) Dekóduj base64 → raw bytes
        print("\n=== board_base64 dekódováno ===")
        board_bytes = await page.evaluate("""() => {
            const b64 = DKS.puzzle._json.board_base64;
            const bytes = DKS.base64ToByteArray(b64);
            return Array.from(bytes);
        }""")
        print(f"  Délka: {len(board_bytes)} bytes")
        print(f"  Raw: {board_bytes}")

        print("\n=== solution_base64 dekódováno ===")
        sol_bytes = await page.evaluate("""() => {
            const b64 = DKS.puzzle._json.solution_base64;
            const bytes = DKS.base64ToByteArray(b64);
            return Array.from(bytes);
        }""")
        print(f"  Délka: {len(sol_bytes)} bytes")
        print(f"  Raw: {sol_bytes}")

        # 3) Jak Board parsuje data
        print("\n=== Board po rozbalení ===")
        board_data = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            return {
                size: board.size,
                cell_count: board._canvas ? 'has canvas' : 'no canvas',
            };
        }""")
        print(json.dumps(board_data, indent=2))

        # 4) Buňky a klece z board
        print("\n=== Board cells ===")
        cells_data = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            if (!board._cells) return 'no _cells';
            const result = [];
            for (let r = 0; r < board.size; r++) {
                for (let c = 0; c < board.size; c++) {
                    const cell = board._cells[r][c];
                    result.push({
                        row: r, col: c,
                        value: cell._value || cell.value,
                        cage: cell._cage ? {
                            sum: cell._cage._sum || cell._cage.sum,
                            id: cell._cage._id || cell._cage.id
                        } : null
                    });
                }
            }
            return result;
        }""")
        if isinstance(cells_data, list):
            print(f"  Celkem buněk: {len(cells_data)}")
            for c in cells_data[:20]:
                print(f"  [{c['row']},{c['col']}] value={c.get('value')} cage={c.get('cage')}")
        else:
            print(f"  {cells_data}")

        # 5) Zkus přístup přes cages
        print("\n=== Cages ===")
        cages_data = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            // Zkus najít cages
            const props = Object.keys(board).filter(k => !k.startsWith('_') || k.includes('cage') || k.includes('Cage'));
            const allProps = Object.keys(board);
            return {all_props: allProps, filtered: props};
        }""")
        print(json.dumps(cages_data, indent=2))

        # 6) Všechny vlastnosti boardu
        print("\n=== Board — všechny vlastnosti ===")
        board_full = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            const result = {};
            for (const key of Object.keys(board)) {
                const val = board[key];
                const t = typeof val;
                if (t === 'function') continue;
                if (t === 'object' && val !== null) {
                    if (Array.isArray(val)) {
                        result[key] = `Array(${val.length})`;
                        if (val.length > 0 && val.length < 100) {
                            try {
                                const sample = val[0];
                                result[key + '_sample'] = typeof sample === 'object' ? Object.keys(sample || {}).slice(0,10) : sample;
                            } catch(e) {}
                        }
                    } else {
                        result[key] = Object.keys(val).slice(0, 10);
                    }
                } else {
                    result[key] = val;
                }
            }
            return result;
        }""")
        print(json.dumps(board_full, indent=2, ensure_ascii=False)[:5000])

        # 7) Solution data
        print("\n=== Solution ===")
        solution_data = await page.evaluate("""() => {
            const sol = DKS.puzzle.solution;
            if (!sol) return 'no solution';
            const props = Object.keys(sol);
            const result = {props: props};
            for (const p of props) {
                const v = sol[p];
                if (typeof v !== 'function') {
                    if (Array.isArray(v)) {
                        result[p] = v.slice(0, 20);
                    } else {
                        result[p] = v;
                    }
                }
            }
            return result;
        }""")
        print(json.dumps(solution_data, indent=2, ensure_ascii=False)[:3000])

        await browser.close()


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