import socketio, asyncio, logging, os


from livekit.api import LiveKitAPI, AccessToken
from models.dashboard import CommandPayload
from socketio.async_server import AsyncServer
from pydantic import BaseModel
from agents.client_agent import process_message
from fastapi import APIRouter, HTTPException
from database import db

logger = logging.getLogger(__name__)

sio: AsyncServer = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins="*")
socket_app = socketio.ASGIApp(sio, socketio_path="/api/v1/user/dashboard")

class TokenRequest(BaseModel):
    roomName: str
    participantName: str

router = APIRouter(
    prefix="/api/v1/user/dashboard",
    tags=["users-dashboard"],
)

livekit_api = LiveKitAPI(
    url=os.getenv("LIVEKIT_URL"),
    api_key=os.getenv("LIVEKIT_API_KEY"),
    api_secret=os.getenv("LIVEKIT_API_SECRET"),
)

clients = {}
client_system_data = {}
ip = ''
input_command = ''

async def send_data(sid):
    while True:
        try:
            await sio.emit('send_system_data', client_system_data[f'{ip}'], to=sid)
        except Exception as e:
            break
        await asyncio.sleep(1)

@sio.event
async def connect(sid, environ, auth):
    global ip
    if auth and 'requested_ip' in auth:
        ip = auth['requested_ip']
    sio.start_background_task(send_data, sid)

@sio.event
async def disconnect(sid):
    client_ip = None
    for key, value in clients.items():
        if value == sid:
            client_ip = key
            del clients[key]
            break
    if client_ip and client_ip in client_system_data:
        del client_system_data[client_ip]
    logger.warning(f"Client disconnected: {sid}")

@sio.event
async def update_system_data(sid, data: dict):
    logger.warning(f"Received system data from client {sid}: {data}")
    parent_key = list(data.keys())[0]
    if parent_key not in list(clients.keys()):
        username = data.get('username', None)
        userdata = await db["users"].find_one({"username": username})
        if userdata["ip_address"] != parent_key:
            await db["users"].update_one(
                {"username": username},
                {"$set": {"ip_address": parent_key}}
            )
        clients[parent_key] = sid
    client_system_data.update(data)
    logger.warning(f"Data received from client")

@sio.event
async def acknowledge_command(sid, result):
    logger.warning(f"Command acknowledged by client {sid}: {result}")

@router.post("/token")
async def get_token(request: TokenRequest):
    room_name = request.roomName
    participant_name = request.participantName

    if not room_name or not participant_name:
        raise HTTPException(status_code=400, detail="Missing roomName or participantName")

    api_key = os.getenv("LIVEKIT_API_KEY")
    api_secret = os.getenv("LIVEKIT_API_SECRET")

    if not api_key or not api_secret:
        raise HTTPException(status_code=500, detail="Server misconfigured: Missing API key/secret")

    # Create AccessToken without identity
    # Create AccessToken with grants as individual parameters
    at = AccessToken(
        api_key=api_key,
        api_secret=api_secret,
        identity=participant_name,  # Set identity directly
        room_join=True,
        room=room_name,
        can_publish=True,
        can_subscribe=True,
        can_publish_data=True
    )
    token = at.to_jwt()
    return {"token": token}

@router.post('/command')
async def command(payload: CommandPayload):
    try:
        response = await process_message(payload.command)
        logger.warning(f"Processed command: {response}")
        logger.warning(f"Emitting command to client with IP: {clients[f'{payload.ip_address}']}")
        await sio.emit('execute_command', response, to=clients[f'{payload.ip_address}'])
        return response
    except Exception as e:
        logger.error(f"Error processing command: {str(e)}")
        raise HTTPException(status_code=500, detail="Internal server error")