from fastapi import FastAPI, Depends, HTTPException, WebSocket, WebSocketDisconnect from fastapi.middleware.cors import CORSMiddleware from typing import List import json from app.core.config import settings from app.api.api import api_router app = FastAPI( title=settings.project_name, openapi_url=f"{settings.api_v1_str}/openapi.json", description="Prior Permission Required (PPR) system API for aircraft operations management", version="2.0.0" ) # Set up CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure this properly for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # WebSocket connection manager for real-time updates class ConnectionManager: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def send_personal_message(self, message: str, websocket: WebSocket): await websocket.send_text(message) async def broadcast(self, message: dict): message_str = json.dumps(message) for connection in self.active_connections: try: await connection.send_text(message_str) except: # Connection is dead, remove it self.active_connections.remove(connection) manager = ConnectionManager() @app.websocket("/ws/tower-updates") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: # Keep connection alive data = await websocket.receive_text() # Echo back for heartbeat await websocket.send_text(f"Heartbeat: {data}") except WebSocketDisconnect: manager.disconnect(websocket) @app.get("/") async def root(): return { "message": "Airfield PPR API", "version": "2.0.0", "docs": "/docs" } @app.get("/health") async def health_check(): return {"status": "healthy", "timestamp": "2024-01-01T00:00:00Z"} # Include API router app.include_router(api_router, prefix=settings.api_v1_str) # Make connection manager available to the app app.state.connection_manager = manager