"""Utility functions for OpenClaw Sandbox CLI."""

import subprocess
import sys

from rich.console import Console
from rich.panel import Panel

from .output import is_json_mode

console = Console()
error_console = Console(stderr=True)
quiet_console = Console(quiet=True)


def get_console() -> Console:
    """Return a quiet console in JSON mode, normal console otherwise."""
    return quiet_console if is_json_mode() else console


def print_success(message: str):
    """Print a success message."""
    if is_json_mode():
        return
    console.print(f"[green]\u2713[/green] {message}")


def print_error(message: str):
    """Print an error message."""
    if is_json_mode():
        return
    error_console.print(f"[red]\u2717[/red] {message}")


def print_info(message: str):
    """Print an info message."""
    if is_json_mode():
        return
    console.print(f"[blue]\u2139[/blue] {message}")


def print_warning(message: str):
    """Print a warning message."""
    if is_json_mode():
        return
    error_console.print(f"[yellow]\u26a0[/yellow] {message}")


def print_panel(title: str, content: str):
    """Print a rich panel."""
    if is_json_mode():
        return
    console.print(Panel(content, title=title, border_style="blue"))


def run_shell(cmd: str, check: bool = True, capture: bool = True) -> subprocess.CompletedProcess:
    """Run a shell command and return the result."""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            check=check,
            capture_output=capture,
            text=True,
        )
        return result
    except subprocess.CalledProcessError as e:
        print_error(f"Command failed: {cmd}")
        if e.stdout:
            console.print(e.stdout)
        if e.stderr:
            error_console.print(e.stderr)
        if check:
            sys.exit(1)
        return e
