import json
from typing import Any, Callable, Optional

from rich.console import Console

from sunwaee.config import is_machine_caller

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


def success(data: Any, human_fn: Optional[Callable] = None) -> None:
    if is_machine_caller():
        print(json.dumps({"ok": True, "data": data}, default=str))
    elif human_fn:
        human_fn()


def error(message: str, code: str, exit_code: int = 1) -> None:
    if is_machine_caller():
        print(json.dumps({"ok": False, "error": message, "code": code}))
    else:
        err_console.print(f"[bold red]Error:[/bold red] {message}")
    raise SystemExit(exit_code)


def info(message: str) -> None:
    """Print an informational message to human callers only."""
    if not is_machine_caller():
        console.print(message)
