import requests
import json

def getUsuarios():
    url = 'https://suite.ekloud.net:1445/Aryve/base/kontrol/usuarios/GetBP/GetUsuario'
    payload = json.dumps({"parametros": {"IdGrupo": -2, "Idactivos": 13}})
    
    headers = {
        'Content-Type': 'application/json',
        'cookie': 'ASP.NET_SessionId=hi5xlpd2iec0pwbjmsud11t2; .AspNet.ApplicationCookie=NCc7HVma9dwuiNCb0eSu-073j4zONkoJ2XsnkZ5GTmVsIuI5BWhu8L48RyGJHxpeMVLRS66DpustdJPGGvkZysR2Xe7_iiM4nyo1eU52917ksbLrTLZ0ncuki3_NzLaskeKd2Zql7z2ELspJd7sXvLxMVxsY-HFIkGzpZyGSa9FdU2AsPQDUxWl68HScRVi953A7pIzLlS-jLtUMg8DvLUjG12syonSKZMHq5n3cL4tX2g3NZo_BrhUp_I78ef8PJs1MRX9gxSjX7rxqKvqeiXEsXk7EAzRWcEq-qEUD2FrhLThtvVDmkfPCkRlTJRfEYzBtahcQxZfAuD7d3c5QhOq_u1L-ViV0_2U-Me2YlP7P5-8A6KHpLveVV-b8oU4yNwVVZhel9mEcrXWjjEqBb6vRP-EZsN6vNou72S-xM2l-PAcbxoFo4A3Oehob9bsrhX9Dz8boXHeePwLMYvpo_Kct0EwLY7pW6JWPWHa9mBuFzezSYcZPll2QPYCjPuUUsowaaNb4OWur3JEc-IAsPeoVGE7n7065vRJEU9puJwI; sidebar_closed=1'
    }

    try:
        # Timeout de 15 segundos para evitar bloqueos infinitos
        response = requests.post(url, headers=headers, data=payload, timeout=15)
        
        print(f"DEBUG: Status Code: {response.status_code}")
        
        if response.status_code != 200:
            print(f"DEBUG: Error del servidor: {response.status_code} - {response.text[:200]}")
            return {}

        # Intentamos cargar el json de forma segura
        try:
            data = response.json()
        except Exception:
            print("DEBUG: La respuesta no es JSON. Contenido recibido:")
            print(response.text[:500])
            return {}

        tmp = {}
        for item in data:
            # Validamos que existan los datos necesarios
            id_usuario = item.get('ID')
            email = item.get('Email')
            nombre = item.get('Nombre')
            apellidos = item.get('Apellidos')

            if email and nombre and apellidos and id_usuario:
                tmp[id_usuario] = {
                    "email": email,
                    "nombre": f"{nombre} {apellidos}"
                }
        
        print(f"DEBUG: Se procesaron {len(tmp)} usuarios exitosamente.")
        return tmp

    except Exception as e:
        print(f"DEBUG: Error de conexión o ejecución: {e}")
        return {}