import Tablet.DecimalGoalVocabularyDefault
import Tablet.ParserExponentConstants
import Tablet.F64_Insts_CoreOpsArithDivF64F64
import Tablet.F64_Insts_CoreOpsArithMulF64F64
import Tablet.F64_Insts_CoreOpsArithNegF64
import Tablet.F64_Insts_Dec2flt_modelNumImpDec2fltLemireU64
import Tablet.F64_Insts_Dec2flt_modelNumImpTraitsFloatU64
import Tablet.num_imp_dec2flt_Dec2FltAssemblyTrace
import Tablet.num_imp_dec2flt_biased_fp_to_float
import Tablet.num_imp_dec2flt_common_BiasedFp_Insts_CoreCmpPartialEqBiasedFp_eq
import Tablet.num_imp_dec2flt_common_BiasedFp_zero_pow2
import Tablet.num_imp_dec2flt_dec2flt_with_trace
import Tablet.num_imp_dec2flt_decimal_seq_DecimalSeq
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq
import Tablet.num_imp_dec2flt_lemire_compute_float
import Tablet.num_imp_dec2flt_parse_parse_number
import Tablet.num_imp_dec2flt_slow_parse_long_mantissa

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: ParserSlowControlFlow]
theorem ParserSlowControlFlow :
    forall (s : Str) (f : F64)
      (tr : num.imp.dec2flt.Dec2FltAssemblyTrace F64)
      (r : num.imp.dec2flt.decimal.Decimal),
      DecimalGoalVocabularyDefault.sourceString s ->
      num.imp.dec2flt.dec2flt_with_trace
        F64.Insts.Dec2flt_modelNumImpDec2fltLemireU64
        F64.Insts.CoreOpsArithDivF64F64 F64.Insts.CoreOpsArithMulF64F64
        F64.Insts.CoreOpsArithNegF64 s =
          ok (core.result.Result.Ok f,
            num.imp.dec2flt.Dec2FltTrace.Assembled tr) ->
      tr.slow_path_guard = true ->
      num.imp.dec2flt.parse.parse_number tr.body = ok (some r) ->
      (r.many_digits = true -> 0 < r.mantissa.val) ->
      -342 <= r.exponent.val /\ r.exponent.val <= 308 /\
        exists d : num.imp.dec2flt.decimal_seq.DecimalSeq,
          num.imp.dec2flt.decimal_seq.parse_decimal_seq tr.body = ok d /\
          num.imp.dec2flt.slow.parse_long_mantissa
            F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 tr.body =
              ok tr.selected_pair := by
-- BODY
  intro s f tr target hsource htrace hslow hparse hpositive
  have bind_ok_inv : forall {alpha beta : Type} (x : Result alpha)
      (g : alpha -> Result beta) y,
      Bind.bind x g = ok y -> exists z, x = ok z /\ g z = ok y := by
    intro alpha beta x g y hx
    cases x with
    | fail err => simp [Bind.bind, Aeneas.Std.bind] at hx
    | div => simp [Bind.bind, Aeneas.Std.bind] at hx
    | ok z => exact ⟨z, rfl, hx⟩
  rcases ParserExponentConstants with
    ⟨hbits, htotal, hsig, hexpbits, hexpsat, hinf, hbias, hmin,
      hsmall, hlarge, hroundmin, hroundmax⟩
  have compute_low : forall (q : Std.I64) (w : Std.U64), q.val < -342 ->
      num.imp.dec2flt.lemire.compute_float
          F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 q w =
        ok { m := 0#u64, p_biased := 0#i32 } := by
    intro q w hq
    unfold num.imp.dec2flt.lemire.compute_float
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 0#i32 =
      ok { m := 0#u64, p_biased := 0#i32 } by rfl, hinf]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 2047#i32 =
      ok { m := 0#u64, p_biased := 2047#i32 } by rfl]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 (-1)#i32 =
      ok { m := 0#u64, p_biased := (-1)#i32 } by rfl]
    simp only [bind_tc_ok]
    by_cases hw : w = 0#u64
    · simp [hw]
    · simp only [hw, if_false]
      rw [F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SMALLEST_POWER_OF_TEN.eq_def]
      rw [show lift (IScalar.cast .I64 (-342)#i32) = ok (-342)#i64 by rfl]
      simp only [bind_tc_ok]
      have hq' : q < (-342)#i64 := by
        simpa only [IScalar.lt_equiv] using hq
      simp [hq']
  have compute_high : forall (q : Std.I64) (w : Std.U64),
      308 < q.val -> 0 < w.val ->
      num.imp.dec2flt.lemire.compute_float
          F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 q w =
        ok { m := 0#u64, p_biased := 2047#i32 } := by
    intro q w hq hwpos
    unfold num.imp.dec2flt.lemire.compute_float
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 0#i32 =
      ok { m := 0#u64, p_biased := 0#i32 } by rfl, hinf]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 2047#i32 =
      ok { m := 0#u64, p_biased := 2047#i32 } by rfl]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 (-1)#i32 =
      ok { m := 0#u64, p_biased := (-1)#i32 } by rfl]
    simp only [bind_tc_ok]
    have hw : w ≠ 0#u64 := by
      intro heq
      have := UScalar.val_eq_of_eq heq
      simp at this
      omega
    simp only [hw, if_false]
    rw [F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.SMALLEST_POWER_OF_TEN.eq_def]
    rw [show lift (IScalar.cast .I64 (-342)#i32) = ok (-342)#i64 by rfl]
    simp only [bind_tc_ok]
    have hnlow : ¬ (q < (-342)#i64) := by
      have hqval : 308 < q.val := hq
      have hnlowVal : ¬ (q.val < (-342 : Int)) :=
        not_lt.mpr (le_trans (by norm_num : (-342 : Int) ≤ 308)
          (le_of_lt hqval))
      simpa only [IScalar.lt_equiv] using hnlowVal
    simp only [hnlow, if_false]
    rw [F64.Insts.Dec2flt_modelNumImpTraitsFloatU64.LARGEST_POWER_OF_TEN.eq_def]
    rw [show lift (IScalar.cast .I64 308#i32) = ok 308#i64 by rfl]
    simp only [bind_tc_ok]
    have hq' : q > 308#i64 := by
      simpa only [IScalar.lt_equiv] using hq
    simp [hq']
  have compute_zero : forall (q : Std.I64),
      num.imp.dec2flt.lemire.compute_float
          F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 q (0#u64) =
        ok { m := 0#u64, p_biased := 0#i32 } := by
    intro q
    unfold num.imp.dec2flt.lemire.compute_float
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 0#i32 =
      ok { m := 0#u64, p_biased := 0#i32 } by rfl, hinf]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 2047#i32 =
      ok { m := 0#u64, p_biased := 2047#i32 } by rfl]
    simp only [bind_tc_ok]
    rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 (-1)#i32 =
      ok { m := 0#u64, p_biased := (-1)#i32 } by rfl]
    rfl
  unfold num.imp.dec2flt.dec2flt_with_trace at htrace
  obtain ⟨body, hbody, htrace⟩ := bind_ok_inv _ _ _ htrace
  obtain ⟨first, hfirst, htrace⟩ := bind_ok_inv _ _ _ htrace
  cases first with
  | none =>
      obtain ⟨pfe, hpfe, htrace⟩ := bind_ok_inv _ _ _ htrace
      cases htrace
  | some c =>
      obtain ⟨body1, hbody1, htrace⟩ := bind_ok_inv _ _ _ htrace
      obtain ⟨empty, hempty, htrace⟩ := bind_ok_inv _ _ _ htrace
      by_cases he : empty = true
      · simp only [he, if_true] at htrace
        obtain ⟨pfe, hpfe, htrace⟩ := bind_ok_inv _ _ _ htrace
        cases htrace
      · have hef : empty = false := Bool.eq_false_of_not_eq_true he
        simp only [hef, if_false] at htrace
        obtain ⟨parsed, hparsed, htrace⟩ := bind_ok_inv _ _ _ htrace
        cases parsed with
        | none =>
            obtain ⟨special, hspecial, htrace⟩ := bind_ok_inv _ _ _ htrace
            cases special with
            | none =>
                obtain ⟨pfe, hpfe, htrace⟩ := bind_ok_inv _ _ _ htrace
                cases htrace
            | some value => cases htrace
        | some parsedRecord =>
            obtain ⟨fast, hfast, htrace⟩ := bind_ok_inv _ _ _ htrace
            cases fast with
            | some value => cases htrace
            | none =>
                obtain ⟨firstPair, hfirstPair, htrace⟩ :=
                  bind_ok_inv _ _ _ htrace
                obtain ⟨phase1, hphase1, htrace⟩ := bind_ok_inv _ _ _ htrace
                rcases phase1 with
                  ⟨many1, many2, firstPair1, fp, secondGuard⟩
                obtain ⟨phase2, hphase2, htrace⟩ := bind_ok_inv _ _ _ htrace
                rcases phase2 with
                  ⟨post, secondExp, secondMant, secondResult, secondEqual,
                    forced⟩
                obtain ⟨phase3, hphase3, htrace⟩ := bind_ok_inv _ _ _ htrace
                rcases phase3 with ⟨selected, slowGuard, slowResult⟩
                obtain ⟨i, hi, htrace⟩ := bind_ok_inv _ _ _ htrace
                obtain ⟨i1, hi1, htrace⟩ := bind_ok_inv _ _ _ htrace
                obtain ⟨i2, hi2, htrace⟩ := bind_ok_inv _ _ _ htrace
                obtain ⟨word, hword, htrace⟩ := bind_ok_inv _ _ _ htrace
                obtain ⟨assembled, hassembled, htrace⟩ :=
                  bind_ok_inv _ _ _ htrace
                have traceFields : tr.body = body1 /\
                    tr.slow_path_guard = slowGuard /\
                    tr.selected_pair = selected := by
                  by_cases hnegative : c = 45#u8
                  · simp only [hnegative, if_true] at htrace
                    obtain ⟨result, hresult, htrace⟩ :=
                      bind_ok_inv _ _ _ htrace
                    cases htrace
                    exact ⟨rfl, rfl, rfl⟩
                  · simp only [hnegative, if_false] at htrace
                    cases htrace
                    exact ⟨rfl, rfl, rfl⟩
                rcases traceFields with ⟨htraceBody, htraceSlow, htraceSelected⟩
                have htarget : target = parsedRecord := by
                  rw [htraceBody, hparsed] at hparse
                  injection hparse with h
                  exact (Option.some.inj h).symm
                subst target
                have hslow' : slowGuard = true := htraceSlow.symm.trans hslow
                have hslowCall :
                    num.imp.dec2flt.slow.parse_long_mantissa
                        F64.Insts.Dec2flt_modelNumImpTraitsFloatU64 body1 =
                      ok selected := by
                    by_cases hneg : post.p_biased < 0#i32
                    · simp only [hneg, if_true] at hphase3
                      obtain ⟨replacement, hreplacement, hphase3⟩ :=
                        bind_ok_inv _ _ _ hphase3
                      cases hphase3
                      exact hreplacement
                    · simp only [hneg, if_false] at hphase3
                      cases hphase3
                      simp at hslow'
                have hbounds : -342 <= parsedRecord.exponent.val /\
                    parsedRecord.exponent.val <= 308 := by
                    by_contra hb
                    have hout : parsedRecord.exponent.val < -342 \/
                        308 < parsedRecord.exponent.val := by omega
                    have hpostNonnegative : 0 <= post.p_biased.val := by
                      have hfp : fp = firstPair := by
                        by_cases hm : parsedRecord.many_digits = true
                        · simp only [hm, if_true] at hphase1
                          cases hphase1
                          rfl
                        · simp only [hm, if_false] at hphase1
                          cases hphase1
                          rfl
                      subst fp
                      by_cases hm : parsedRecord.many_digits = true
                      · simp only [hm, if_true] at hphase1
                        cases hphase1
                        rcases hout with hlow | hhigh
                        · have hfirstFixed := compute_low parsedRecord.exponent
                            parsedRecord.mantissa hlow
                          rw [hfirstPair] at hfirstFixed
                          cases hfirstFixed
                          simp only [ge_iff_le, decide_true, if_true] at hphase2
                          obtain ⟨incremented, hincremented, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          obtain ⟨second, hsecond, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          have hsecondFixed := compute_low parsedRecord.exponent
                            incremented hlow
                          rw [hsecond] at hsecondFixed
                          cases hsecondFixed
                          obtain ⟨equal, hequal, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          have heq : equal = true := by
                            simpa [num.imp.dec2flt.common.BiasedFp.Insts.CoreCmpPartialEqBiasedFp.eq]
                              using hequal
                          subst equal
                          simp only [if_true] at hphase2
                          obtain ⟨chosen, hchosen, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          cases hchosen
                          cases hphase2
                          norm_num
                        · have hwpos := hpositive hm
                          have hfirstFixed := compute_high parsedRecord.exponent
                            parsedRecord.mantissa hhigh hwpos
                          rw [hfirstPair] at hfirstFixed
                          cases hfirstFixed
                          simp only [ge_iff_le, decide_true, if_true] at hphase2
                          obtain ⟨incremented, hincremented, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          have hincVal : incremented.val =
                              parsedRecord.mantissa.val + 1 := by
                            have hadd := UScalar.add_equiv parsedRecord.mantissa
                              (1#u64)
                            rw [hincremented] at hadd
                            simp at hadd
                            omega
                          have hincPos : 0 < incremented.val := by omega
                          obtain ⟨second, hsecond, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          have hsecondFixed := compute_high parsedRecord.exponent
                            incremented hhigh hincPos
                          rw [hsecond] at hsecondFixed
                          cases hsecondFixed
                          obtain ⟨equal, hequal, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          have heq : equal = true := by
                            simpa [num.imp.dec2flt.common.BiasedFp.Insts.CoreCmpPartialEqBiasedFp.eq]
                              using hequal
                          subst equal
                          simp only [if_true] at hphase2
                          obtain ⟨chosen, hchosen, hphase2⟩ :=
                            bind_ok_inv _ _ _ hphase2
                          cases hchosen
                          cases hphase2
                          norm_num
                      · simp only [hm, if_false] at hphase1
                        cases hphase1
                        simp only [Bool.false_eq_true, if_false] at hphase2
                        cases hphase2
                        rcases hout with hlow | hhigh
                        · have hfixed := compute_low parsedRecord.exponent
                            parsedRecord.mantissa hlow
                          rw [hfirstPair] at hfixed
                          cases hfixed
                          norm_num
                        · by_cases hw : parsedRecord.mantissa.val = 0
                          · have hweq : parsedRecord.mantissa = 0#u64 :=
                              UScalar.eq_of_val_eq hw
                            rw [hweq] at hfirstPair
                            have hfixed := compute_zero parsedRecord.exponent
                            rw [hfirstPair] at hfixed
                            cases hfixed
                            norm_num
                          · have hwpos : 0 < parsedRecord.mantissa.val := by omega
                            have hfixed := compute_high parsedRecord.exponent
                              parsedRecord.mantissa hhigh hwpos
                            rw [hfirstPair] at hfixed
                            cases hfixed
                            norm_num
                    have hnotneg : ¬ (post.p_biased < 0#i32) := by
                      have hnotnegVal : ¬ (post.p_biased.val < (0 : Int)) :=
                        not_lt.mpr hpostNonnegative
                      simpa only [IScalar.lt_equiv] using hnotnegVal
                    simp only [hnotneg, if_false] at hphase3
                    cases hphase3
                    simp at hslow'
                refine ⟨hbounds.1, hbounds.2, ?_⟩
                have hslowCallCopy := hslowCall
                unfold num.imp.dec2flt.slow.parse_long_mantissa at hslowCallCopy
                rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 0#i32 =
                  ok { m := 0#u64, p_biased := 0#i32 } by rfl, hinf]
                  at hslowCallCopy
                simp only [bind_tc_ok] at hslowCallCopy
                rw [show num.imp.dec2flt.common.BiasedFp.zero_pow2 2047#i32 =
                  ok { m := 0#u64, p_biased := 2047#i32 } by rfl]
                  at hslowCallCopy
                simp only [bind_tc_ok] at hslowCallCopy
                obtain ⟨d, hd, hrest⟩ := bind_ok_inv _ _ _ hslowCallCopy
                rw [htraceBody, htraceSelected]
                exact ⟨d, hd, hslowCall⟩


end dec2flt_model
