"""WebSocket broadcast manager for agentradar."""
from __future__ import annotations

import asyncio
import json
import logging
from typing import Set

from fastapi import WebSocket

logger = logging.getLogger("agentradar.websocket")

_connections: Set[WebSocket] = set()
_connections_lock = asyncio.Lock()


async def connect(ws: WebSocket) -> None:
    await ws.accept()
    async with _connections_lock:
        _connections.add(ws)
    logger.debug("WebSocket client connected. Total: %d", len(_connections))


async def disconnect(ws: WebSocket) -> None:
    async with _connections_lock:
        _connections.discard(ws)
    logger.debug("WebSocket client disconnected. Total: %d", len(_connections))


async def broadcast(event: dict) -> None:
    """Send event to all connected clients."""
    if not _connections:
        return
    payload = json.dumps(event, default=str)
    dead: list[WebSocket] = []
    async with _connections_lock:
        targets = list(_connections)
    for ws in targets:
        try:
            await ws.send_text(payload)
        except Exception:
            dead.append(ws)
    if dead:
        async with _connections_lock:
            for ws in dead:
                _connections.discard(ws)


async def broadcast_raw(text: str) -> None:
    if not _connections:
        return
    dead: list[WebSocket] = []
    async with _connections_lock:
        targets = list(_connections)
    for ws in targets:
        try:
            await ws.send_text(text)
        except Exception:
            dead.append(ws)
    if dead:
        async with _connections_lock:
            for ws in dead:
                _connections.discard(ws)
