import asyncio
import json
import logging
import uuid
import time
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import uvicorn
from typing import List, Dict, Any

from .profile import local_profile
from .chat_store import RoomChatStore

logger = logging.getLogger("brynq.rooms.host")

class RoomHost:
    def __init__(self, manager):
        self.manager = manager
        self.app = FastAPI(title="Room P2P Host Server")
        self.active_connections: List[WebSocket] = []
        # Persistent chat history — survives host restarts
        room_id = (manager.active_room or {}).get("room_id", "default")
        self.chat_store = RoomChatStore(room_id)
        self.server = None
        self._setup_routes()

    def _setup_routes(self):
        @self.app.websocket("/ws/room")
        async def websocket_endpoint(ws: WebSocket):
            await ws.accept()
            self.active_connections.append(ws)
            # Send persisted history on connect
            history = self.chat_store.get_history()
            await ws.send_json({"type": "history", "messages": history})

            # Announce join
            await self.broadcast({"type": "system", "content": "A peer has connected."})

            try:
                while True:
                    data = await ws.receive_text()
                    msg = json.loads(data)
                    if msg.get("type") == "chat":
                        msg["id"] = str(uuid.uuid4())
                        msg["timestamp"] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
                        self.chat_store.add_message(msg)
                        await self.broadcast(msg)
                    elif msg.get("type") == "task_event":
                        await self.broadcast(msg)
            except WebSocketDisconnect:
                self.active_connections.remove(ws)
                await self.broadcast({"type": "system", "content": "A peer disconnected."})

    async def broadcast(self, message: Dict[str, Any]):
        for connection in self.active_connections:
            try:
                await connection.send_json(message)
            except Exception:
                pass

    async def broadcast_chat(self, content: str):
        prof = local_profile.get()
        msg = {
            "type": "chat",
            "content": content,
            "sender_id": prof["user_id"],
            "sender_name": prof["username"],
            "id": str(uuid.uuid4()),
            "timestamp": time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
        }
        self.chat_store.add_message(msg)
        await self.broadcast(msg)

    async def start(self):
        config = uvicorn.Config(app=self.app, host="0.0.0.0", port=8081, log_level="warning")
        self.server = uvicorn.Server(config)
        logger.info("Starting RoomHost WS Server on port 8081...")
        await self.server.serve()

    async def stop(self):
        if self.server:
            self.server.should_exit = True
        if self.chat_store:
            self.chat_store.close()
