# Gestionnaire de connexions WebSocket — accepte, envoie, broadcast

import logging

from fastapi import WebSocket

logger = logging.getLogger(__name__)


class ConnectionManager:
    def __init__(self) -> None:
        self.connections: dict[str, WebSocket] = {}
        self.usernames: dict[str, str] = {}
        self._counter: int = 0

    def _next_id(self) -> str:
        self._counter += 1
        return f"conn_{self._counter}"

    async def connect(self, websocket: WebSocket) -> str:
        await websocket.accept()
        conn_id = self._next_id()
        self.connections[conn_id] = websocket
        logger.info("Connexion %s établie", conn_id)
        return conn_id

    def disconnect(self, conn_id: str) -> None:
        self.connections.pop(conn_id, None)
        self.usernames.pop(conn_id, None)
        logger.info("Connexion %s fermée", conn_id)

    def set_username(self, conn_id: str, username: str) -> None:
        self.usernames[conn_id] = username

    def get_username(self, conn_id: str) -> str | None:
        return self.usernames.get(conn_id)

    async def send(self, conn_id: str, message: dict) -> None:
        ws = self.connections.get(conn_id)
        if ws:
            await ws.send_json(message)

    async def dispatch(self, messages: list[tuple[str, dict]]) -> None:
        """Envoie une liste de (conn_id, message) produite par le LobbyManager."""
        for conn_id, message in messages:
            await self.send(conn_id, message)
