"""Cleave TUI - Interactive terminal interface for task decomposition."""

from pathlib import Path

from textual.app import App

from cleave.core.settings import load_settings
from cleave.tui.screens.main import CleaveMainScreen
from cleave.tui.themes.registry import ThemeRegistry


class CleaveTUI(App):
    """Cleave TUI - Interactive task decomposition interface.

    A terminal UI for managing directives and executing them through the
    Claude Agent SDK with Cleave skill integration.
    """

    TITLE = "╔═══ CLEAVE ═══╗"
    SUB_TITLE = "∴ Recursive Task Decomposition ∴"

    def __init__(self, working_directory: Path | None = None):
        super().__init__()
        self.working_directory = working_directory or Path.cwd()

        # Initialize theme system
        self.theme_registry = ThemeRegistry()
        self.theme_registry.load_builtin_themes()
        self.theme_registry.load_user_themes()

        # Load theme from settings
        settings = load_settings()
        self._active_theme = settings.theme
        self._apply_theme(self._active_theme)

    def _apply_theme(self, theme_name: str) -> None:
        """Apply a theme to the app.

        Args:
            theme_name: Name of the theme to apply.
        """
        theme_data = self.theme_registry.get_theme(theme_name)
        if theme_data:
            self._active_theme = theme_name

    def cycle_theme(self) -> None:
        """Cycle to the next theme."""
        next_theme = self.theme_registry.get_next_theme(self._active_theme)
        self._apply_theme(next_theme)

        # Save theme preference
        from cleave.core.settings import save_settings
        settings = load_settings()
        settings.theme = next_theme
        save_settings(settings)

        # Notify user
        self.notify(f"Theme: {next_theme}")

    def on_mount(self) -> None:
        """Push the main screen on mount."""
        self.push_screen(CleaveMainScreen(working_directory=self.working_directory))


def main() -> None:
    """Run the Cleave TUI application."""
    app = CleaveTUI()
    app.run()


if __name__ == "__main__":
    main()
