import asyncio
from evenage.core import AgentConfig, EvenAgeConfig
from evenage.core.agent_runtime import Agent


class ResponderAgent(Agent):
    def plan(self, task: dict) -> list[dict]:
        return [{"action": "tool", "name": "_respond", "params": {"value": task.get("value", 0)}}]

    async def _execute_tool_step(self, step: dict, context: dict):
        # inline simple tool
        return {"echo": step["params"]["value"]}


def test_delegation_memory_bus():
    cfg = EvenAgeConfig(queue_backend="memory", db_backend="sqlite", database_url="sqlite:///:memory:")
    a_cfg = AgentConfig(name="caller", role="Caller", goal="Delegate")
    b_cfg = AgentConfig(name="responder", role="Responder", goal="Respond")

    caller = Agent(a_cfg, cfg)
    responder = ResponderAgent(b_cfg, cfg)

    async def run():
        await caller.connect_bus()
        await responder.connect_bus()

        # publish a task to responder
        task_id = await caller.delegate("responder", {"value": 42})

        # emulate worker consuming and responding
        tasks = await responder.bus.consume_tasks("responder", block_ms=0, count=1)
        assert len(tasks) == 1
        result = await responder.handle(tasks[0]["payload"])
        await responder.bus.publish_response(task_id, result)

        # caller waits for response
        response = await caller.bus.wait_for_response(task_id, timeout_sec=2)
        assert response is not None
        assert response.get("status") == "success"

    asyncio.run(run())
