"""Output formatting — tables, colors, spinners, syntax highlighting."""

from __future__ import annotations

import json as _json
from contextlib import contextmanager
from typing import Any, Generator

from rich.console import Console
from rich.syntax import Syntax
from rich.table import Table

console = Console()
err_console = Console(stderr=True)


def success(msg: str) -> None:
    console.print(f"[bold green]\u2705 {msg}[/]")


def error(msg: str) -> None:
    err_console.print(f"[bold red]\u274c {msg}[/]")


def warning(msg: str) -> None:
    console.print(f"[bold yellow]\u26a0\ufe0f  {msg}[/]")


def info(msg: str) -> None:
    console.print(f"[blue]\U0001f4a1 {msg}[/]")


@contextmanager
def spinner(msg: str) -> Generator[None, None, None]:
    """Animated spinner via rich.status."""
    with console.status(f"[bold cyan]{msg}[/bold cyan]"):
        yield


def json_output(data: Any) -> None:
    """Pretty-print JSON with syntax highlighting."""
    raw = _json.dumps(data, indent=2, ensure_ascii=False, default=str)
    console.print(Syntax(raw, "json", theme="monokai", word_wrap=True))


# Legacy alias — used in existing code
def json(data: Any) -> None:
    json_output(data)


def table(rows: list[dict], columns: list[str] | None = None) -> None:
    if not rows:
        info("Нет результатов.")
        return
    cols = columns or list(rows[0].keys())
    t = Table(show_lines=False, expand=False, pad_edge=True)
    for c in cols:
        t.add_column(c, style="cyan", header_style="bold cyan")
    for row in rows:
        t.add_row(*(str(row.get(c, "")) for c in cols))
    console.print(t)
