"""
Abstract base class for user interfaces.
"""

from abc import ABC, abstractmethod
from typing import Optional


class UserInterface(ABC):
    """Abstract base class for user I/O interfaces.
    
    Implement this class to create different ways to interact with the user,
    such as CLI, web UI, TCP/IP protocol, email, etc.
    """
    
    @abstractmethod
    def read_input(self, prompt: Optional[str] = None) -> str:
        """Read input from the user.
        
        Args:
            prompt: Optional prompt to display to the user.
            
        Returns:
            The user's input as a string.
        """
        pass
    
    @abstractmethod
    def write_output(self, text: str) -> None:
        """Write output to the user.
        
        Args:
            text: The text to display to the user.
        """
        pass
    
    @abstractmethod
    def write_error(self, text: str) -> None:
        """Write an error message to the user.
        
        Args:
            text: The error message to display.
        """
        pass
    
    @abstractmethod
    def write_info(self, text: str) -> None:
        """Write an informational message to the user.
        
        Args:
            text: The info message to display.
        """
        pass
    
    def run_session(self, agent, system_prompt: Optional[str] = None) -> None:
        """Run an interactive session with the agent.
        
        This is a default implementation that can be overridden by subclasses
        if they need different session handling (e.g., web, TCP, email).
        
        Args:
            agent: The OpenRouterAgent instance to use.
            system_prompt: Optional system prompt for the agent.
        """
        self.write_info("Starting interactive session. Type 'quit' to exit.")
        
        while True:
            try:
                user_input = self.read_input("\nYou: ")
                
                if user_input.lower() == "quit":
                    self.write_output("Goodbye!")
                    break
                elif user_input.lower() == "clear":
                    agent.clear_history()
                    self.write_output("Conversation history cleared.")
                    continue
                elif user_input.lower() == "history":
                    history = agent.get_conversation_history()
                    self.write_output("\nConversation History:")
                    for i, msg in enumerate(history):
                        role = msg.get("role", "unknown").upper()
                        content = msg.get("content", "")[:100]
                        if len(msg.get("content", "")) > 100:
                            content += "..."
                        self.write_output(f"{i+1}. [{role}]: {content}")
                    continue
                
                if not user_input.strip():
                    continue
                
                response = agent.run(
                    user_input=user_input,
                    system_prompt=system_prompt,
                    reset_conversation=False
                )
                
                self.write_output(response)
                
            except KeyboardInterrupt:
                self.write_output("\n\nInterrupted. Exiting...")
                break
            except Exception as e:
                self.write_error(f"An error occurred: {e}")