# backend/app/routes/websocket.py
import asyncio

from fastapi import APIRouter, WebSocket, WebSocketDisconnect

from ..core.websocket_manager import manager

router = APIRouter(prefix="/ws", tags=["Websocket"])


@router.websocket("")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            try:
                await asyncio.wait_for(websocket.receive_text(), timeout=30.0)
            except asyncio.TimeoutError:
                await websocket.send_json({"type": "ping"})
    except WebSocketDisconnect:
        manager.disconnect(websocket)
    except Exception:
        manager.disconnect(websocket)
