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: RoundingTotality]
theorem RoundingTotality :
    ∀ x : Real, 0 <= x -> ∃ target : F64, DecimalGoalVocabularyDefault.roundsMagnitude x target := by
-- BODY
  set_option maxHeartbeats 800000 in
    exact (by
      intro x hx
      dsimp [DecimalGoalVocabularyDefault]
      let unit : Nat := 2 ^ 52
      let top : Nat := 9218868437227405312
      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 ⊢
        by_cases small : m + 1 < 4503599627370496
        · have next_decomp : 4503599627370496 * e + (m + 1) = n + 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 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 not_high : ¬1075 ≤ 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 not_high, 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 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 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)
        exact chain p k (by omega) hq
      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 bound : top ≤ UScalar.cMax UScalarTy.U64 := by
          have top_value : top = 9218868437227405312 := by norm_num [top, unit]
          rw [top_value]
          norm_num [UScalar.cMax, UScalar.rMax, U64.rMax, UScalarTy.numBits]
        let w : F64 := UScalar.ofNat top bound
        refine ⟨w, ?_⟩
        change 0 ≤ x ∧ (↑w : Nat) ≤ top ∧
          (if (↑w : Nat) = top then threshold ≤ x else
            x < threshold ∧ ∀ v : F64, (↑v : Nat) < top → v ≠ w →
              abs (x - value (↑w : Nat)) ≤ abs (x - value (↑v : Nat)) ∧
              (abs (x - value (↑w : Nat)) = abs (x - value (↑v : Nat)) →
                (↑w : Nat) % 2 = 0))
        have hw : (↑w : Nat) = top := by rfl
        refine ⟨hx, ?_, ?_⟩
        · omega
        · rw [if_pos hw]
          exact high
      · have low : x < threshold := lt_of_not_ge high
        let dist : Nat → Real := fun n => abs (x - value n)
        let candidates : Set Nat := {n | n < top}
        have candidates_finite : candidates.Finite := by
          exact Set.toFinite candidates
        have candidates_nonempty : candidates.Nonempty := by
          refine ⟨0, ?_⟩
          change 0 < top
          norm_num [top, unit]
        obtain ⟨r0, hr0, hmin⟩ := Set.exists_min_image candidates dist candidates_finite candidates_nonempty
        have hmin_nat : ∀ n : Nat, n < top → dist r0 ≤ dist n := by
          intro n hn
          exact hmin n hn
        let property : Nat → Prop := fun n => n < top ∧ dist n = dist r0
        have property_exists : ∃ n, property n := ⟨r0, hr0, rfl⟩
        let r := Nat.find property_exists
        have rprop : property r := by exact Nat.find_spec property_exists
        have hr_lt : r < top := rprop.1
        have rbase : dist r = dist r0 := rprop.2
        have least_index : ∀ n : Nat, n < top → dist n = dist r0 → r ≤ n := by
          intro n hn heq
          exact Nat.find_min' property_exists ⟨hn, heq⟩
        set_option maxHeartbeats 800000 in
          have adjacent : ∀ p q : Nat, p < top → q < top →
              dist p = dist r → dist q = dist r → p < q → q = p + 1 := by
            intro p q hp hq pmin qmin hpq
            by_contra gap
            have left_step : value p < value (p + 1) := monotone p (p + 1) (by omega) (by omega)
            have right_step : value (p + 1) < value q := monotone (p + 1) q (by omega) hq
            have middle : dist (p + 1) < dist p := by
              exact closer (value p) (value (p + 1)) (value q) left_step right_step
                (pmin.trans qmin.symm)
            have min_p : dist p ≤ dist (p + 1) := by
              calc dist p = dist r0 := pmin.trans rbase
                   _ ≤ dist (p + 1) := hmin_nat (p + 1) (by omega)
            exact (not_lt_of_ge min_p) middle
        have minimum_property : ∀ n : Nat, n < top → dist r ≤ dist n := by
          intro n hn
          calc dist r = dist r0 := rbase
               _ ≤ dist n := hmin_nat n hn
        have finish : ∀ chosen : Nat, chosen < top →
            (∀ n : Nat, n < top → dist chosen ≤ dist n) →
            ((chosen % 2 = 0) ∨ (∀ n : Nat, n < top → dist chosen = dist n → n = chosen)) →
            ∃ target : F64,
              0 ≤ x ∧ (↑target : Nat) ≤ top ∧
              (if (↑target : Nat) = top then threshold ≤ x else
                x < threshold ∧ ∀ v : F64, (↑v : Nat) < top → v ≠ target →
                  abs (x - value (↑target : Nat)) ≤ abs (x - value (↑v : Nat)) ∧
                  (abs (x - value (↑target : Nat)) = abs (x - value (↑v : Nat)) →
                    (↑target : Nat) % 2 = 0)) := by
          intro chosen chosen_lt chosen_min choice_rule
          obtain ⟨w, hw⟩ := make_word chosen chosen_lt
          refine ⟨w, ?_⟩
          change 0 ≤ x ∧ (↑w : Nat) ≤ top ∧
            (if (↑w : Nat) = top then threshold ≤ x else
              x < threshold ∧ ∀ v : F64, (↑v : Nat) < top → v ≠ w →
                abs (x - value (↑w : Nat)) ≤ abs (x - value (↑v : Nat)) ∧
                (abs (x - value (↑w : Nat)) = abs (x - value (↑v : Nat)) →
                  (↑w : Nat) % 2 = 0))
          have wval : (↑w : Nat) = chosen := hw
          have wnot : (↑w : Nat) ≠ top := by omega
          refine ⟨hx, ?_, ?_⟩
          · omega
          · rw [if_neg wnot]
            refine ⟨low, ?_⟩
            intro v hv hne
            have vn : (↑v : Nat) < top := hv
            have bound_dist := chosen_min (↑v : Nat) vn
            constructor
            · simpa [dist, wval] using bound_dist
            · intro equal_dist
              rcases choice_rule with even | unique
              · simpa [wval] using even
              · have index_equal : (↑v : Nat) = chosen := by
                  apply unique (↑v : Nat) vn
                  simpa [dist, wval] using equal_dist
                have value_equal : (↑v : Nat) = (↑w : Nat) := index_equal.trans wval.symm
                have word_equal : v = w := word_eq v w value_equal
                exact (hne word_equal).elim
        by_cases even : r % 2 = 0
        · exact finish r hr_lt minimum_property (Or.inl even)
        · by_cases next : r + 1 < top ∧ dist r = dist (r + 1)
          · have next_min : ∀ n : Nat, n < top → dist (r + 1) ≤ dist n := by
              intro n hn
              rw [← next.2]
              exact minimum_property n hn
            have next_even : (r + 1) % 2 = 0 := by omega
            exact finish (r + 1) next.1 next_min (Or.inl next_even)
          · have unique : ∀ n : Nat, n < top → dist r = dist n → n = r := by
              intro n hn heq
              by_cases nr : n = r
              · exact nr
              · have nbase : dist n = dist r0 := by exact heq.symm.trans rbase
                have rle : r ≤ n := least_index n hn nbase
                have order : r < n := by omega
                have adjacent_right : n = r + 1 := by
                  set_option maxRecDepth 1000000 in
                    exact adjacent r n hr_lt hn (by rfl) heq.symm order
                exfalso
                apply next
                have next_value : dist r = dist (r + 1) := by
                  calc dist r = dist n := heq
                       _ = dist (r + 1) := by rw [adjacent_right]
                exact ⟨by omega, next_value⟩
            exact finish r hr_lt minimum_property (Or.inr unique)
    )

end dec2flt_model
