"""
Průzkumný skript v4: vytáhne klece (cages) z DKS.puzzle.board.
"""

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)

        # Klece
        print("\n=== Cages ===")
        cages = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            return board._cages.map((cage, i) => ({
                id: i,
                sum: cage.sum,
                cells: cage.cells.map(c => ({row: c._row, col: c._col}))
            }));
        }""")
        for cage in cages:
            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}]")

        # Řešení
        print("\n=== Řešení ===")
        solution = await page.evaluate("""() => {
            return DKS.puzzle.solution._values;
        }""")
        for r, row in enumerate(solution):
            print(f"  Řádek {r}: {row}")

        # Cage map — ověření
        print("\n=== Cage map (ověření) ===")
        cage_map = await page.evaluate("""() => {
            const board = DKS.puzzle.board;
            const map = [];
            for (let r = 0; r < board.size; r++) {
                const row = [];
                for (let c = 0; c < board.size; c++) {
                    const cell = board._cells[r][c];
                    const cageIdx = board._cages.indexOf(cell._cage);
                    row.push(cageIdx);
                }
                map.push(row);
            }
            return map;
        }""")
        for r, row in enumerate(cage_map):
            print(f"  {row}")

        # Ověření součtů
        print("\n=== Ověření součtů ===")
        for cage in cages:
            total = sum(solution[c['row']][c['col']] for c in cage['cells'])
            ok = "✓" if total == cage['sum'] else "✗"
            print(f"  Klec {cage['id']:2d}: sum={cage['sum']:2d}, actual={total:2d} {ok}")

        await browser.close()


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