import Tablet.DecimalGoalVocabularyDefault
import Tablet.F64
import Tablet.F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64
import Tablet.F64_Insts_CoreOpsArithDivF64F64
import Tablet.F64_Insts_CoreOpsArithMulF64F64
import Tablet.F64_Insts_CoreOpsArithNegF64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatExtU64
import Tablet.num_imp_dec2flt_dec2flt
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_parse_parse_inf_nan
import Tablet.num_imp_dec2flt_decimal_Decimal_try_fast_path
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa
import Tablet.num_imp_dec2flt_biased_fp_to_float

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: RoundingDeterminism]
theorem RoundingDeterminism :
    ∀ (x : Real) (a b : F64), 0 <= x -> DecimalGoalVocabularyDefault.roundsMagnitude x a ->
      DecimalGoalVocabularyDefault.roundsMagnitude x b -> a = b := by
-- BODY
  intro x a b hx ha hb
  dsimp [DecimalGoalVocabularyDefault] at ha hb
  let unit : Nat := 2 ^ 52
  let top : Nat := 2047 * unit
  let threshold : Real := (2 : Real) ^ 1024 - (2 : Real) ^ 970
  let value : Nat → Real := fun n =>
    let e := n / 4503599627370496
    let m := n % 4503599627370496
    if e = 0 then (m : Real) / (2 : Real) ^ 1074
    else if 1075 ≤ e then
      ((4503599627370496 + m : Nat) : Real) * (2 : Real) ^ (e - 1075)
    else ((4503599627370496 + m : Nat) : Real) / (2 : Real) ^ (1075 - e)
  have step : ∀ n : Nat, n + 1 < top → value n < value (n + 1) := by
    intro n hn
    let e := n / unit
    let m := n % unit
    have unit_pos : 0 < unit := by norm_num [unit]
    have rem_bound : m < unit := by
      exact Nat.mod_lt _ unit_pos
    have decomp : unit * e + m = n := by
      exact Nat.div_add_mod n unit
    have top_value : top = 9218868437227405312 := by norm_num [top, unit]
    have n_bound : n + 1 < 9218868437227405312 := by simpa [top_value] using hn
    norm_num [unit] at decomp rem_bound n_bound ⊢
    have decomp_symbol : unit * e + m = n := by exact decomp
    by_cases small : m + 1 < 4503599627370496
    · have next_decomp : 4503599627370496 * e + (m + 1) = n + 1 := by omega
      have next_quotient : (n + 1) / 4503599627370496 = e := by
        omega
      have next_remainder : (n + 1) % 4503599627370496 = m + 1 := by
        omega
      have value_n : value n = if e = 0 then (m : Real) / (2 : Real)^1074 else
          if 1075 ≤ e then ((4503599627370496 + m : Nat) : Real) * (2 : Real)^(e-1075)
          else ((4503599627370496 + m : Nat) : Real) / (2 : Real)^(1075-e) := by
        dsimp [value]
        rw [← decomp]
        have quotient : (4503599627370496 * e + m) / 4503599627370496 = e := by
          rw [Nat.mul_add_div (by norm_num)]
          simp [Nat.div_eq_of_lt rem_bound]
        have remainder : (4503599627370496 * e + m) % 4503599627370496 = m := by
          rw [Nat.mul_add_mod]
          simp [Nat.mod_eq_of_lt rem_bound]
        simp [quotient, remainder] <;> ring
      have value_next : value (n+1) = if e = 0 then (m+1 : Real) / (2 : Real)^1074 else
          if 1075 ≤ e then ((4503599627370496 + m + 1 : Nat) : Real) * (2 : Real)^(e-1075)
          else ((4503599627370496 + m + 1 : Nat) : Real) / (2 : Real)^(1075-e) := by
        dsimp [value]
        rw [← next_decomp]
        have quotient : (4503599627370496 * e + (m + 1)) / 4503599627370496 = e := by
          rw [Nat.mul_add_div (by norm_num)]
          simp [Nat.div_eq_of_lt (by omega)]
        have remainder : (4503599627370496 * e + (m + 1)) % 4503599627370496 = m + 1 := by
          rw [Nat.mul_add_mod]
          simp [Nat.mod_eq_of_lt (by omega)]
        simp only [quotient, remainder, Nat.cast_add]
        by_cases z : e = 0
        · simp [z] <;> ring
        · by_cases h : 1075 ≤ e
          · simp [z, h] <;> ring
          · simp [z, h] <;> ring
      rw [value_n, value_next]
      by_cases zero : e = 0
      · simp [zero]
        apply (div_lt_div_iff_of_pos_right (by positivity)).2
        norm_num
      · by_cases high : 1075 ≤ e
        · simp [zero, high]
        · simp [zero, high]
          apply (div_lt_div_iff_of_pos_right (by positivity)).2
          norm_num
    · have edge : m + 1 = 4503599627370496 := by omega
      have next_decomp : 4503599627370496 * (e + 1) = n + 1 := by omega
      have next_quotient : (n + 1) / 4503599627370496 = e + 1 := by
        omega
      have next_remainder : (n + 1) % 4503599627370496 = 0 := by
        omega
      have value_n : value n = if e = 0 then (m : Real) / (2 : Real)^1074 else
          if 1075 ≤ e then ((4503599627370496 + m : Nat) : Real) * (2 : Real)^(e-1075)
          else ((4503599627370496 + m : Nat) : Real) / (2 : Real)^(1075-e) := by
        dsimp [value]
        rw [← decomp]
        have quotient : (4503599627370496 * e + m) / 4503599627370496 = e := by
          rw [Nat.mul_add_div (by norm_num)]
          simp [Nat.div_eq_of_lt rem_bound]
        have remainder : (4503599627370496 * e + m) % 4503599627370496 = m := by
          rw [Nat.mul_add_mod]
          simp [Nat.mod_eq_of_lt rem_bound]
        simp [quotient, remainder]
      have value_next : value (n+1) = if e+1 = 0 then (0 : Real) / (2 : Real)^1074 else
          if 1075 ≤ e+1 then ((4503599627370496 : Nat) : Real) * (2 : Real)^((e+1)-1075)
          else ((4503599627370496 : Nat) : Real) / (2 : Real)^ (1075-(e+1)) := by
        dsimp [value]
        rw [← next_decomp]
        have quotient : (4503599627370496 * (e + 1)) / 4503599627370496 = e + 1 := by
          rw [show 4503599627370496 * (e + 1) = (e + 1) * 4503599627370496 by ring]
          exact Nat.mul_div_left _ (by norm_num)
        have remainder : (4503599627370496 * (e + 1)) % 4503599627370496 = 0 := by
          exact Nat.mul_mod_right _ _
        simp [quotient, remainder] <;> ring
      rw [value_n, value_next]
      by_cases zero : e = 0
      · have m_edge : m = 4503599627370495 := by omega
        have next_zero : ¬e + 1 = 0 := by omega
        have next_high : ¬1075 ≤ e + 1 := by omega
        simp only [if_pos zero, if_neg next_zero, if_neg next_high]
        rw [m_edge]
        rw [show 1075 - (e + 1) = 1074 by omega]
        apply (div_lt_div_iff_of_pos_right (by positivity)).2
        norm_num
      · by_cases boundary : e = 1074
        · have low : e < 1075 := by omega
          have not_high : ¬1075 ≤ e := by omega
          have next_high : 1075 ≤ e + 1 := by omega
          have next_zero : ¬e + 1 = 0 := by omega
          simp only [if_neg zero, if_neg not_high, if_pos boundary,
            if_neg next_zero, if_pos next_high]
          rw [show 1075 - e = 1 by omega, show e + 1 - 1075 = 0 by omega]
          have cast_bound : (m : Real) < 4503599627370496 := by exact_mod_cast rem_bound
          norm_num at ⊢
          linarith
        · by_cases high : 1075 ≤ e
          · have high2 : 1074 ≤ e := by omega
            have next_zero : ¬e + 1 = 0 := by omega
            have next_high : 1075 ≤ e + 1 := by omega
            simp only [if_neg zero, if_pos high, if_neg next_zero, if_pos next_high]
            rw [show e + 1 - 1075 = e - 1074 by omega]
            have pos : (0 : Real) < (2 : Real)^(e-1075) := by positivity
            have cast_bound : (m : Real) < 4503599627370496 := by exact_mod_cast rem_bound
            have cast_sum : ((4503599627370496 + m : Nat) : Real) =
                (4503599627370496 : Real) + m := by norm_num
            rw [cast_sum]
            have nextpow : (2 : Real)^(e-1074) = 2 * (2 : Real)^(e-1075) := by
              rw [show e-1074 = (e-1075)+1 by omega, pow_succ]
              ring
            rw [nextpow]
            have base : (4503599627370496 : Real) + m < 2 * 4503599627370496 := by
              linarith
            calc
              (4503599627370496 + (m : Real)) * (2 : Real)^(e-1075) <
                  (2 * 4503599627370496 : Real) * (2 : Real)^(e-1075) :=
                mul_lt_mul_of_pos_right base pos
              _ = 4503599627370496 * (2 * (2 : Real)^(e-1075)) := by ring
          · have low : e < 1075 := by omega
            have low2 : e < 1074 := by omega
            have not_high : ¬1074 ≤ e := by omega
            have next_zero : ¬e + 1 = 0 := by omega
            have next_high : ¬1075 ≤ e + 1 := by omega
            simp only [if_neg zero, if_neg high, if_neg next_zero, if_neg next_high]
            rw [show 1075 - (e + 1) = 1074 - e by omega]
            have cast_bound : (m : Real) < 4503599627370496 := by exact_mod_cast rem_bound
            have cast_sum : ((4503599627370496 + m : Nat) : Real) =
                (4503599627370496 : Real) + m := by norm_num
            rw [cast_sum]
            have denrel : (2 : Real)^(1075-e) = 2 * (2 : Real)^(1074-e) := by
              rw [show 1075-e = (1074-e)+1 by omega, pow_succ]
              ring
            have rhs : (4503599627370496 : Real) / (2 : Real)^(1074-e) =
                (2 * 4503599627370496 : Real) / (2 : Real)^(1075-e) := by
              rw [denrel]
              apply (div_eq_div_iff (by positivity) (by positivity)).2
              ring
            have base : (4503599627370496 : Real) + m < 2 * 4503599627370496 := by
              linarith
            exact ((div_lt_div_iff_of_pos_right (by positivity)).2 base).trans_eq rhs.symm
  have chain : ∀ p k : Nat, 0 < k → p + k < top → value p < value (p + k) := by
    intro p k hk hbound
    induction k with
    | zero => omega
    | succ k ih =>
        by_cases base : k = 0
        · subst k
          simpa using step p (by omega)
        · have prior : value p < value (p + k) := ih (by omega) (by omega)
          have next : value (p + k) < value (p + k + 1) := by
            apply step
            omega
          exact prior.trans next
  have monotone : ∀ p q : Nat, p < q → q < top → value p < value q := by
    intro p q hp hq
    obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le (Nat.le_of_lt hp)
    have hk : 0 < k := by omega
    exact chain p k hk hq
  change 0 ≤ x ∧ (↑a : Nat) ≤ top ∧
    (if (↑a : Nat) = top then threshold ≤ x else
      x < threshold ∧ ∀ v : F64, (↑v : Nat) < top → v ≠ a →
        abs (x - value (↑a : Nat)) ≤ abs (x - value (↑v : Nat)) ∧
        (abs (x - value (↑a : Nat)) = abs (x - value (↑v : Nat)) →
          (↑a : Nat) % 2 = 0)) at ha
  change 0 ≤ x ∧ (↑b : Nat) ≤ top ∧
    (if (↑b : Nat) = top then threshold ≤ x else
      x < threshold ∧ ∀ v : F64, (↑v : Nat) < top → v ≠ b →
        abs (x - value (↑b : Nat)) ≤ abs (x - value (↑v : Nat)) ∧
        (abs (x - value (↑b : Nat)) = abs (x - value (↑v : Nat)) →
          (↑b : Nat) % 2 = 0)) at hb
  have word_eq : ∀ u v : F64, (↑u : Nat) = ↑v → u = v := by
    intro u v h
    cases u with
    | mk ub =>
        cases v with
        | mk vb =>
            congr
            apply BitVec.eq_of_toNat_eq
            change ub.toNat = vb.toNat at h
            exact h
  have make_word : ∀ n : Nat, n < top → ∃ c : F64, (↑c : Nat) = n := by
    intro n hn
    have bound : n ≤ UScalar.cMax UScalarTy.U64 := by
      apply le_trans (Nat.le_of_lt hn)
      norm_num [top, unit, UScalar.cMax, UScalar.rMax, U64.rMax, UScalarTy.numBits]
    refine ⟨UScalar.ofNat n bound, ?_⟩
    rfl
  have closer : ∀ A Z B : Real, A < Z → Z < B →
      abs (x - A) = abs (x - B) → abs (x - Z) < abs (x - A) := by
    intro A Z B hAZ hZB hEq
    have between : A < x ∧ x < B := by
      constructor
      · by_contra h
        have hxA : x ≤ A := le_of_not_gt h
        have hxB : x ≤ B := le_trans hxA (le_of_lt (hAZ.trans hZB))
        rw [abs_of_nonpos (sub_nonpos.mpr hxA), abs_of_nonpos (sub_nonpos.mpr hxB)] at hEq
        linarith
      · by_contra h
        have hBx : B ≤ x := le_of_not_gt h
        have hAx : A ≤ x := le_trans (le_of_lt hAZ)
          (le_trans (le_of_lt hZB) hBx)
        rw [abs_of_nonneg (sub_nonneg.mpr hAx), abs_of_nonneg (sub_nonneg.mpr hBx)] at hEq
        linarith
    rcases le_total Z x with hZx | hxZ
    · rw [abs_of_nonneg (sub_nonneg.mpr hZx),
        abs_of_nonneg (sub_nonneg.mpr between.1.le)]
      linarith
    · have hAeqB : abs (x - A) = B - x := by
        rw [abs_of_nonpos (sub_nonpos.mpr between.2.le)] at hEq
        simpa [sub_eq_add_neg] using hEq
      calc
        abs (x - Z) = Z - x := by
          rw [abs_of_nonpos (sub_nonpos.mpr hxZ)]
          ring
        _ < B - x := by linarith
        _ = abs (x - A) := hAeqB.symm
  by_cases high : threshold ≤ x
  · have atop : (↑a : Nat) = top := by
      by_contra h
      have condition := (ha.2).2
      simp [h] at condition
      have hfinite : x < threshold := by
        exact condition.1
      exact (not_lt_of_ge high) hfinite
    have btop : (↑b : Nat) = top := by
      by_contra h
      have condition := (hb.2).2
      simp [h] at condition
      have hfinite : x < threshold := by
        exact condition.1
      exact (not_lt_of_ge high) hfinite
    apply word_eq
    omega
  · have low : x < threshold := lt_of_not_ge high
    have atop : (↑a : Nat) ≠ top := by
      intro h
      have hthreshold : threshold ≤ x := by simpa [h] using (ha.2).2
      exact (not_le_of_gt low) hthreshold
    have btop : (↑b : Nat) ≠ top := by
      intro h
      have hthreshold : threshold ≤ x := by simpa [h] using (hb.2).2
      exact (not_le_of_gt low) hthreshold
    have alt : (↑a : Nat) < top := by omega
    have blt : (↑b : Nat) < top := by omega
    have ha_finite := (ha.2).2
    have hb_finite := (hb.2).2
    simp [atop] at ha_finite
    simp [btop] at hb_finite
    have anear := ha_finite.2
    have bnear := hb_finite.2
    by_cases indices : (↑a : Nat) = ↑b
    · exact word_eq a b indices
    · have words : a ≠ b := by
        intro h
        apply indices
        simpa [h]
      have dab := anear b blt (by intro h; exact indices h.symm)
      have dba := bnear a alt (by intro h; exact indices h)
      have equal_distance : abs (x - value (↑a : Nat)) = abs (x - value (↑b : Nat)) :=
        le_antisymm dab.1 dba.1
      have even_a : (↑a : Nat) % 2 = 0 := dab.2 equal_distance
      have even_b : (↑b : Nat) % 2 = 0 := dba.2 equal_distance.symm
      by_cases order : (↑a : Nat) < ↑b
      · have no_gap : ¬(↑a : Nat) + 1 < ↑b := by
          intro gap
          obtain ⟨c, hc⟩ := make_word ((↑a : Nat) + 1) (by omega)
          have c_lt : (↑c : Nat) < top := by simpa [hc] using show (↑a : Nat) + 1 < top by omega
          have c_ne : (↑c : Nat) ≠ (↑a : Nat) := by
            intro h
            rw [hc] at h
            omega
          have competitor := anear c c_lt c_ne
          have left_step := monotone (↑a : Nat) ((↑a : Nat) + 1) (by omega) (by omega)
          have right_step := monotone ((↑a : Nat) + 1) (↑b : Nat) gap blt
          have middle : abs (x - value ((↑a : Nat) + 1)) < abs (x - value (↑a : Nat)) :=
            closer (value (↑a : Nat)) (value ((↑a : Nat) + 1)) (value (↑b : Nat))
              left_step right_step equal_distance
          have competitor' : abs (x - value (↑a : Nat)) ≤
              abs (x - value ((↑a : Nat) + 1)) := by
            simpa [hc] using competitor.1
          exact (not_lt_of_ge competitor') middle
        have consecutive : (↑b : Nat) = (↑a : Nat) + 1 := by omega
        have : False := by omega
        exact this.elim
      · have order' : (↑b : Nat) < (↑a : Nat) := by omega
        have no_gap : ¬(↑b : Nat) + 1 < ↑a := by
          intro gap
          obtain ⟨c, hc⟩ := make_word ((↑b : Nat) + 1) (by omega)
          have c_lt : (↑c : Nat) < top := by simpa [hc] using show (↑b : Nat) + 1 < top by omega
          have c_ne : (↑c : Nat) ≠ (↑b : Nat) := by
            intro h
            rw [hc] at h
            omega
          have competitor := bnear c c_lt c_ne
          have left_step := monotone (↑b : Nat) ((↑b : Nat) + 1) (by omega) (by omega)
          have right_step := monotone ((↑b : Nat) + 1) (↑a : Nat) gap alt
          have middle : abs (x - value ((↑b : Nat) + 1)) < abs (x - value (↑b : Nat)) :=
            closer (value (↑b : Nat)) (value ((↑b : Nat) + 1)) (value (↑a : Nat))
              left_step right_step equal_distance.symm
          have competitor' : abs (x - value (↑b : Nat)) ≤
              abs (x - value ((↑b : Nat) + 1)) := by
            simpa [hc] using competitor.1
          exact (not_lt_of_ge competitor') middle
        have consecutive : (↑a : Nat) = (↑b : Nat) + 1 := by omega
        have : False := by omega
        exact this.elim

end dec2flt_model
