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50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
WebSocket endpoints for real-time communication

These endpoints handle persistent WebSocket connections for:
- Streaming query results in real time
- Progress notifications for long-running processes
- Project and task status updates
- Chat-like interface for iterative queries
- Live collaboration on BIM projects
- Push notifications for important events

Supports multiple concurrent connections with robust
disconnection handling, automatic reconnection and message queuing.
"""
import logging
import json
import asyncio
from typing import Dict, List, Optional
from datetime import datetime
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_async_session
from app.models import Project, Query, QueryType, QueryStatus
from app.api.v1.endpoints.query import process_query, get_project_for_query

logger = logging.getLogger(__name__)
router = APIRouter()


class ConnectionManager:
    """Manages multiple WebSocket connections

    **Responsibilities:**
    - Tracking active connections by connection_id
    - Mapping query -> connection for targeted notifications
    - Automatic cleanup of dead connections
    - Broadcasting messages to connection groups
    - Graceful disconnection handling

    **Usage Patterns:**
    - A connection can monitor multiple queries
    - Queries can have multiple listeners
    - Messages with routing for specific connections
    - Heartbeat for keep-alive connections

    **Data Structure:**
    - active_connections: Dict[connection_id, WebSocket]
    - query_connections: Dict[query_id, connection_id]
    - Atomic cleanup to prevent memory leaks
    """

    def __init__(self):
        # Active connections dictionary: connection_id -> WebSocket
        self.active_connections: Dict[str, WebSocket] = {}
        # Mapping query -> connection for targeted notifications
        self.query_connections: Dict[str, str] = {}  # query_id -> connection_id

    async def connect(self, websocket: WebSocket, connection_id: str):
        """Connect a new WebSocket"""
        await websocket.accept()
        self.active_connections[connection_id] = websocket
        logger.info(f"WebSocket connected: {connection_id}")

    def disconnect(self, connection_id: str):
        """Disconnect a WebSocket"""
        if connection_id in self.active_connections:
            del self.active_connections[connection_id]
        # Clean up query mappings
        query_ids_to_remove = [qid for qid, cid in self.query_connections.items() if cid == connection_id]
        for qid in query_ids_to_remove:
            del self.query_connections[qid]
        logger.info(f"WebSocket disconnected: {connection_id}")

    async def send_message(self, connection_id: str, message: dict):
        """Send message to specific connection"""
        if connection_id in self.active_connections:
            try:
                await self.active_connections[connection_id].send_text(json.dumps(message))
            except Exception as e:
                logger.error(f"Error sending message to {connection_id}: {e}")
                self.disconnect(connection_id)

    async def send_query_update(self, query_id: str, message: dict):
        """Send update to connection monitoring specific query"""
        if query_id in self.query_connections:
            connection_id = self.query_connections[query_id]
            await self.send_message(connection_id, message)


manager = ConnectionManager()


@router.websocket("/query-stream")
async def websocket_query_stream(websocket: WebSocket):
    """WebSocket endpoint for streaming query results"""
    connection_id = f"ws_{datetime.now().timestamp()}"

    try:
        await manager.connect(websocket, connection_id)

        # Send connection confirmation
        await manager.send_message(connection_id, {
            "type": "connection_established",
            "connection_id": connection_id,
            "timestamp": datetime.now().isoformat(),
            "message": "WebSocket connection established. Send query requests to start streaming."
        })

        while True:
            # Receive query request
            data = await websocket.receive_text()

            try:
                query_request = json.loads(data)

                # Validate request format
                if not isinstance(query_request, dict) or "type" not in query_request:
                    await manager.send_message(connection_id, {
                        "type": "error",
                        "message": "Invalid request format. Expected JSON with 'type' field."
                    })
                    continue

                request_type = query_request.get("type")

                if request_type == "query":
                    await handle_streaming_query(connection_id, query_request)
                elif request_type == "ping":
                    await manager.send_message(connection_id, {
                        "type": "pong",
                        "timestamp": datetime.now().isoformat()
                    })
                else:
                    await manager.send_message(connection_id, {
                        "type": "error",
                        "message": f"Unknown request type: {request_type}"
                    })

            except json.JSONDecodeError:
                await manager.send_message(connection_id, {
                    "type": "error",
                    "message": "Invalid JSON format."
                })
            except Exception as e:
                logger.error(f"Error handling WebSocket message: {e}")
                await manager.send_message(connection_id, {
                    "type": "error",
                    "message": "An internal error occurred"
                })

    except WebSocketDisconnect:
        logger.info(f"WebSocket disconnected: {connection_id}")
    finally:
        manager.disconnect(connection_id)


async def handle_streaming_query(connection_id: str, query_request: dict):
    """Handle a streaming query request"""
    try:
        # Extract query parameters
        project_id = query_request.get("project_id")
        query_text = query_request.get("query")
        options = query_request.get("options", {})
        tenant_id = query_request.get("tenant_id", "unknown")  # In real app, extract from auth

        # Validate required fields
        if not project_id or not query_text:
            await manager.send_message(connection_id, {
                "type": "error",
                "message": "Missing required fields: project_id and query"
            })
            return

        query_id = f"qry_stream_{datetime.now().timestamp()}"
        manager.query_connections[query_id] = connection_id

        # Send query started message
        await manager.send_message(connection_id, {
            "type": "query_started",
            "query_id": query_id,
            "project_id": project_id,
            "query": query_text,
            "timestamp": datetime.now().isoformat()
        })

        # Simulate streaming query processing with progress updates
        processing_steps = [
            ("parsing", "Parsing natural language query", 10),
            ("validation", "Validating project access", 20),
            ("analysis", "Analyzing query intent", 40),
            ("extraction", "Extracting entities and filters", 60),
            ("execution", "Executing query against IFC data", 80),
            ("formatting", "Formatting results", 95),
            ("complete", "Query completed", 100)
        ]

        for step, description, progress in processing_steps:
            await manager.send_message(connection_id, {
                "type": "progress",
                "query_id": query_id,
                "step": step,
                "description": description,
                "progress": progress,
                "timestamp": datetime.now().isoformat()
            })

            # Simulate processing time
            await asyncio.sleep(0.2)

            # Send intermediate results for some steps
            if step == "analysis":
                await manager.send_message(connection_id, {
                    "type": "intermediate_result",
                    "query_id": query_id,
                    "step": step,
                    "data": {
                        "intent": "count" if "count" in query_text.lower() else "find",
                        "entities": ["wall", "window", "door"] if any(word in query_text.lower() for word in ["wall", "window", "door"]) else [],
                        "confidence": 0.85
                    }
                })
            elif step == "extraction":
                await manager.send_message(connection_id, {
                    "type": "intermediate_result",
                    "query_id": query_id,
                    "step": step,
                    "data": {
                        "filters": {"type": "IfcWall"} if "wall" in query_text.lower() else {},
                        "metrics": ["count"],
                        "estimated_results": 42 if "window" in query_text.lower() else 156
                    }
                })

        # Generate final result (mock implementation)
        if "window" in query_text.lower():
            result = "42 windows"
            explanation = "Found 42 windows across all levels in the project."
            elements_counted = 42
        elif "wall" in query_text.lower():
            result = "156 walls"
            explanation = "Found 156 walls of various types in the project."
            elements_counted = 156
        else:
            result = "No matching elements found"
            explanation = "Could not identify specific elements in your query."
            elements_counted = 0

        # Send final result
        await manager.send_message(connection_id, {
            "type": "query_complete",
            "query_id": query_id,
            "status": "completed",
            "result": result,
            "explanation": explanation,
            "confidence": 0.85,
            "details": {
                "elements_counted": elements_counted,
                "processing_time_ms": len(processing_steps) * 200,
                "cache_hit": False
            },
            "usage": {
                "queries": 1,
                "tokens": len(query_text.split()) * 2,
                "compute_ms": len(processing_steps) * 200
            },
            "timestamp": datetime.now().isoformat()
        })

        # Clean up query mapping
        if query_id in manager.query_connections:
            del manager.query_connections[query_id]

    except Exception as e:
        logger.error(f"Error in streaming query: {e}")
        await manager.send_message(connection_id, {
            "type": "query_error",
            "query_id": query_id,
            "error": "Query processing failed",
            "timestamp": datetime.now().isoformat()
        })

        # Clean up query mapping
        if query_id in manager.query_connections:
            del manager.query_connections[query_id]


@router.websocket("/upload-progress")
async def websocket_upload_progress(websocket: WebSocket, project_id: str):
    """WebSocket endpoint for upload progress"""
    connection_id = f"upload_{project_id}_{datetime.now().timestamp()}"

    try:
        await manager.connect(websocket, connection_id)

        # Send connection confirmation
        await manager.send_message(connection_id, {
            "type": "upload_connection_established",
            "project_id": project_id,
            "connection_id": connection_id,
            "timestamp": datetime.now().isoformat(),
            "message": f"Upload progress monitoring started for project {project_id}"
        })

        # Simulate upload and processing progress
        await simulate_upload_progress(connection_id, project_id)

        # Keep connection alive for real-time updates
        while True:
            try:
                # Listen for ping/control messages
                data = await asyncio.wait_for(websocket.receive_text(), timeout=30.0)
                message = json.loads(data)

                if message.get("type") == "ping":
                    await manager.send_message(connection_id, {
                        "type": "pong",
                        "project_id": project_id,
                        "timestamp": datetime.now().isoformat()
                    })
                elif message.get("type") == "get_status":
                    # Send current project status
                    await send_project_status(connection_id, project_id)

            except asyncio.TimeoutError:
                # Send keepalive
                await manager.send_message(connection_id, {
                    "type": "keepalive",
                    "project_id": project_id,
                    "timestamp": datetime.now().isoformat()
                })
            except json.JSONDecodeError:
                await manager.send_message(connection_id, {
                    "type": "error",
                    "message": "Invalid JSON format"
                })

    except WebSocketDisconnect:
        logger.info(f"Upload progress WebSocket disconnected for project {project_id}")
    finally:
        manager.disconnect(connection_id)


async def simulate_upload_progress(connection_id: str, project_id: str):
    """Simulate upload and processing progress"""
    upload_stages = [
        ("initializing", "Initializing upload", 0, 1.0),
        ("uploading", "Uploading IFC file to S3", 10, 2.0),
        ("validating", "Validating IFC file format", 30, 1.5),
        ("parsing", "Parsing IFC structure", 40, 3.0),
        ("processing", "Processing elements and geometry", 60, 4.0),
        ("indexing", "Creating database indexes", 85, 2.0),
        ("finalizing", "Finalizing project setup", 95, 1.0),
        ("completed", "Upload and processing completed", 100, 0.0)
    ]

    total_elements = 1247  # Mock total elements
    processed_elements = 0

    for stage, description, progress, duration in upload_stages:
        # Send stage start
        await manager.send_message(connection_id, {
            "type": "upload_progress",
            "project_id": project_id,
            "stage": stage,
            "description": description,
            "progress": progress,
            "elements_processed": processed_elements,
            "total_elements": total_elements,
            "timestamp": datetime.now().isoformat()
        })

        # Simulate incremental progress within stage
        if duration > 0:
            steps = max(1, int(duration * 5))  # 5 updates per second
            for i in range(steps):
                await asyncio.sleep(duration / steps)

                # Calculate incremental progress
                stage_progress = (i + 1) / steps
                current_progress = progress + (10 * stage_progress if stage != "completed" else 0)

                # Update processed elements for processing stages
                if stage in ["parsing", "processing"]:
                    stage_elements = int(total_elements * stage_progress)
                    if stage == "parsing":
                        processed_elements = int(total_elements * 0.3 * stage_progress)
                    elif stage == "processing":
                        processed_elements = int(total_elements * 0.3 + total_elements * 0.6 * stage_progress)

                # Send incremental update
                await manager.send_message(connection_id, {
                    "type": "upload_progress",
                    "project_id": project_id,
                    "stage": stage,
                    "description": description,
                    "progress": min(current_progress, 100),
                    "elements_processed": processed_elements,
                    "total_elements": total_elements,
                    "stage_progress": stage_progress * 100,
                    "timestamp": datetime.now().isoformat()
                })

        # Send stage completion for intermediate stages
        if stage != "completed":
            await manager.send_message(connection_id, {
                "type": "stage_completed",
                "project_id": project_id,
                "stage": stage,
                "next_stage": upload_stages[upload_stages.index((stage, description, progress, duration)) + 1][0],
                "timestamp": datetime.now().isoformat()
            })

    # Send final completion
    await manager.send_message(connection_id, {
        "type": "upload_completed",
        "project_id": project_id,
        "status": "ready",
        "total_elements": total_elements,
        "processing_time_seconds": sum(stage[3] for stage in upload_stages),
        "file_size_mb": 45.2,  # Mock file size
        "ready_for_queries": True,
        "timestamp": datetime.now().isoformat()
    })


async def send_project_status(connection_id: str, project_id: str):
    """Send current project status"""
    # Mock project status - in real implementation, query database
    await manager.send_message(connection_id, {
        "type": "project_status",
        "project_id": project_id,
        "status": "ready",  # ready, processing, failed, etc.
        "progress": 100,
        "elements_count": 1247,
        "file_size_mb": 45.2,
        "last_updated": datetime.now().isoformat(),
        "ready_for_queries": True,
        "timestamp": datetime.now().isoformat()
    })