""" WebSocket Chat - Real-time messaging for chat interface. Provides instant message updates without polling. """ from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query from app.core.security import decode_access_token from app.core.database import get_session from app.models.lead import Lead, Message, Conversation from sqlalchemy import select from uuid import UUID from typing import Dict, Set import logging import json import asyncio router = APIRouter() logger = logging.getLogger(__name__) # Store active connections per lead_id # Structure: {lead_id: {websocket1, websocket2, ...}} active_connections: Dict[str, Set[WebSocket]] = {} class ConnectionManager: """Manages WebSocket connections for chat.""" def __init__(self): self.connections: Dict[str, Set[WebSocket]] = {} async def connect(self, lead_id: str, websocket: WebSocket): """Add a connection for a lead.""" if lead_id not in self.connections: self.connections[lead_id] = set() self.connections[lead_id].add(websocket) logger.debug(f"🔌 Chat WS connected: lead={lead_id}, total={len(self.connections[lead_id])}") def disconnect(self, lead_id: str, websocket: WebSocket): """Remove a connection.""" if lead_id in self.connections: self.connections[lead_id].discard(websocket) if not self.connections[lead_id]: del self.connections[lead_id] logger.debug(f"🔌 Chat WS disconnected: lead={lead_id}") async def broadcast_to_lead(self, lead_id: str, message: dict): """Send message to all connections watching a lead.""" if lead_id in self.connections: dead_connections = set() for ws in self.connections[lead_id]: try: await ws.send_json(message) except Exception as e: logger.warning(f"Failed to send to WS: {e}") dead_connections.add(ws) # Clean up dead connections for ws in dead_connections: self.connections[lead_id].discard(ws) manager = ConnectionManager() @router.websocket("/{lead_id}") async def chat_websocket( websocket: WebSocket, lead_id: str, token: str = Query(...) ): """ WebSocket endpoint for real-time chat updates. Events sent to client: - new_message: New message in conversation - lead_updated: Lead data changed - typing: Someone is typing Client can send: - ping: Keep-alive - typing: Notify others of typing """ await websocket.accept() # Authenticate try: payload = decode_access_token(token) user_id = payload.get("sub") tenant_id = payload.get("tenant_id") if not user_id: await websocket.close(code=4001, reason="Invalid token") return logger.debug(f"🔌 Chat WS authenticated: user={user_id}, lead={lead_id}") except Exception as e: logger.error(f"Chat WS auth failed: {e}") await websocket.close(code=4003, reason="Authentication failed") return # Connect await manager.connect(lead_id, websocket) try: # Send initial connection confirmation await websocket.send_json({ "type": "connected", "lead_id": lead_id }) while True: # Receive messages from client message = await websocket.receive() if "text" in message: try: data = json.loads(message["text"]) msg_type = data.get("type") if msg_type == "ping": await websocket.send_json({"type": "pong"}) elif msg_type == "typing": # Broadcast typing indicator to others await manager.broadcast_to_lead(lead_id, { "type": "typing", "user_id": user_id }) except json.JSONDecodeError: pass except WebSocketDisconnect: manager.disconnect(lead_id, websocket) except Exception as e: # Suppress expected disconnect errors if "disconnect" not in str(e).lower(): logger.warning(f"Chat WS error: {e}") manager.disconnect(lead_id, websocket) try: await websocket.close() except: pass async def notify_new_message(lead_id: str, message_data: dict): """ Call this from message handlers to notify WebSocket clients. Args: lead_id: The lead ID message_data: Message dict with id, content, sender_type, media_url, etc. """ await manager.broadcast_to_lead(str(lead_id), { "type": "new_message", "message": message_data }) async def notify_lead_updated(lead_id: str, lead_data: dict): """ Call this when lead data changes (status, heat_level, etc.) """ await manager.broadcast_to_lead(str(lead_id), { "type": "lead_updated", "lead": lead_data })