import asyncio
import json
import logging
import websockets
from typing import Dict, Any

from .profile import local_profile
import time
import uuid

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

class RoomClient:
    def __init__(self, manager, host_ws_url: str, room_id: str):
        self.manager = manager
        self.host_ws_url = host_ws_url
        self.room_id = room_id
        self.ws = None
        self._connected = False

    async def connect(self):
        try:
            # Try connecting directly to host first
            self.ws = await websockets.connect(self.host_ws_url)
            self._connected = True
            logger.info(f"Connected to room host at {self.host_ws_url}")
            asyncio.create_task(self.listen())
        except Exception as e:
            logger.warning(f"Direct connection failed, falling back to cloud relay: {e}")
            # Cloud WebSocket fallback (MVP URL)
            self.ws = await websockets.connect(f"ws://localhost:8000/ws/signal/{self.room_id}")
            self._connected = True
            asyncio.create_task(self.listen())

    async def listen(self):
        try:
            while self._connected:
                msg = await self.ws.recv()
                data = json.loads(msg)
                if data.get("type") == "chat":
                    logger.info(f"Room Chat: {data.get('sender_name')}: {data.get('content')}")
                elif data.get("type") == "system":
                    logger.info(f"Room System: {data.get('content')}")
                elif data.get("type") == "history":
                    pass # ignore for CLI simplistic MVP
        except websockets.exceptions.ConnectionClosed:
            logger.info("Disconnected from room.")
            self._connected = False

    async def send_chat(self, content: str):
        if not self._connected or not self.ws:
            logger.error("Cannot send chat, disconnected.")
            return

        prof = local_profile.get()
        msg = {
            "type": "chat",
            "content": content,
            "sender_id": prof["user_id"],
            "sender_name": prof["username"]
        }
        await self.ws.send(json.dumps(msg))

    async def disconnect(self):
        self._connected = False
        if self.ws:
            await self.ws.close()
