"""
UI utilities for Nia CLI - ASCII art and spinners.
"""
from rich.console import Console
from rich.text import Text
from rich.panel import Panel
from contextlib import contextmanager
import random

console = Console()

NIA_LOGO_MINI = "[bold cyan]NIA[/bold cyan]"

# Spinner styles that look good
SPINNER_STYLES = [
    "dots",
    "dots2", 
    "dots3",
    "dots12",
    "line",
    "arc",
    "bouncingBar",
    "bouncingBall",
    "moon",
    "runner",
    "aesthetic",
]

# Action-specific spinners and messages
SPINNER_MESSAGES = {
    "login": ["Authenticating...", "Connecting to Nia...", "Verifying..."],
    "sync": ["Syncing...", "Uploading changes...", "Processing files..."],
    "search": ["Searching...", "Finding matches...", "Querying knowledge..."],
    "upgrade": ["Checking for updates...", "Upgrading...", "Installing..."],
    "fetch": ["Fetching...", "Loading data...", "Retrieving..."],
    "connect": ["Connecting...", "Establishing connection...", "Reaching server..."],
    "process": ["Processing...", "Working...", "Computing..."],
    "default": ["Working...", "Please wait...", "Processing..."],
}


def print_logo(subtitle: str | None = None, compact: bool = False):
    """Print the Nia header (no logo)."""
    pass


def print_header(title: str, subtitle: str | None = None):
    """Print a styled header with optional subtitle."""
    console.print(f"\n{NIA_LOGO_MINI} [bold cyan]{title}[/bold cyan]")
    if subtitle:
        console.print(f"  [dim]{subtitle}[/dim]")
    console.print()


@contextmanager
def spinner(action: str = "default", message: str | None = None, min_time: float = 0.4):
    """
    Context manager for showing a spinner during operations.
    
    Usage:
        with spinner("sync", "Syncing files..."):
            do_sync()
    """
    import time
    from rich.status import Status
    
    # Pick message
    if message is None:
        messages = SPINNER_MESSAGES.get(action, SPINNER_MESSAGES["default"])
        message = messages[0]
    
    # Pick a good spinner
    spinner_name = "dots"
    start_time = time.time()
    
    with Status(f"[bold cyan]{message}[/bold cyan]", spinner=spinner_name, console=console) as status:
        # Expose update method through a simple interface
        status._message = message
        yield status
        
        # Ensure spinner is visible for at least min_time
        elapsed = time.time() - start_time
        if elapsed < min_time:
            time.sleep(min_time - elapsed)


def update_spinner(status, message: str):
    """Update the spinner message."""
    status.update(f"[bold cyan]{message}[/bold cyan]")


def success(message: str, prefix: str = "✓"):
    """Print a success message."""
    console.print(f"[green]{prefix}[/green] {message}")


def error(message: str, prefix: str = "✗"):
    """Print an error message."""
    console.print(f"[red]{prefix}[/red] {message}")


def warning(message: str, prefix: str = "⚠"):
    """Print a warning message."""
    console.print(f"[yellow]{prefix}[/yellow] {message}")


def info(message: str, prefix: str = "•"):
    """Print an info message."""
    console.print(f"[cyan]{prefix}[/cyan] {message}")


def dim(message: str):
    """Print a dimmed message."""
    console.print(f"[dim]{message}[/dim]")


def print_welcome():
    """Print the welcome message."""
    console.print("[bold cyan]Nia Sync Engine[/bold cyan] — Keep local folders in sync with Nia cloud\n")
