# nordvpn_set_protocol
# --------------------
# Cambia el protocolo de NordVPN (NordLynx o OpenVPN).
# NordLynx = WireGuard (recomendado por velocidad).
#
# USO (sourced):
#   source nordvpn_set_protocol.sh
#   nordvpn_set_protocol NordLynx
#   nordvpn_set_protocol OpenVPN

nordvpn_set_protocol() {
    local protocol="${1:?nordvpn_set_protocol: se requiere protocolo (NordLynx|OpenVPN)}"

    if ! command -v nordvpn &>/dev/null; then
        echo '{"ok":false,"error":"nordvpn no instalado"}' >&2
        return 1
    fi

    case "$protocol" in
        NordLynx|nordlynx|NORDLYNX) protocol="NordLynx" ;;
        OpenVPN|openvpn|OPENVPN)     protocol="OpenVPN" ;;
        *)
            echo "{\"ok\":false,\"error\":\"protocolo invalido: $protocol (usar NordLynx o OpenVPN)\"}"
            return 1
            ;;
    esac

    local output
    output=$(nordvpn set protocol "$protocol" 2>&1)
    local rc=$?

    if [ $rc -eq 0 ] || echo "$output" | grep -qi "already set\|successfully"; then
        echo "{\"ok\":true,\"protocol\":\"$protocol\"}"
    else
        echo "{\"ok\":false,\"error\":$(echo "$output" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read().strip()))' 2>/dev/null || echo "\"$output\"")}"
        return 1
    fi
}
