"""REPL engine implementation"""

from typing import Optional
from diona.ai.client.simplecli.core.command import CommandHandler


class REPLEngine:
    """REPL loop engine for interactive chat"""
    
    def __init__(self, config_manager, provider_manager, session_manager, tool_manager, agent_system, interface_manager):
        """Initialize REPL engine
        
        Args:
            config_manager: Configuration manager
            provider_manager: Provider manager
            session_manager: Session manager
            tool_manager: Tool manager
            agent_system: AI agent system
            interface_manager: Interface manager
        """
        self.config_manager = config_manager
        self.provider_manager = provider_manager
        self.session_manager = session_manager
        self.tool_manager = tool_manager
        self.agent_system = agent_system
        self.interface_manager = interface_manager
        self.command_handler = CommandHandler(
            config_manager, session_manager, tool_manager, interface_manager
        )
        self.agent_mode = True  # Default to agent mode
    
    def start(self):
        """Start interactive REPL loop"""
        # Display welcome message
        from diona.ai.client.simplecli import __version__
        self.interface_manager.render_welcome(__version__)
        
        while True:
            try:
                # Get user input
                user_input = self.interface_manager.get_input()
                
                # Check for commands
                if user_input.startswith('/'):
                    # Handle command
                    self.command_handler.handle_command(user_input[1:])
                    continue
                
                # Add user message to session
                self.session_manager.add_user_message(user_input)
                
                # Get context
                context = self.session_manager.get_context()
                
                # Run AI agent or direct chat
                if self.agent_mode:
                    # Use agent system
                    response = ""
                    for chunk in self.agent_system.run_agent(context):
                        response += chunk
                        print(chunk, end="", flush=True)
                    print()  # New line at the end
                    self.session_manager.add_assistant_message(response)
                else:
                    # Use direct chat
                    ai_config = self.config_manager.get_ai_config()
                    response = ""
                    for chunk in self.provider_manager.chat_stream(
                        context,
                        ai_config.get('model'),
                        temperature=0.7
                    ):
                        response += chunk
                        print(chunk, end="", flush=True)
                    print()  # New line at the end
                    self.session_manager.add_assistant_message(response)
                
                # Display token count
                token_count = self.session_manager.get_token_count()
                self.interface_manager.display_info(f"Token count: {token_count}")
                
            except KeyboardInterrupt:
                self.interface_manager.display_warning("\nOperation interrupted.")
                continue
            except Exception as e:
                self.interface_manager.display_error(f"Error: {str(e)}")
                continue
    
    def run_single(self, prompt: str) -> str:
        """Run single prompt (non-interactive mode)
        
        Args:
            prompt: User prompt
            
        Returns:
            AI response
        """
        # Add user message
        self.session_manager.add_user_message(prompt)
        
        # Get context
        context = self.session_manager.get_context()
        
        # Run AI agent or direct chat
        if self.agent_mode:
            response = ""
            for chunk in self.agent_system.run_agent(context):
                response += chunk
        else:
            ai_config = self.config_manager.get_ai_config()
            response = ""
            for chunk in self.provider_manager.chat_stream(
                context,
                ai_config.get('model'),
                temperature=0.7
            ):
                response += chunk
        
        # Add assistant message
        self.session_manager.add_assistant_message(response)
        
        return response
    
    def set_agent_mode(self, mode: bool):
        """Set agent mode
        
        Args:
            mode: True for agent mode, False for direct chat
        """
        self.agent_mode = mode
