"""Data model for opening trees."""

from __future__ import annotations

from dataclasses import dataclass, field

import chess


@dataclass
class OpeningNode:
    """A single node in an opening tree."""

    move: str  # SAN notation, e.g. "d4"
    explanation: str  # Why this move is played (empty for opponent moves)
    children: list[OpeningNode] = field(default_factory=list)


@dataclass
class Opening:
    """Metadata + tree for a complete opening."""

    name: str  # e.g. "London System"
    slug: str  # e.g. "london-system"
    color: chess.Color  # chess.WHITE or chess.BLACK
    description: str  # One-line description
    root: OpeningNode  # The tree root (first move)


def flatten_main_line(opening: Opening) -> list[tuple[str, str]]:
    """Walk children[0] down the tree, returning (san, explanation) pairs."""
    result: list[tuple[str, str]] = []
    node = opening.root
    while True:
        result.append((node.move, node.explanation))
        if not node.children:
            break
        node = node.children[0]
    return result


def validate_opening(opening: Opening) -> bool:
    """Replay the main line on a board to catch SAN typos."""
    board = chess.Board()
    for san, _ in flatten_main_line(opening):
        try:
            move = board.parse_san(san)
            board.push(move)
        except (chess.InvalidMoveError, chess.IllegalMoveError, chess.AmbiguousMoveError):
            return False
    return True
