from __future__ import annotations

import asyncio
import json

from app.livekit.adapters.bridge_gateway import BridgeGateway


class _Participant:
    def __init__(self) -> None:
        self.calls = []

    async def publish_data(self, payload, **kwargs) -> None:
        self.calls.append((json.loads(payload), kwargs))


class _Room:
    name = "room-load-1"

    def __init__(self) -> None:
        self.local_participant = _Participant()


def test_publish_debug_event_targets_originating_bridge() -> None:
    async def _run() -> None:
        room = _Room()
        gateway = BridgeGateway(
            room=room,
            bridge_identity="bridge-load-1",
            protocol="LOAD-1",
            stress_test=True,
        )

        await gateway.publish_debug_event(
            "stt.completed", duration_ms=123, text="texto reconhecido"
        )

        payload, kwargs = room.local_participant.calls[0]
        assert payload["type"] == "debug_event"
        assert payload["event"] == "stt.completed"
        assert payload["stress_test"] is True
        assert payload["data"] == {
            "duration_ms": 123,
            "text": "texto reconhecido",
        }
        assert kwargs == {
            "reliable": True,
            "destination_identities": ["bridge-load-1"],
            "topic": "agent.debug",
        }

    asyncio.run(_run())


def test_publish_debug_event_is_suppressed_outside_stress_test() -> None:
    async def _run() -> None:
        room = _Room()
        gateway = BridgeGateway(
            room=room,
            bridge_identity="bridge-regular-1",
            protocol="REGULAR-1",
        )

        await gateway.publish_debug_event("stt.completed", duration_ms=123)

        assert room.local_participant.calls == []

    asyncio.run(_run())
