automatically select the first in stock variation on woocommerce variable products

I need a code for woocommerce variable products that:

  • Automatically selects the first variation that appears;
  • But if the first variation is out of stock, automatically selects the variation that appears next, and so on;
  • If all variations are out of stock, automatically selects the first variation.

I tried this snippet:

add_filter( 'woocommerce_dropdown_variation_attribute_options_args', 'filter_woocommerce_dropdown_variation_attribute_options_args', 10, 1 );
function filter_woocommerce_dropdown_variation_attribute_options_args( $args ) {
if ( count( $args['options'] ) > 0 ) {
$option_key = '';
$product = $args['product'];
if ( is_a( $product, 'WC_Product_Variable' ) ) {
foreach ( $product->get_available_variations() as $key => $variation ) {
$is_in_stock = $variation['is_in_stock'];
if ( $is_in_stock ) {
$option_key = $key;
break;
}
}
}
if ( is_numeric( $option_key ) ) {
$args['selected'] = $args['options'][$option_key];
}
}
return $args;
}

but doesn’t work in some products, like:

Anyone can help me? Thank you