from fastapi import WebSocket


class ConnectionManager:
    def __init__(self):
        self._telemetry: list[WebSocket] = []
        self._logs: list[WebSocket] = []

    async def connect_telemetry(self, ws: WebSocket):
        await ws.accept()
        self._telemetry.append(ws)

    async def connect_logs(self, ws: WebSocket):
        await ws.accept()
        self._logs.append(ws)

    def disconnect(self, ws: WebSocket):
        self._telemetry = [w for w in self._telemetry if w != ws]
        self._logs = [w for w in self._logs if w != ws]

    async def broadcast_telemetry(self, data: dict):
        await self._broadcast(self._telemetry, data)

    async def broadcast_log(self, record: dict):
        await self._broadcast(self._logs, record)

    async def _broadcast(self, clients: list, data: dict):
        dead = []
        for ws in clients:
            try:
                await ws.send_json(data)
            except Exception:
                dead.append(ws)
        for ws in dead:
            self.disconnect(ws)


manager = ConnectionManager()
