# """
# FastAPI server for the virtual system interface
# """

# from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
# from fastapi.staticfiles import StaticFiles
# from fastapi.responses import HTMLResponse
# from fastapi.middleware.cors import CORSMiddleware
# import uvicorn
# import asyncio
# import json
# from typing import List, Dict
# from pathlib import Path
# from bootloader.bootloader import SystemBootloader
# from bootloader.display_server import VirtualDisplayServer

# class VirtualSystemServer:
#     def __init__(self):
#         self.app = FastAPI(title="Virtual System Interface")
#         self.setup_middleware()
#         self.setup_routes()
#         self.bootloader = SystemBootloader()
#         self.display_server = VirtualDisplayServer()
#         self.active_connections: List[WebSocket] = []

#     def setup_middleware(self):
#         """Setup CORS and other middleware"""
#         self.app.add_middleware(
#             CORSMiddleware,
#             allow_origins=["*"],
#             allow_credentials=True,
#             allow_methods=["*"],
#             allow_headers=["*"],
#         )

#         # Mount static files
#         self.app.mount(
#             "/interface",
#             StaticFiles(directory="bootloader/interface"),
#             name="interface"
#         )

#     def setup_routes(self):
#         """Setup API routes"""
#         @self.app.get("/", response_class=HTMLResponse)
#         async def get_interface():
#             interface_path = Path("bootloader/interface/index.html")
#             return HTMLResponse(content=interface_path.read_text(), status_code=200)

#         @self.app.websocket("/ws")
#         async def websocket_endpoint(websocket: WebSocket):
#             await self.handle_websocket(websocket)

#         @self.app.websocket("/ws/gpu")
#         async def gpu_stream(websocket: WebSocket):
#             await self.handle_gpu_stream(websocket)

#         @self.app.get("/api/system/status")
#         async def get_system_status():
#             return await self.get_system_status()

#         @self.app.post("/api/system/boot")
#         async def boot_system(os_image: str = None):
#             return await self.boot_system(os_image)

#         @self.app.get("/api/os/images")
#         async def get_os_images():
#             return {"images": self.bootloader.get_available_os_images()}

#     async def handle_websocket(self, websocket: WebSocket):
#         """Handle main WebSocket connections"""
#         await websocket.accept()
#         self.active_connections.append(websocket)
#         try:
#             while True:
#                 data = await websocket.receive_json()
#                 await self.process_websocket_message(websocket, data)
#         except WebSocketDisconnect:
#             self.active_connections.remove(websocket)

#     async def handle_gpu_stream(self, websocket: WebSocket):
#         """Handle GPU frame streaming WebSocket"""
#         await websocket.accept()
#         self.active_connections.append(websocket)
#         try:
#             while True:
#                 if self.bootloader.gpu_driver:
#                     frame = await self.bootloader.gpu_driver.get_frame()
#                     if frame:
#                         await websocket.send_bytes(frame)
#                 await asyncio.sleep(1/60)  # 60 FPS target
#         except WebSocketDisconnect:
#             self.active_connections.remove(websocket)

#     async def process_websocket_message(self, websocket: WebSocket, data: dict):
#         """Process incoming WebSocket messages"""
#         if data.get("type") == "boot":
#             success = await self.bootloader.boot_system(data.get("os_image"))
#             await self.broadcast({
#                 "type": "boot_status",
#                 "success": success
#             })
#         elif data.get("type") == "get_os_images":
#             await websocket.send_json({
#                 "type": "os_images",
#                 "images": self.bootloader.get_available_os_images()
#             })

#     async def broadcast(self, message: dict):
#         """Broadcast message to all connected clients"""
#         for connection in self.active_connections:
#             try:
#                 await connection.send_json(message)
#             except:
#                 pass

#     async def get_system_status(self):
#         """Get current system status"""
#         return {
#             "status": "running" if self.bootloader.boot_status == "initialized" else "stopped",
#             "cpu_cores": self.bootloader.config.cpu_cores,
#             "cpu_threads": self.bootloader.config.cpu_threads,
#             "vram_size": f"{self.bootloader.config.vram_size_gb}GB",
#             "gpu_enabled": self.bootloader.config.enable_gpu
#         }

#     async def boot_system(self, os_image: str = None):
#         """Boot the system with specified OS image"""
#         try:
#             success = await self.bootloader.boot_system(os_image)
#             return {"success": success}
#         except Exception as e:
#             raise HTTPException(status_code=500, detail=str(e))

#     def start(self, host="0.0.0.0", port=8000):
#         """Start the FastAPI server"""
#         uvicorn.run(
#             self.app,
#             host=host,
#             port=port,
#             reload=True,
#             access_log=True
#         )

# # Create and start server
# if __name__ == "__main__":
#     server = VirtualSystemServer()
#     server.start()
