import requests

# Detectar URL del servidor

# ? Definir SERVER_URL
# LOCAL_SERVER_URL = "http://192.168.20.107:4040"             # "http://192.168.20.159:5050"
# PUBLIC_SERVER_URL = "http://updatescapp.itgchile.com:93"    #"http://monitoreo.itgchile.com:93"

import socket
ip = socket.gethostbyname(socket.gethostname())

LOCAL_SERVER_URL_2 = f"http://{ip}:4023";                 # Servidor local backend servidor
ITG_SERVER_URL_1   = "http://192.168.20.150:4023";            # Servidor ITG, accedido internamente
ITG_SERVER_URL_2   = "http://ambiental.itgchile.com:4023"     # Servidor ITG, accedido externamente

# Lista de URLs a probar
URL_TO_TEST        = [ITG_SERVER_URL_2, ITG_SERVER_URL_1, LOCAL_SERVER_URL_2 ] 

# Test Local
# URL_TO_TEST        = [LOCAL_SERVER_URL_2 ] 

# Variable para almacenar la URL del servidor activo
SERVER_URL = None 

def check_server_status(url, timeout=3):
    """
    Verifica si el servidor está activo solicitando su versión.
    Args:
    - url (str): URL del servidor a verificar.
    - timeout (int): Tiempo en segundos para esperar una respuesta.

    Returns:
    - bool: True si el servidor está activo, False en caso contrario.
    """
    # _server_url = f"{url}/ping"
    _server_url = f"{url}/check_server_status"  
    try:
        # response = requests.get(_server_url, timeout=timeout)
        response = requests.head(_server_url, timeout=timeout) 
        response.raise_for_status()  # Esto arrojará un error si la respuesta tiene un código de error HTTP.
        
        if response.status_code == 200:
            return True
    except requests.RequestException as e:
        print(f"Error al consultar la versión del servidor en {url}: {e}")
    return False

def get_active_server_url():
    """
    Determina cuál URL de servidor utilizar y actualiza la variable global SERVER_URL.

    Returns:
    - str: URL del servidor activo.
    """
    global SERVER_URL

    # Iterar sobre cada URL en la lista URL_TO_TEST
    for url in URL_TO_TEST:
        if check_server_status(url):
            print(f"\nConectado a {url} exitosamente\n")
            SERVER_URL = url
            return SERVER_URL

    print("\nError en conexión. No se pudo conectar a ninguno de los servidores.\n")
    return None