"""Rich output helpers for the Sika CLI.

Provides console creation, JSON output, and status styling used
across all CLI commands.
"""

from __future__ import annotations

import json
from typing import TYPE_CHECKING, Any

from rich.console import Console

if TYPE_CHECKING:
    import typer

    from sika.recon.models import ScanStatus

# ---------------------------------------------------------------------------
# Console
# ---------------------------------------------------------------------------


def get_console(ctx: typer.Context) -> Console:
    """Return a Rich console respecting ``--no-color``.

    Args:
        ctx: Typer context carrying global options in ``ctx.obj``.
    """
    obj: dict[str, Any] = ctx.ensure_object(dict)
    return Console(no_color=obj.get("no_color", False))


def get_error_console(ctx: typer.Context) -> Console:
    """Return a Rich console for stderr output.

    Args:
        ctx: Typer context carrying global options in ``ctx.obj``.
    """
    obj: dict[str, Any] = ctx.ensure_object(dict)
    return Console(stderr=True, no_color=obj.get("no_color", False))


# ---------------------------------------------------------------------------
# JSON output
# ---------------------------------------------------------------------------


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

    Args:
        data: Any JSON-serialisable value (dict, list, str, etc.).
    """
    print(json.dumps(data, indent=2, default=str))


# ---------------------------------------------------------------------------
# Status styling
# ---------------------------------------------------------------------------

_STATUS_COLOURS: dict[str, str] = {
    "submitted": "cyan",
    "discovering": "yellow",
    "resolving": "yellow",
    "attributing": "yellow",
    "analyzing_history": "yellow",
    "analyzing_bgp": "yellow",
    "expanding_asns": "yellow",
    "analyzing_peering": "yellow",
    "detecting_scrubbing": "yellow",
    "analyzing_customers": "yellow",
    "scoring_resilience": "yellow",
    "completed": "green",
    "failed": "red",
}


def status_style(status: ScanStatus | str) -> str:
    """Return a Rich markup string for a scan status.

    Args:
        status: A :class:`~sika.recon.models.ScanStatus` or plain string.

    Returns:
        A Rich-styled string like ``[green]completed[/green]``.
    """
    value = str(status)
    colour = _STATUS_COLOURS.get(value, "white")
    return f"[{colour}]{value}[/{colour}]"
