# backend/app/core/websocket_manager.py
import asyncio

from fastapi import WebSocket


class ConnectionManager:
    def __init__(self):
        self.active_connections: set[WebSocket] = set()

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.add(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.discard(websocket)

    async def broadcast(self, message: dict):
        if not self.active_connections:
            return

        connections_snapshot = list(self.active_connections)

        async def send_safe(ws: WebSocket):
            try:
                await ws.send_json(message)
            except Exception:
                self.disconnect(ws)

        await asyncio.gather(*(send_safe(ws) for ws in connections_snapshot))


manager = ConnectionManager()


async def send_ws_update(id: str):
    await asyncio.gather(
        manager.broadcast({"type": "dashboard_update"}),
        manager.broadcast({"type": "tournament_update", "id": id}),
    )
