refine Nat.fold'_induction (motive := fun k (ivs : Array (Inversion x)) => ivs.Nodup ∧ ∀ iv, iv ∈ ivs → iv.snd.1 < k) n _ #[] ?_ ?_
n : Nat
x : Permutation n
⊢ Array.Nodup
      (Nat.fold' n
        (fun j =>
          Nat.fold' ↑j fun i ivs =>
            if h : x[↑i] > x[↑j] then
              Array.push ivs { fst := Fin.castLE (_ : ↑j ≤ n) i, snd := j, lt := (_ : ↑i < ↑j), inverted := h }
            else ivs)
        #[]) ∧
    ∀ (iv : Inversion x),
      iv ∈
          Nat.fold' n
            (fun j =>
              Nat.fold' ↑j fun i ivs =>
                if h : x[↑i] > x[↑j] then
                  Array.push ivs { fst := Fin.castLE (_ : ↑j ≤ n) i, snd := j, lt := (_ : ↑i < ↑j), inverted := h }
                else ivs)
            #[] →
        ↑iv.snd < n
case refine_1
n : Nat
x : Permutation n
⊢ (fun k ivs => Array.Nodup ivs ∧ ∀ (iv : Inversion x), iv ∈ ivs → ↑iv.snd < k) 0 #[]

case refine_2
n : Nat
x : Permutation n
⊢ ∀ (i : Nat) (hi : i < n) (a : Array (Inversion x)),
    (fun k ivs => Array.Nodup ivs ∧ ∀ (iv : Inversion x), iv ∈ ivs → ↑iv.snd < k) i a →
      (fun k ivs => Array.Nodup ivs ∧ ∀ (iv : Inversion x), iv ∈ ivs → ↑iv.snd < k) (i + 1)
        (Nat.fold' (↑{ val := i, isLt := hi })
          (fun i_1 ivs =>
            if h : x[↑i_1] > x[↑{ val := i, isLt := hi }] then
              Array.push ivs
                { fst := Fin.castLE (_ : ↑{ val := i, isLt := hi } ≤ n) i_1, snd := { val := i, isLt := hi },
                  lt := (_ : ↑i_1 < ↑{ val := i, isLt := hi }), inverted := h }
            else ivs)
          a)