"""WebSocket endpoint and broadcast helper."""

from __future__ import annotations

import json
import logging

from aiohttp import web, WSMsgType

from meeting_helper.state import state

logger = logging.getLogger(__name__)


async def ws_handler(request: web.Request) -> web.WebSocketResponse:
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    state.ws_clients.add(ws)
    logger.info("Client connected (total=%d)", len(state.ws_clients))

    # Send current status
    await ws.send_str(json.dumps({"type": "status", "value": state.status}))

    # Send current meeting info if active
    if state.meeting_info:
        info = state.meeting_info
        await ws.send_str(json.dumps({
            "type": "meeting_status",
            "active": True,
            "app": getattr(info, "app_name", ""),
            "meeting_name": getattr(info, "meeting_name", "") or "",
        }))

    # Send last response for late-joining clients
    if state.last_response:
        await ws.send_str(json.dumps({"type": "done", "full_text": state.last_response}))

    try:
        async for msg in ws:
            if msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):
                break
    finally:
        state.ws_clients.discard(ws)
        logger.info("Client disconnected (total=%d)", len(state.ws_clients))

    return ws


async def broadcast(message: dict) -> None:
    """Send a JSON message to all connected WebSocket clients."""
    if not state.ws_clients:
        return

    data = json.dumps(message)
    dead = set()

    for ws in list(state.ws_clients):
        try:
            await ws.send_str(data)
        except Exception:
            dead.add(ws)

    state.ws_clients -= dead
