from __future__ import annotations

import pytest

from agent_framework.runtime.agent_runtime import AgentRuntimeMixin


class _Observer:
    def __init__(self):
        self.events = []

    async def emit(self, code, payload=None, **kwargs):
        self.events.append((code, payload, kwargs))


class _Runtime(AgentRuntimeMixin):
    name = "test_agent"

    def __init__(self):
        self.observer = _Observer()


@pytest.mark.asyncio
async def test_business_events_are_published_recursively_once():
    runtime = _Runtime()
    state = {"session_id": "s1", "intent": "x", "route": "test_agent"}
    result = {
        "ok": True,
        "cached": False,
        "result": {
            "nodes": {
                "a": {"business_events": ["RCT.001", {"code": "CVN.002", "payload": {"x": 1}}]},
                "b": {"business_events": ["RCT.001"]},
            }
        },
    }
    await runtime._publish_business_events(result, state)
    codes = [event[0] for event in runtime.observer.events]
    assert codes == ["RCT.001", "CVN.002"]


@pytest.mark.asyncio
async def test_cached_tool_result_does_not_republish_business_events():
    runtime = _Runtime()
    await runtime._publish_business_events(
        {"cached": True, "business_events": ["RCT.001"]}, {"session_id": "s1"}
    )
    assert runtime.observer.events == []
