import socketio, asyncio, logging

from socketio.async_server import AsyncServer
from fastapi import APIRouter
from agents.client_agent import command_formater

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")

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

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

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 command(sid, command):
    try:
        logger.warning(f"Command received from client: {command} for {clients[f'{ip}']}")
        formatted_command = await command_formater(command)  # Await the async function
        logger.warning(f"Formatted command: {formatted_command}")
        # await sio.emit('execute_command', command, to=clients[f'{ip}'])
    except Exception as e:
        logger.error(f"Error sending command: {e}")


@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):
    parent_key = list(data.keys())[0]
    clients[parent_key] = sid
    client_system_data.update(data)
    logger.warning(f"Data received from client")
