"""Console UI implementation"""

import sys
import time
from typing import Generator, Optional
from rich.console import Console
from rich.markdown import Markdown
from rich.spinner import Spinner
from rich.panel import Panel
from rich.text import Text
from diona.ai.client.simplecli.ui.styles import default_theme


class InterfaceManager:
    """Interface manager for user interaction and output"""
    
    def __init__(self):
        """Initialize interface manager"""
        self.console = Console()
        self.theme = default_theme
    
    def render_welcome(self, version: str):
        """Display welcome screen
        
        Args:
            version: Version string
        """
        welcome_text = Text(f"Welcome to Simple AI CLI Client v{version}", style="cyan bold")
        welcome_text.append("\n", style="reset")
        welcome_text.append("Type /help for available commands", style="green")
        welcome_text.append("\n", style="reset")
        welcome_text.append("Type /exit to quit", style="green")
        
        panel = Panel(welcome_text, title="Simple AI CLI", border_style="cyan")
        self.console.print(panel)
        self.console.print()
    
    def render_help(self):
        """Display help information"""
        help_text = Text("Available commands:\n", style="cyan bold")
        help_text.append("/help             ", style="green")
        help_text.append("- Show this help message\n", style="reset")
        help_text.append("/clear            ", style="green")
        help_text.append("- Clear current session history\n", style="reset")
        help_text.append("/model [model]    ", style="green")
        help_text.append("- Switch to a different model\n", style="reset")
        help_text.append("/sessions         ", style="green")
        help_text.append("- List all sessions\n", style="reset")
        help_text.append("/new [name]       ", style="green")
        help_text.append("- Create a new session\n", style="reset")
        help_text.append("/switch [id]      ", style="green")
        help_text.append("- Switch to a different session\n", style="reset")
        help_text.append("/export [format]  ", style="green")
        help_text.append("- Export current session (json or markdown)\n", style="reset")
        help_text.append("/tools            ", style="green")
        help_text.append("- List available tools\n", style="reset")
        help_text.append("/agent            ", style="green")
        help_text.append("- Toggle AI agent mode\n", style="reset")
        help_text.append("/exit             ", style="green")
        help_text.append("- Exit the application\n", style="reset")
        
        panel = Panel(help_text, title="Help", border_style="cyan")
        self.console.print(panel)
    
    def get_input(self, prompt: str = "> ") -> str:
        """Get user input
        
        Args:
            prompt: Input prompt
            
        Returns:
            User input string
        """
        try:
            return input(prompt)
        except KeyboardInterrupt:
            self.console.print("\nExiting...", style="yellow")
            sys.exit(0)
    
    def display_markdown(self, text: str):
        """Render Markdown text
        
        Args:
            text: Markdown text to render
        """
        markdown = Markdown(text)
        self.console.print(markdown)
    
    def stream_display(self, generator: Generator[str, None, None]):
        """Stream display AI response with typewriter effect
        
        Args:
            generator: Generator yielding response chunks
        """
        try:
            for chunk in generator:
                print(chunk, end="", flush=True)
            print()  # New line at the end
        except KeyboardInterrupt:
            self.console.print("\nGeneration interrupted.", style="yellow")
    
    def display_error(self, message: str):
        """Display error message
        
        Args:
            message: Error message
        """
        self.console.print(f"[red]Error:[/red] {message}")
    
    def display_warning(self, message: str):
        """Display warning message
        
        Args:
            message: Warning message
        """
        self.console.print(f"[yellow]Warning:[/yellow] {message}")
    
    def display_info(self, message: str):
        """Display info message
        
        Args:
            message: Info message
        """
        self.console.print(f"[blue]Info:[/blue] {message}")
    
    def display_success(self, message: str):
        """Display success message
        
        Args:
            message: Success message
        """
        self.console.print(f"[green]Success:[/green] {message}")
    
    def show_spinner(self, text: str, duration: Optional[float] = None):
        """Show loading spinner
        
        Args:
            text: Spinner text
            duration: Duration to show spinner (None for indefinite)
        """
        if duration:
            end_time = time.time() + duration
            with self.console.status(text, spinner="dots"):
                while time.time() < end_time:
                    time.sleep(0.1)
        else:
            return self.console.status(text, spinner="dots")
    
    def display_tool_execution(self, tool_name: str):
        """Display tool execution message
        
        Args:
            tool_name: Name of the tool being executed
        """
        self.console.print(f"[cyan][Tool] Executing {tool_name}...[/cyan]")
    
    def display_tool_result(self, result: str):
        """Display tool execution result
        
        Args:
            result: Tool execution result
        """
        self.console.print(f"[green][Tool Result] {result}[/green]")
    
    def display_agent_message(self, message: str):
        """Display agent message
        
        Args:
            message: Agent message
        """
        self.console.print(f"[magenta][Agent] {message}[/magenta]")
