"""Rich-based display helpers for streaming pi-rpc output."""

from __future__ import annotations

from rich.console import Console

_console = Console()


def stream_event(event: dict) -> None:
    """Print a pi-rpc event to the console as it arrives.

    Used as the on_event callback for PiRpcClient.prompt().
    """
    event_type = event.get("type")

    if event_type == "message_update":
        ame = event.get("assistantMessageEvent", {})
        if ame.get("type") == "text_delta":
            _console.print(ame.get("delta", ""), end="")

    elif event_type == "tool_execution_start":
        tool = event.get("toolName", "?")
        args = event.get("args", {})
        detail = ""
        if tool == "bash":
            cmd = args.get("command", "")
            # Show first 60 chars of command
            detail = f" {cmd[:60]}{'…' if len(cmd) > 60 else ''}"
        elif tool in ("read", "write", "edit"):
            path = args.get("file_path", args.get("path", ""))
            if path:
                detail = f" {path}"
        _console.print(f"\n[dim]> {tool}{detail}[/dim]", end="")

    elif event_type == "tool_execution_end":
        pass  # starts are enough — ends arrive out of order with parallel tool calls

    elif event_type in ("turn_end", "message_end"):
        msg = event.get("message", {})
        if msg.get("stopReason") == "error":
            error = msg.get("errorMessage", "Unknown error")
            _console.print(f"\n[bold red]Agent error: {error}[/bold red]")

    elif event_type == "agent_end":
        _console.print()  # final newline
