"""Rich console instance and output helpers.

All UX output goes to stderr; stdout is reserved for machine-readable data.
Every helper respects the ``quiet`` flag except :func:`print_error`, which
always prints because errors should never be silenced.

Color is disabled automatically when:
- The ``NO_COLOR`` environment variable is set (https://no-color.org)
- The ``--no-color`` CLI flag is passed
- Output is not a TTY (Rich's built-in detection)
"""

from __future__ import annotations

import os
from contextlib import contextmanager
from typing import TYPE_CHECKING

from rich.console import Console
from rich.panel import Panel
from rich.rule import Rule
from rich.table import Table

if TYPE_CHECKING:
    from collections.abc import Iterator

# Respect NO_COLOR env var (https://no-color.org) at startup.
_no_color: bool = bool(os.environ.get("NO_COLOR", ""))

# Shared console bound to stderr — all informational output goes here.
err_console = Console(stderr=True, no_color=_no_color)


def reconfigure(no_color: bool) -> None:
    """Recreate the module-level consoles with updated color settings.

    Called early in the CLI callback when ``--no-color`` is passed so that
    all subsequent output through the helper functions respects the flag.
    Direct ``err_console`` references in command modules are not affected,
    but all print_* helpers in this module will use the new console.
    """
    global err_console
    err_console = Console(stderr=True, no_color=no_color)


def print_banner(banner: str, quiet: bool) -> None:
    """Print the ASCII art banner unless quiet mode is active."""
    if not quiet:
        err_console.print(banner, style="bold blue")


def print_status(message: str, quiet: bool) -> None:
    """Print a status message to stderr unless quiet mode is active."""
    if not quiet:
        err_console.print(f"  [dim]→[/dim] {message}")


def print_success(message: str, quiet: bool) -> None:
    """Print a success message to stderr unless quiet mode is active."""
    if not quiet:
        err_console.print(f"  [green]✓[/green] {message}")


def print_error(message: str) -> None:
    """Print an error panel to stderr. Errors always print regardless of quiet mode."""
    err_console.print(Panel(message, title="[red]Error[/red]", border_style="red"))


def print_table(title: str, columns: list[str], rows: list[list[str]]) -> None:
    """Print a Rich table to stderr. Used by list-models, config, list-secrets."""
    table = Table(title=title)
    for col in columns:
        table.add_column(col)
    for row in rows:
        table.add_row(*row)
    err_console.print(table)


def print_rule(quiet: bool) -> None:
    """Print a horizontal rule to stderr unless quiet mode is active."""
    if not quiet:
        err_console.print(Rule(style="dim"))


@contextmanager
def spinner(message: str, quiet: bool) -> Iterator[None]:
    """Show a Rich spinner while a block executes.

    In quiet mode the spinner is suppressed entirely.
    """
    if quiet:
        yield
    else:
        with err_console.status(f"  {message}", spinner="dots"):
            yield
