"""Command handler for special commands"""

from typing import Dict, Callable, Any


class CommandHandler:
    """Command handler for processing special commands"""
    
    def __init__(self, config_manager, session_manager, tool_manager, interface_manager):
        """Initialize command handler
        
        Args:
            config_manager: Configuration manager
            session_manager: Session manager
            tool_manager: Tool manager
            interface_manager: Interface manager
        """
        self.config_manager = config_manager
        self.session_manager = session_manager
        self.tool_manager = tool_manager
        self.interface_manager = interface_manager
        self.commands = self._register_commands()
    
    def _register_commands(self) -> Dict[str, Callable]:
        """Register available commands
        
        Returns:
            Dictionary of command names to handler functions
        """
        return {
            'help': self._handle_help,
            'clear': self._handle_clear,
            'model': self._handle_model,
            'sessions': self._handle_sessions,
            'new': self._handle_new_session,
            'switch': self._handle_switch_session,
            'export': self._handle_export,
            'tools': self._handle_tools,
            'agent': self._handle_agent,
            'exit': self._handle_exit
        }
    
    def handle_command(self, command: str) -> bool:
        """Handle a command
        
        Args:
            command: Command string
            
        Returns:
            True if command was handled, False otherwise
        """
        # Split command into parts
        parts = command.strip().split()
        if not parts:
            return False
        
        cmd_name = parts[0].lower()
        args = parts[1:]
        
        if cmd_name in self.commands:
            self.commands[cmd_name](*args)
            return True
        return False
    
    def _handle_help(self, *args):
        """Handle /help command"""
        self.interface_manager.render_help()
    
    def _handle_clear(self, *args):
        """Handle /clear command"""
        self.session_manager.clear_history()
        self.interface_manager.display_success("History cleared.")
    
    def _handle_model(self, *args):
        """Handle /model command"""
        if args:
            model = args[0]
            self.config_manager.update_model(model)
            self.interface_manager.display_success(f"Switched to model: {model}")
        else:
            current_model = self.config_manager.get_ai_config().get('model')
            self.interface_manager.display_info(f"Current model: {current_model}")
    
    def _handle_sessions(self, *args):
        """Handle /sessions command"""
        sessions = self.session_manager.list_sessions()
        if not sessions:
            self.interface_manager.display_info("No sessions found.")
            return
        
        self.interface_manager.console.print("Sessions:", style="cyan bold")
        for session in sessions:
            status = "[*]" if session['is_current'] else "[ ]"
            self.interface_manager.console.print(f"{status} {session['name']} (ID: {session['session_id']}) - {session['message_count']} messages")
    
    def _handle_new_session(self, *args):
        """Handle /new command"""
        name = " ".join(args) if args else "New Session"
        session = self.session_manager.create_session(name)
        self.interface_manager.display_success(f"Created new session: {name}")
    
    def _handle_switch_session(self, *args):
        """Handle /switch command"""
        if not args:
            self.interface_manager.display_error("Please provide session ID")
            return
        
        session_id = args[0]
        session = self.session_manager.switch_session(session_id)
        if session:
            self.interface_manager.display_success(f"Switched to session: {session.name}")
        else:
            self.interface_manager.display_error(f"Session not found: {session_id}")
    
    def _handle_export(self, *args):
        """Handle /export command"""
        format = args[0] if args else "json"
        if format not in ["json", "markdown"]:
            self.interface_manager.display_error("Invalid format. Use 'json' or 'markdown'")
            return
        
        content = self.session_manager.export_session(format)
        if content:
            if format == "json":
                self.interface_manager.console.print(content)
            else:
                self.interface_manager.display_markdown(content)
        else:
            self.interface_manager.display_error("No session to export")
    
    def _handle_tools(self, *args):
        """Handle /tools command"""
        tools = self.tool_manager.get_available_tools()
        if not tools:
            self.interface_manager.display_info("No tools available.")
            return
        
        self.interface_manager.console.print("Available tools:", style="cyan bold")
        for tool_name in tools:
            description = self.tool_manager.get_tool_description(tool_name)
            self.interface_manager.console.print(f"- {tool_name}: {description}")
    
    def _handle_agent(self, *args):
        """Handle /agent command"""
        # Toggle agent mode (implementation depends on how agent mode is stored)
        self.interface_manager.display_info("Agent mode toggled")
    
    def _handle_exit(self, *args):
        """Handle /exit command"""
        self.interface_manager.display_success("Goodbye!")
        exit(0)
