"""Personality registry — look up and activate voice overlays."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from alice_cli.personalities.base import Personality

_REGISTRY: dict[str, type[Personality]] = {}

# Active personality instance (module-level singleton).
_active: Personality | None = None


def register(name: str, cls: type[Personality]) -> None:
    """Register a personality class under *name* (lower-cased)."""
    _REGISTRY[name.lower()] = cls


def get_personality(name: str) -> Personality:
    """Instantiate and return a personality by name."""
    cls = _REGISTRY.get(name.lower())
    if cls is None:
        available = ", ".join(sorted(_REGISTRY))
        raise ValueError(f"Unknown personality '{name}'. Available: {available}")
    return cls()


def available_personalities() -> list[str]:
    """Return sorted list of registered personality names."""
    return sorted(_REGISTRY)


def get_active() -> Personality:
    """Return the currently active personality, defaulting to alice."""
    global _active
    if _active is None:
        _active = get_personality("alice")
    return _active


def set_active(name: str) -> Personality:
    """Set and return the active personality by name."""
    global _active
    _active = get_personality(name)
    return _active


# Auto-register built-in personalities on import.
from alice_cli.personalities.alice import AlicePersonality  # noqa: E402
from alice_cli.personalities.mr_rogers import MrRogersPersonality  # noqa: E402
from alice_cli.personalities.shodan import ShodanPersonality  # noqa: E402

register("alice", AlicePersonality)
register("mr_rogers", MrRogersPersonality)
register("shodan", ShodanPersonality)
