"""Theme registry for managing available themes."""

from pathlib import Path
from typing import Any

from cleave.tui.themes.loader import ThemeLoader


def get_builtin_themes_dir() -> Path:
    """Get the directory containing built-in themes."""
    return Path(__file__).parent / "builtin"


def get_user_themes_dir() -> Path:
    """Get the user themes directory."""
    return Path.home() / ".cleave" / "themes"


class ThemeRegistry:
    """Registry for managing TUI themes.

    Handles loading built-in themes, user themes, and theme switching.
    """

    def __init__(self):
        """Initialize theme registry."""
        self.loader = ThemeLoader()
        self.themes: dict[str, dict[str, Any]] = {}

    def register_theme(self, name: str, theme_path: Path | None = None, theme_data: dict[str, Any] | None = None):
        """Register a theme.

        Args:
            name: Theme name.
            theme_path: Path to theme TCSS file (if loading from file).
            theme_data: Pre-loaded theme data (if already loaded).
        """
        if theme_data:
            self.themes[name] = theme_data
        elif theme_path:
            content = self.loader.load_theme_file(theme_path)
            if content:
                self.themes[name] = {
                    "name": name,
                    "content": content,
                }

    def load_builtin_themes(self):
        """Load all built-in themes."""
        builtin_dir = get_builtin_themes_dir()
        if not builtin_dir.exists():
            return

        for theme_file in builtin_dir.glob("*.tcss"):
            theme_name = theme_file.stem
            theme_data = self.loader.load_theme_with_metadata(builtin_dir, theme_name)
            if theme_data:
                self.themes[theme_name] = theme_data

    def load_user_themes(self):
        """Load themes from user directory (~/.cleave/themes/)."""
        user_dir = get_user_themes_dir()
        if not user_dir.exists():
            return

        for theme_file in user_dir.glob("*.tcss"):
            theme_name = theme_file.stem
            theme_data = self.loader.load_theme_with_metadata(user_dir, theme_name)
            if theme_data:
                self.themes[theme_name] = theme_data

    def get_theme(self, name: str) -> dict[str, Any] | None:
        """Get a theme by name.

        Args:
            name: Theme name.

        Returns:
            Theme data dictionary, or None if not found.
        """
        return self.themes.get(name)

    def list_themes(self) -> list[str]:
        """List all available theme names.

        Returns:
            List of theme names.
        """
        return list(self.themes.keys())

    def get_next_theme(self, current: str) -> str:
        """Get the next theme in the cycle.

        Args:
            current: Current theme name.

        Returns:
            Next theme name in alphabetical order, wrapping to start.
        """
        theme_names = sorted(self.list_themes())
        if not theme_names:
            return current

        if current not in theme_names:
            return theme_names[0]

        current_index = theme_names.index(current)
        next_index = (current_index + 1) % len(theme_names)
        return theme_names[next_index]
