"""Output formatting utilities using Rich."""

from __future__ import annotations

import json
from typing import Any

from rich.console import Console
from rich.json import JSON
from rich.panel import Panel
from rich.table import Table
from rich.text import Text

# Global console instance
console = Console()

# Global quiet mode flag — set by cli.py callback
_quiet = False


def set_quiet(value: bool) -> None:
    """Enable or disable quiet mode globally."""
    global _quiet
    _quiet = value


def is_quiet() -> bool:
    """Return whether quiet mode is active."""
    return _quiet


def print_table(
    data: list[dict[str, Any]],
    columns: list[tuple[str, str]] | None = None,
    title: str | None = None,
    *,
    id_field: str | None = None,
) -> None:
    """Print data as a rich table.

    Args:
        data: List of dictionaries to display
        columns: List of (key, header) tuples. If None, uses dict keys.
        title: Optional table title
        id_field: In quiet mode, print only this field per row (one per line)
    """
    if not data:
        if not _quiet:
            console.print("[dim]No data to display[/dim]")
        return

    # Quiet mode: print only IDs, one per line
    if _quiet and id_field:
        for row in data:
            val = row.get(id_field, "")
            print(val if val is not None else "")
        return

    table = Table(title=title, show_header=True, header_style="bold cyan")

    # Determine columns
    if columns is None:
        columns = [(k, k.replace("_", " ").title()) for k in data[0].keys()]

    for _key, header in columns:
        # Prevent UUID columns from being truncated
        no_wrap = header.lower() in ("job id", "id")
        table.add_column(header, no_wrap=no_wrap)

    for row in data:
        values = []
        for key, _ in columns:
            value = row.get(key, "")
            if value is None:
                value = "-"
            elif isinstance(value, bool):
                value = "[green]Yes[/green]" if value else "[red]No[/red]"
            elif isinstance(value, dict | list):
                value = json.dumps(value, ensure_ascii=False)
            else:
                value = str(value)
            values.append(value)
        table.add_row(*values)

    console.print(table)


def print_json(data: Any) -> None:
    """Print data as formatted JSON.

    When output is piped (non-TTY), prints plain JSON to ensure valid output.
    When output is a terminal, uses Rich syntax highlighting.

    Args:
        data: Data to print as JSON
    """
    json_str = (
        data
        if isinstance(data, str)
        else json.dumps(data, ensure_ascii=False, indent=2, default=str)
    )
    if console.is_terminal:
        console.print(JSON(json_str))
    else:
        print(json_str)


def print_error(message: str, title: str = "Error") -> None:
    """Print an error message.

    Args:
        message: Error message to display
        title: Panel title
    """
    if _quiet:
        console.print(message, style="red", stderr=True)
    else:
        console.print(Panel(Text(message, style="red"), title=title, border_style="red"))


def print_success(message: str) -> None:
    """Print a success message.

    Args:
        message: Success message to display
    """
    if not _quiet:
        console.print(f"[green]{message}[/green]")


def print_warning(message: str) -> None:
    """Print a warning message.

    Args:
        message: Warning message to display
    """
    console.print(f"[yellow]{message}[/yellow]")


def print_info(message: str) -> None:
    """Print an info message.

    Args:
        message: Info message to display
    """
    if not _quiet:
        console.print(f"[cyan]{message}[/cyan]")


def print_key_value(data: dict[str, Any], title: str | None = None) -> None:
    """Print key-value pairs in a formatted way.

    Args:
        data: Dictionary of key-value pairs
        title: Optional title
    """
    if title:
        console.print(f"\n[bold]{title}[/bold]")

    max_key_len = max(len(str(k)) for k in data.keys()) if data else 0

    for key, value in data.items():
        if value is None:
            value = "[dim]-[/dim]"
        elif isinstance(value, bool):
            value = "[green]Yes[/green]" if value else "[red]No[/red]"
        elif isinstance(value, dict | list):
            value = json.dumps(value, ensure_ascii=False)

        key_display = str(key).replace("_", " ").title()
        console.print(f"  [cyan]{key_display:<{max_key_len + 2}}[/cyan] {value}")


def print_streaming_line(text: str, style: str = "") -> None:
    """Print a line for streaming output without newline.

    Args:
        text: Text to print
        style: Rich style to apply
    """
    if style:
        console.print(f"[{style}]{text}[/{style}]", end="")
    else:
        console.print(text, end="")
