"""Dialogue tree data model and TOML loading."""

import tomllib
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class DialogueChoice:
    """A player response option in a dialogue."""

    text: str
    next_node: str
    condition: str | None = None


@dataclass
class DialogueNode:
    """A single node in a dialogue tree."""

    id: str
    text: str
    choices: list[DialogueChoice] = field(default_factory=list)
    action: str | None = None


@dataclass
class DialogueTree:
    """A complete dialogue tree for an NPC."""

    npc_name: str
    root_node: str
    nodes: dict[str, DialogueNode] = field(default_factory=dict)


def load_dialogue(path: Path) -> DialogueTree:
    """Load a dialogue tree from a TOML file.

    Args:
        path: Path to the TOML file

    Returns:
        DialogueTree instance

    Raises:
        ValueError: If root_node or any next_node reference doesn't exist
    """
    with open(path, "rb") as f:
        data = tomllib.load(f)

    npc_name = data["npc_name"]
    root_node = data["root_node"]
    nodes: dict[str, DialogueNode] = {}

    # Parse all nodes
    for node_id, node_data in data.get("nodes", {}).items():
        choices = []
        for choice_data in node_data.get("choices", []):
            choices.append(
                DialogueChoice(
                    text=choice_data["text"],
                    next_node=choice_data["next_node"],
                    condition=choice_data.get("condition"),
                )
            )

        nodes[node_id] = DialogueNode(
            id=node_id,
            text=node_data["text"],
            choices=choices,
            action=node_data.get("action"),
        )

    # Validate root_node exists
    if root_node not in nodes:
        msg = f"root_node '{root_node}' not found in nodes"
        raise ValueError(msg)

    # Validate all next_node references exist
    for node in nodes.values():
        for choice in node.choices:
            if choice.next_node not in nodes:
                msg = f"next_node '{choice.next_node}' not found in nodes"
                raise ValueError(msg)

    return DialogueTree(npc_name=npc_name, root_node=root_node, nodes=nodes)


def load_all_dialogues(directory: Path) -> dict[str, DialogueTree]:
    """Load all dialogue trees from TOML files in a directory.

    Args:
        directory: Path to directory containing .toml files

    Returns:
        Dict mapping npc_name to DialogueTree instances
    """
    trees: dict[str, DialogueTree] = {}
    for path in sorted(directory.glob("*.toml")):
        tree = load_dialogue(path)
        trees[tree.npc_name] = tree
    return trees
