"""
Průzkumný skript v5: najde správné property names pro cell row/col.
"""

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)

        # Zjisti property names buněk v klecích
        print("\n=== Cell properties ===")
        cell_props = await page.evaluate("""() => {
            const cage = DKS.puzzle.board._cages[0];
            const cell = cage.cells[0];
            return Object.keys(cell);
        }""")
        print(json.dumps(cell_props, indent=2))

        # Zkus všechny varianty row/col
        print("\n=== Cell row/col lookup ===")
        cell_data = await page.evaluate("""() => {
            const cage = DKS.puzzle.board._cages[0];
            const cell = cage.cells[0];
            const result = {};
            for (const key of Object.keys(cell)) {
                const val = cell[key];
                if (typeof val !== 'function' && typeof val !== 'object') {
                    result[key] = val;
                }
            }
            return result;
        }""")
        print(json.dumps(cell_data, indent=2))

        # Klece s buňkami — správné property
        print("\n=== Cages s buňkami ===")
        cages = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            return board._cages.map((cage, i) => {
                const cells = cage.cells.map(c => {
                    // Najdi row/col property
                    const keys = Object.keys(c);
                    const rowKey = keys.find(k => k.toLowerCase().includes('row') && typeof c[k] === 'number');
                    const colKey = keys.find(k => (k.toLowerCase().includes('col') || k.toLowerCase().includes('column')) && typeof c[k] === 'number');
                    return {
                        row: rowKey ? c[rowKey] : null,
                        col: colKey ? c[colKey] : null,
                        rowKey: rowKey,
                        colKey: colKey
                    };
                });
                return {id: i, sum: cage.sum, cells: cells};
            });
        }""")
        for cage in cages[:5]:
            cells_str = ", ".join(f"({c['row']},{c['col']})" for c in cage['cells'])
            print(f"  Klec {cage['id']:2d}: sum={cage['sum']:2d}, buňky=[{cells_str}]")
            if cage['id'] == 0:
                print(f"    rowKey={cage['cells'][0]['rowKey']}, colKey={cage['cells'][0]['colKey']}")

        # Pokud row/col stále None, zkus index-based approach
        print("\n=== Fallback: cage map z _cells ===")
        cage_map = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            const result = [];
            for (const cage of board._cages) {
                const cellPositions = [];
                for (const cageCell of cage.cells) {
                    // Najdi pozici buňky v _cells mřížce
                    for (let r = 0; r < board.size; r++) {
                        for (let c = 0; c < board.size; c++) {
                            if (board._cells[r][c] === cageCell) {
                                cellPositions.push({row: r, col: c});
                            }
                        }
                    }
                }
                result.push({sum: cage.sum, cells: cellPositions});
            }
            return result;
        }""")
        for i, cage in enumerate(cage_map):
            cells_str = ", ".join(f"({c['row']},{c['col']})" for c in cage['cells'])
            print(f"  Klec {i:2d}: sum={cage['sum']:2d}, buňky=[{cells_str}]")

        # Ověření součtů
        print("\n=== Ověření součtů ===")
        solution = await page.evaluate("() => DKS.puzzle.solution._values")
        for i, cage in enumerate(cage_map):
            total = sum(solution[c['row']][c['col']] for c in cage['cells'])
            ok = "✓" if total == cage['sum'] else "✗"
            print(f"  Klec {i:2d}: sum={cage['sum']:2d}, actual={total:2d} {ok}")

        await browser.close()


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