"""Data types for sprite animation state configuration."""

from dataclasses import dataclass, field
from typing import Any


@dataclass
class AnimationStateConfig:
    """Configuration for a single named animation state.

    Attributes:
        name: State name (e.g. "idle", "walk", "appear").
        directional: If True the state has per-direction variants (_up/_down/_left/_right).
        loop: If True the animation loops; if False it plays once then fires on_complete.
        priority: Higher value preempts lower-priority active states.
        on_complete: What to do when a non-looping animation finishes.
            "idle" — transition to the idle state.
            "hide" — set sprite.visible = False then transition to idle.
            None — do nothing (stay on the last frame).
        reverse_load: Load frames in reverse order from the sprite sheet (used by appear
            so that the sheet stores frames visible→invisible but playback is invisible→visible).
        auto_from: Name of another state whose already-loaded textures should be reversed
            to generate this state (e.g. disappear auto-generated from appear).
        frames: Frame count for non-directional states.
        row: Sprite sheet row for non-directional states.
        directions: Per-direction frame data for directional states.
            Shape: {"up": {"frames": N, "row": R}, "down": ..., ...}
            Missing counterpart in a left/right pair is auto-generated by flipping.
    """

    name: str
    directional: bool
    loop: bool
    priority: int
    on_complete: str | None = None
    reverse_load: bool = False
    auto_from: str | None = None
    frames: int | None = None
    row: int | None = None
    directions: dict[str, dict[str, int]] | None = field(default=None)

    @classmethod
    def from_dict(cls, name: str, data: dict[str, Any]) -> AnimationStateConfig:
        """Parse an AnimationStateConfig from a JSON-style dict.

        Args:
            name: State name (key in the parent states dict).
            data: Dict with keys directional, loop, priority and optional extras.

        Returns:
            Populated AnimationStateConfig instance.
        """
        directions: dict[str, dict[str, int]] | None = None
        if data.get("directional"):
            raw = data.get("directions", {})
            directions = {k: dict(v) for k, v in raw.items()} if raw else {}

        return cls(
            name=name,
            directional=bool(data["directional"]),
            loop=bool(data["loop"]),
            priority=int(data["priority"]),
            on_complete=data.get("on_complete"),
            reverse_load=bool(data.get("reverse_load", False)),
            auto_from=data.get("auto_from"),
            frames=data.get("frames"),
            row=data.get("row"),
            directions=directions,
        )
