-- 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

protected def mul : Wad := (w.toZMod.val * w'.toZMod.val / WAD_SCALE : UInt128)

end Wad

namespace Ray

variable (r r' : Ray)

end Ray

def SignedWad := UInt128 × (Unit ⊕ Unit)

namespace SignedWad

instance : Inhabited SignedWad := ⟨default, default⟩

variable (w w₁ w₂ : SignedWad)

def sign : ℤ := if SierraBool.toBool w.2 then -1 else 1

instance : Zero SignedWad := ⟨(0, false.toSierraBool)⟩

def toRat : ℚ := if w.2 then -(Wad.toRat w.1) else Wad.toRat w.1

protected def mul : SignedWad :=
⟨Wad.mul (w₁.1 : Wad) (w₂.1 : Wad), Bool.toSierraBool (Bool.xor (SierraBool.toBool w₁.2) (SierraBool.toBool w₂.2))⟩

instance : Mul SignedWad := ⟨SignedWad.mul⟩

-- Repository definitions used:
content: ...

-- 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

content: protected def mul : Wad := (w.toZMod.val * w'.toZMod.val / WAD_SCALE : UInt128)

content: def SignedWad := UInt128 × (Unit ⊕ Unit)

content: def toRat : ℚ := if w.2 then -(Wad.toRat w.1) else Wad.toRat w.1

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

content: theorem WAD_SCALE_pos : 0 < WAD_SCALE

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

content: theorem mul_def :
    w₁ * w₂ = ⟨Wad.mul (w₁.1 : Wad) (w₂.1 : Wad), Bool.toSierraBool (Bool.xor (SierraBool.toBool w₁.2) (SierraBool.toBool w₂.2))⟩

-- Target theorem and proof:
theorem toRat_mul (h₁ : w₁.1.val * w₂.1.val / Wad.WAD_SCALE < U128_MOD ):
    |SignedWad.toRat (w₁ * w₂) - SignedWad.toRat w₁ * SignedWad.toRat w₂| < 1 / Wad.WAD_SCALE
:= by
  rcases w₁ with ⟨w₁, s₁⟩
  rcases w₂ with ⟨w₂, s₂⟩
  rcases s₁ with (⟨⟨⟩⟩|⟨⟨⟩⟩) <;> rcases s₂ with (⟨⟨⟩⟩|⟨⟨⟩⟩)
    <;> dsimp only at h₁
    <;> simp [mul_def, toRat, Wad.mul, Wad.toRat, Wad.toZMod, Nat.mod_eq_of_lt h₁, -one_div]
    <;> rw [Rat.nat_cast_div_eq, Nat.cast_mul, ZMod.natCast_val, ZMod.natCast_val, mul_div_assoc,
      sub_div, div_mul_eq_mul_div]
    <;> [rw [sub_right_comm, sub_self, zero_sub, abs_neg];
       rw [neg_sub, sub_add_cancel];
       rw [neg_sub, sub_add_cancel];
       rw [sub_right_comm, sub_self, zero_sub, abs_neg]]
    <;> rw [abs_div,
      Nat.abs_cast, div_lt_div_right Wad.WAD_SCALE_rat_pos, abs_div, Nat.abs_cast,
      Nat.abs_cast, div_lt_one Wad.WAD_SCALE_rat_pos, Nat.cast_lt]
    <;> apply Nat.mod_lt _ Wad.WAD_SCALE_pos