"""Cliente HTTP para comunicarse con los Hardware Agents."""
import httpx
from config import REGISTERED_AGENTS

TIMEOUT = httpx.Timeout(60.0, connect=5.0)


def get_agent_url(agent_id=None):
    """Obtiene la URL base de un agent.
    Si se pasa agent_id, busca ese agent especifico.
    Si no, usa el primero disponible (compatibilidad con un solo agent).
    Retorna URL string o None si no hay agents.
    """
    if agent_id and agent_id in REGISTERED_AGENTS:
        a = REGISTERED_AGENTS[agent_id]
        return f"http://{a['host']}:{a['port']}"

    # Sin agent_id: usar el primero disponible
    if REGISTERED_AGENTS:
        first_id = next(iter(REGISTERED_AGENTS))
        a = REGISTERED_AGENTS[first_id]
        return f"http://{a['host']}:{a['port']}"

    return None


async def get_agent_status(agent_id=None):
    """Consulta el estado de un Hardware Agent."""
    url = get_agent_url(agent_id)
    if not url:
        return {
            'agent_reachable': False,
            'programmer_connected': False,
            'message': 'Ningun agent registrado',
        }
    try:
        async with httpx.AsyncClient(timeout=TIMEOUT) as client:
            resp = await client.get(f"{url}/status")
            data = resp.json()
            return {
                'agent_reachable': True,
                'programmer_connected': data.get('programmer_connected', False)
            }
    except Exception:
        return {
            'agent_reachable': False,
            'programmer_connected': False
        }


async def program_wristband(red_minutes, green_minutes, blue_minutes,
                            session_id=None, timeout=30, agent_id=None,
                            token=None):
    """Envia comando de programacion a un Hardware Agent."""
    url = get_agent_url(agent_id)
    if not url:
        return {'status': 'error', 'message': 'Ningun agent registrado'}
    try:
        headers = {}
        if token:
            headers['Authorization'] = f'Bearer {token}'

        async with httpx.AsyncClient(timeout=TIMEOUT) as client:
            resp = await client.post(
                f"{url}/program",
                json={
                    'red_minutes': red_minutes,
                    'green_minutes': green_minutes,
                    'blue_minutes': blue_minutes,
                    'session_id': session_id,
                    'timeout': timeout,
                },
                headers=headers,
            )
            return resp.json()
    except httpx.ConnectError:
        return {'status': 'error', 'message': 'Hardware Agent no disponible'}
    except httpx.ReadTimeout:
        return {'status': 'timeout'}
    except Exception as e:
        return {'status': 'error', 'message': str(e)}
