"""Behave steps for reactive routing and route bridge (actor-first)."""

from __future__ import annotations

from behave import given, then, when

from cleveragents.reactive.route import BridgeConfig, RouteConfig, RouteType
from cleveragents.reactive.route_bridge import RouteBridge
from cleveragents.reactive.stream_router import (
    ReactiveStreamRouter,
    StreamConfig,
    StreamType,
)


@given("a reactive stream router")
def step_stream_router(context):
    context.stream_router = ReactiveStreamRouter()


@given("a dummy actor registry")
def step_dummy_registry(context):
    class DummyActor:
        def __init__(self, name: str):
            self.name = name

        def process_message_sync(self, message, metadata=None):
            return f"processed:{message}"

        def get_capabilities(self):
            return []

    class DummyRegistry:
        def list_actors(self):
            return [DummyActor("dummy")]

    context.actor_registry = DummyRegistry()


@when('I create a cold stream named "{name}"')
def step_create_cold_stream(context, name):
    config = StreamConfig(name=name, type=StreamType.COLD)
    context.stream_router.create_stream(config)


@when('I send message "{message}" to stream "{name}"')
def step_send_message(context, message, name):
    context.stream_router.send_message(name, message)


@then('the stream "{name}" should exist')
def step_stream_exists(context, name):
    assert name in context.stream_router.streams


@when("I create a route bridge")
def step_create_route_bridge(context):
    context.route_bridge = RouteBridge(context.stream_router, context.actor_registry)


@then('the route bridge should include agent "{name}"')
def step_bridge_has_agent(context, name):
    assert name in context.route_bridge.agents


@given('a stream route config named "{name}" with a map agent operator')
def step_stream_route_config(context, name):
    context.route_config = RouteConfig(
        name=name,
        type=RouteType.STREAM,
        operators=[{"type": "map", "params": {"agent": "dummy"}}],
        subscriptions=[],
        publications=[],
        agents=["dummy"],
        bridge=BridgeConfig(),
    )


@when("I convert the stream route to a graph config")
def step_convert_route(context):
    from cleveragents.reactive.route_bridge import RouteBridge

    bridge = RouteBridge(context.stream_router, context.actor_registry)
    graph_cfg = bridge._create_graph_from_stream(context.route_config)  # pylint: disable=protected-access
    context.graph_config = graph_cfg


@then("the graph config should contain nodes")
def step_graph_has_nodes(context):
    assert getattr(context, "graph_config", None) is not None
    assert context.graph_config.nodes
