"""Centralized CLI error formatting utilities.

Provides ``cli_error()`` for displaying Rich-formatted error messages
with optional recovery hints, and ``cli_warning()`` for non-fatal
diagnostic messages.  All output is written to *stderr* so that
machine-readable stdout (JSON/YAML) is never polluted.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, NoReturn

from cleveragents.cli.constants import EXIT_ERROR

if TYPE_CHECKING:
    from rich.console import Console


def _get_err_console() -> Console:
    """Return the stderr Rich console (lazy import to reduce startup time)."""
    from cleveragents.cli.main import get_err_console

    return get_err_console()


def cli_error(
    message: str,
    *,
    hint: str | None = None,
    exit_code: int = EXIT_ERROR,
) -> NoReturn:
    """Display a standardized error message and exit.

    Parameters
    ----------
    message:
        A human-readable description of what went wrong.
    hint:
        An optional suggestion for how the user can fix the problem.
    exit_code:
        The process exit code (defaults to ``EXIT_ERROR``).

    Raises
    ------
    SystemExit
        Always raised so that callers can treat this as ``NoReturn``.
    """
    console = _get_err_console()
    console.print(f"[red bold]Error:[/] {message}")
    if hint:
        console.print(f"[dim]Hint: {hint}[/]")
    raise SystemExit(exit_code)


def cli_warning(message: str, *, hint: str | None = None) -> None:
    """Display a non-fatal warning message on stderr.

    Parameters
    ----------
    message:
        A human-readable description of the warning.
    hint:
        An optional suggestion for the user.
    """
    console = _get_err_console()
    console.print(f"[yellow bold]Warning:[/] {message}")
    if hint:
        console.print(f"[dim]Hint: {hint}[/]")


def cli_not_found(
    resource_type: str,
    name: str,
    *,
    cli_command: str | None = None,
) -> NoReturn:
    """Report a missing resource and exit.

    Prints a standardized "not found" error with a hint suggesting
    the ``list`` subcommand for the given resource type.

    Parameters
    ----------
    resource_type:
        Human-readable type label (e.g. ``"Project"``, ``"Automation Profile"``).
    name:
        The identifier the user supplied.
    cli_command:
        Optional CLI command name override.  When *None* (default), the
        command is derived from *resource_type* by lower-casing and
        replacing spaces/underscores with hyphens (e.g.
        ``"Automation Profile"`` -> ``"automation-profile"``).

    Raises
    ------
    SystemExit
        Always raised with exit code ``EXIT_NOT_FOUND``.
    """
    import re as _re

    from cleveragents.cli.constants import EXIT_NOT_FOUND

    if cli_command is None:
        cli_command = _re.sub(r"[\s_]+", "-", resource_type.lower())

    resource_plural = f"{resource_type.lower()}s"
    cli_error(
        f"{resource_type} '{name}' not found",
        hint=f"Run 'agents {cli_command} list' to see available {resource_plural}",
        exit_code=EXIT_NOT_FOUND,
    )


__all__ = [
    "cli_error",
    "cli_not_found",
    "cli_warning",
]
