"""CLI core implementation"""

from diona.project.cli.core.executor_core import get_executor_core, CLIConstants


class CLI:
    """CLI core class"""

    def __init__(self):
        self.running = False
        self._executor_core = get_executor_core()

    def run(self):
        """Run CLI"""
        from diona.project.cli.ui import UI
        
        self.running = True
        UI.display_banner()
        self.load_commands()

        self._executor_core.set_mode(CLIConstants.MODE_CLIENT)

        while self.running:
            prompt = UI.get_prompt(not self._executor_core.is_default_mode())
            try:
                user_input = input(prompt)
                if not user_input.strip():
                    continue

                self._execute(user_input)
            except KeyboardInterrupt:
                if not self._executor_core.is_default_mode():
                    print("\nUse $exit to exit current mode")
                    continue
                print("\nExiting...")
                self.running = False
            except EOFError:
                print("\nExiting...")
                self.running = False

        print("Goodbye!")

    def _execute(self, user_input: str) -> bool:
        """Execute user input

        Args:
            user_input: User input

        Returns:
            True if should exit
        """
        self._executor_core.execute_sync(user_input)
        return False

    def load_commands(self):
        """Load commands"""
        try:
            from diona.project.command import CommandRegistry
            registry = CommandRegistry()
        except Exception as e:
            print(f"Error loading commands: {e}")

        try:
            from diona.project.agent.sub.test import register_test_agent
            agent = register_test_agent()
            from diona.project.agent import get_sub_agent_registry
            r = get_sub_agent_registry()
            print(f"Loaded sub-agents: {[a.name for a in r.list_all()]}")
        except Exception as e:
            import traceback
            print(f"Error loading sub-agents: {e}")
            traceback.print_exc()
