"""Structured event stream for the HUD.

When EMIT_JSON=1, every notable engine event is also printed to stdout as
a machine-parseable line:  @@EVT {"type": ..., ...}
The HUD spawns the engine with this env and tails stdout. Human-readable
prints stay as they are, so terminal use is unchanged.

Agent status bar: task_started / task_done events are also forwarded to
the terminal agent registry so a live AGENTS line appears in the console
regardless of whether the HUD is running.
"""

from __future__ import annotations

import json
import os

_ON = os.environ.get("EMIT_JSON") == "1"

# Lazy import to avoid circular deps — agent_registry imports nothing from voice
_registry = None


def _get_registry():
    global _registry
    if _registry is None:
        from voice.agent_registry import registry  # noqa: PLC0415
        _registry = registry
    return _registry


def emit(event_type: str, **data) -> None:
    # Always update the terminal agent status bar, HUD or not
    if event_type == "task_started":
        _get_registry().add(
            agent_type=data.get("agent", "worker"),
            desc=data.get("desc", "task"),
            task_id=data.get("id", ""),
        )
    elif event_type == "task_done":
        _get_registry().finish_one(task_id=data.get("id", ""))
    elif event_type == "task_progress":
        # live "what is it doing right now" note from the agent pool's reader
        _get_registry().progress(data.get("id", ""), data.get("note", ""))
    elif event_type == "task_stalled":
        _get_registry().stalled(data.get("id", ""))

    if not _ON:
        return
    data["type"] = event_type
    print("@@EVT " + json.dumps(data, ensure_ascii=False), flush=True)
