-- WadrayVerification/Aux.lean

import CorelibVerification.Aux.ZMod

import Aegis.Aux.Bool

import Aegis.Aux.ZMod.DivMod

open Sierra

def Wad : Type := UInt128

namespace Wad

def WAD_SCALE : ℕ := 1000000000000000000

variable (w w' : Wad)

protected def toZMod : UInt128 := w

protected def toRat : ℚ := w.toZMod.val / WAD_SCALE

-- Repository definitions used:
content: protected def Wad.div : Wad := (w.toZMod.val * WAD_SCALE / w'.toZMod.val : UInt128)

content: instance : Div Wad := ⟨Wad.div⟩

-- Repository lemmas used:
content: theorem List.getElem_append_left{α : Type u_1} {l₁ l₂ : List α} {i : Nat} (hn : i < l₁.length) :\n(l₁ ++ l₂)[i] = l₁[i]

-- Local definitions used:
content: def Wad : Type := UInt128

content: def WAD_SCALE : ℕ := 1000000000000000000

content: protected def toZMod : UInt128 := w

content: protected def toRat : ℚ := w.toZMod.val / WAD_SCALE

-- Local lemmas used:
content: theorem Rat.nat_cast_div_eq {a b : ℕ} :
    ↑(a / b) = (a : ℚ) / (b : ℚ) - ↑(a % b) / (b : ℚ)

content: theorem WAD_SCALE_rat_pos : 0 < (WAD_SCALE : ℚ)

content: theorem WAD_SCALE_rat_ne_zero : (WAD_SCALE : ℚ) ≠ 0

content: protected theorem div_def :
    w / w' = (w.toZMod.val * WAD_SCALE / w'.toZMod.val : UInt128)

-- Target theorem and proof:
theorem toRat_div (h : w.toZMod.val * WAD_SCALE / w'.toZMod.val < U128_MOD)
    (h' : w'.toZMod.val ≠ 0) :
    |(w / w').toRat - w.toRat / w'.toRat| < 1 / WAD_SCALE
:= by
  have h'' : 0 < w'.toZMod.val := Nat.pos_of_ne_zero h'
  have h''' : (0 : ℚ) < w'.toZMod.val := Nat.cast_pos.mpr h''
  simp only [Wad.toRat, Wad.toZMod, Wad.div_def, ZMod.val_natCast] at *
  rw [Nat.mod_eq_of_lt h, Rat.nat_cast_div_eq, sub_div, Nat.cast_mul,
    div_div, mul_div_mul_right _ _ WAD_SCALE_rat_ne_zero,
    div_div_div_cancel_right _ WAD_SCALE_rat_ne_zero, sub_sub_cancel_left,
    abs_neg, abs_div, Nat.abs_cast, div_lt_div_right WAD_SCALE_rat_pos,
    abs_div, Nat.abs_cast, Nat.abs_cast, div_lt_one h''', Nat.cast_lt]
  apply Nat.mod_lt _ h''