"""
Essence Wars - High-performance card game environment for RL research.

This package provides:
- PyGame: Single game wrapper for Python
- PyParallelGames: Batched environments for vectorized training
- Gymnasium-compatible environments (optional)
- PettingZoo-compatible multi-agent environments (optional)

Submodules:
- essence_wars.agents: PPO and AlphaZero agent implementations
- essence_wars.benchmark: Standardized evaluation API
- essence_wars.data: Dataset loading utilities
- essence_wars.transformer: Game Transformer (Phase 6)

Quick Start:
    from essence_wars import PyGame

    game = PyGame()
    game.reset(seed=42)

    obs = game.observe()        # numpy array (328,)
    mask = game.action_mask()   # numpy array (422,)

    action = 421  # EndTurn action
    reward, done = game.step(action)

With Gymnasium:
    import essence_wars  # registers EssenceWars-v0 with gymnasium
    import gymnasium as gym

    env = gym.make("EssenceWars-v0")
    obs, info = env.reset(seed=42)
    obs, reward, terminated, truncated, info = env.step(action)
"""

from importlib.metadata import PackageNotFoundError, version

try:
    __version__ = version("essence-wars")
except PackageNotFoundError:
    # Package not installed (development mode or editable install)
    __version__ = "0.8.8"

# Import core Rust bindings
try:
    from essence_wars._core import (
        ACTION_SPACE_SIZE,
        STATE_TENSOR_SIZE,
        PyGame,
        PyParallelGames,
    )
except ImportError as e:
    raise ImportError(
        "Failed to import Rust bindings. "
        "Make sure you installed the package with: pip install essence-wars\n"
        f"Original error: {e}"
    ) from e

# Convenience function to list available decks
def list_decks() -> list[str]:
    """List all available deck names."""
    result: list[str] = PyGame.list_decks()
    return result

__all__ = [
    "ACTION_SPACE_SIZE",
    # Constants
    "STATE_TENSOR_SIZE",
    # Core classes
    "PyGame",
    "PyParallelGames",
    # Version
    "__version__",
    # Functions
    "list_decks",
]

# Register Gymnasium environments so gym.make("EssenceWars-v0") works
# after `import essence_wars` (standard pattern for third-party gym envs).
import gymnasium as gym  # noqa: E402

try:
    gym.register(
        id="EssenceWars-v0",
        entry_point="essence_wars.env:EssenceWarsEnv",
        kwargs={
            "deck1": "artificer_tokens",
            "deck2": "broodmother_pack",
            "opponent": "greedy",
            "game_mode": "attrition",
        },
    )
    gym.register(
        id="EssenceWarsSelfPlay-v0",
        entry_point="essence_wars.env:EssenceWarsSelfPlayEnv",
        kwargs={
            "deck1": "artificer_tokens",
            "deck2": "broodmother_pack",
            "game_mode": "attrition",
        },
    )
except gym.error.Error:
    # Already registered (happens on reimport)
    pass

# Lazy imports for optional modules to avoid import errors when dependencies missing
def __getattr__(name: str) -> object:
    """Lazy import for optional modules."""
    if name == "EssenceWarsEnv":
        from essence_wars.env import EssenceWarsEnv
        return EssenceWarsEnv
    elif name == "EssenceWarsSelfPlayEnv":
        from essence_wars.env import EssenceWarsSelfPlayEnv
        return EssenceWarsSelfPlayEnv
    elif name == "make_env":
        from essence_wars.env import make_env
        return make_env
    elif name == "VectorizedEssenceWars":
        from essence_wars.env import VectorizedEssenceWars
        return VectorizedEssenceWars
    elif name == "EssenceWarsParallelEnv":
        from essence_wars.parallel_env import EssenceWarsParallelEnv
        return EssenceWarsParallelEnv
    elif name == "parallel_env":
        from essence_wars.parallel_env import parallel_env
        return parallel_env
    raise AttributeError(f"module 'essence_wars' has no attribute {name!r}")
