How to Filter categories in the permalink structure

strangely familiar to this, but it is different, so here’s a modified version

add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename ){

    $cats = get_the_category( $post->ID );
    if ( $cats ) {
        // Make sure we use the same start cat as the permalink generator
        // what happens now actually is the opposite,
        // we end up using the latest category that has a parent
        usort( $cats, '_usort_terms_by_ID' ); // order by ID

        foreach( $cats as $cat ) {

          if ( $cat->parent ) {
              // If there are parent categories, collect them and pick the top most
              $parentcats = explode(" ",get_category_parents( $cat, false, ' ', true ));
              $topcat = $parentcats[0];

          } else {
              $topcat = $cat->slug;
          }
        }
    }
    $permalink = home_url()."https://wordpress.stackexchange.com/".$topcat."https://wordpress.stackexchange.com/".$post->post_name;
    return $permalink;
}