from __future__ import annotations

import json
import time
from typing import Any


class BridgeGateway:
    def __init__(
        self,
        *,
        room: Any,
        bridge_identity: str,
        protocol: str,
        timeline: Any | None = None,
        stress_test: bool = False,
    ) -> None:
        self._room = room
        self._bridge_identity = bridge_identity
        self._protocol = protocol
        self._timeline = timeline
        self._stress_test = bool(stress_test)

    async def publish_debug_event(self, event: str, **data: Any) -> None:
        """Publish bounded, structured diagnostics to the originating Bridge."""
        if not self._bridge_identity or not self._stress_test:
            return
        payload = {
            "type": "debug_event",
            "version": 1,
            "source": "agent",
            "stress_test": True,
            "event": str(event or "unknown").strip(),
            "timestamp_ms": round(time.time() * 1000),
            "protocol": self._protocol,
            "room": self._room.name,
            "data": data,
        }
        await self._room.local_participant.publish_data(
            json.dumps(payload, ensure_ascii=False),
            reliable=True,
            destination_identities=[self._bridge_identity],
            topic="agent.debug",
        )

    async def notify_stage_done(self, reason: str = "stage_done") -> None:
        if not self._bridge_identity:
            return

        payload = {
            "type": "stage",
            "stage": "DONE",
            "reason": reason,
            "room": self._room.name,
            "protocol": self._protocol,
        }
        await self._room.local_participant.publish_data(
            json.dumps(payload, ensure_ascii=False),
            reliable=True,
            destination_identities=[self._bridge_identity],
            topic="agent.stage",
        )
        if self._timeline is not None:
            self._timeline.emit(
                "bridge_done_notified",
                reason=reason,
                destination=self._bridge_identity,
            )

    async def notify_stop(
        self,
        *,
        status: str,
        reason: str,
        resource: str = "",
        failed_resources: tuple[str, ...] = (),
        phase: str = "in_session",
    ) -> None:
        if not self._bridge_identity:
            return

        payload = {
            "type": "stage",
            "stage": "DONE",
            "status": str(status or "").strip(),
            "reason": str(reason or "").strip(),
            "room": self._room.name,
            "protocol": self._protocol,
        }
        if resource:
            payload["resource"] = str(resource).strip()
        normalized_failed_resources = [str(item).strip() for item in failed_resources if str(item).strip()]
        if normalized_failed_resources:
            payload["failed_resources"] = normalized_failed_resources
        if phase:
            payload["phase"] = str(phase).strip()

        await self._room.local_participant.publish_data(
            json.dumps(payload, ensure_ascii=False),
            reliable=True,
            destination_identities=[self._bridge_identity],
            topic="agent.stage",
        )
        if self._timeline is not None:
            self._timeline.emit(
                "bridge_stop_notified",
                status=payload["status"],
                reason=payload["reason"],
                resource=payload.get("resource", ""),
                phase=payload.get("phase", ""),
                destination=self._bridge_identity,
            )
