"""Adapter to load actors into the reactive stream router and route bridge."""

from __future__ import annotations

from typing import Any

from cleveragents.reactive.route_bridge import RouteBridge
from cleveragents.reactive.stream_router import ReactiveStreamRouter


def register_registry_agents(
    stream_router: ReactiveStreamRouter, route_bridge: RouteBridge, actor_registry: Any
) -> None:
    """Register actors from ActorRegistry into the router/route bridge.

    This expects actor_registry to expose list_actors() and get_actor(name).
    Each actor is injected as a callable via process_message_sync if present;
    otherwise skips.
    """
    try:
        actors = actor_registry.list_actors()  # type: ignore[attr-defined]
    except Exception:
        return

    for actor in actors or []:
        # Prefer synchronous processing if available
        if hasattr(actor, "process_message_sync") or hasattr(actor, "process_message"):
            stream_router.register_agent(actor.name, actor)

    # RouteBridge caches agents as a dict; refresh it
    if hasattr(route_bridge, "agents"):
        try:
            route_bridge.agents = {a.name: a for a in actors}
        except Exception:
            route_bridge.agents = {}
