"""CLI core implementation"""

import threading
from ..builtin import exit_command, help_command, time_command, date_command, list_commands_command
from .task import TaskManager
from .command import CommandHandler
from ..ui import UI


class CLI:
    """CLI core class"""
    def __init__(self):
        """Initialize CLI"""
        self.builtin_commands = {
            "exit": exit_command,
            "help": help_command,
            "time": time_command,
            "date": date_command,
            "list-commands": list_commands_command
        }
        self.task_manager = TaskManager()
        self.command_handler = CommandHandler()
        self.running = False
    
    def register_builtin_commands(self):
        """Register built-in commands"""
        pass
    
    def load_commands(self):
        """Load commands (already registered during registry initialization)"""
        def load_commands_task():
            try:
                # Commands are already registered during registry initialization
                from diona.project.command import CommandRegistry
                registry = CommandRegistry()
                # print("Commands loaded successfully")
            except Exception as e:
                print(f"Error loading commands: {e}")
        
        self.task_manager.register_task("load_commands", load_commands_task)
        self.task_manager.execute_task("load_commands")
    
    def parse_input(self, user_input):
        """Parse user input
        
        Args:
            user_input: User input
        
        Returns:
            bool: True if exit, False otherwise
        """
        user_input = user_input.strip()
        if not user_input:
            return False
        
        # Check if it's a built-in command
        if user_input.startswith("/"):
            command_name = user_input[1:].split()[0]
            args = user_input[1:].split()[1:]
            
            if command_name in self.builtin_commands:
                command = self.builtin_commands[command_name]
                return command.execute(args)
            else:
                UI.display_error(f"Built-in command '{command_name}' not found")
                return False
        else:
            # Execute diona command
            self.command_handler.execute_command(user_input)
            return False
    
    def run(self):
        """Run CLI"""
        self.running = True
        UI.display_banner()
        
        # Load commands in background
        self.load_commands()
        
        while self.running:
            UI.display_prompt()
            try:
                user_input = input()
                exit_flag = self.parse_input(user_input)
                if exit_flag:
                    self.running = False
            except KeyboardInterrupt:
                print("\nExiting...")
                self.running = False
            except EOFError:
                print("\nExiting...")
                self.running = False
        
        print("Goodbye!")


def run_cli():
    """Run CLI"""
    cli = CLI()
    cli.run()
