import Tablet.NumberHelperEightDigitWord
import Tablet.NumberHelperReadEightBytes
import Tablet.num_imp_dec2flt_decimal_seq_parse_decimal_seq

open Aeneas Aeneas.Std Result ControlFlow Error
set_option autoImplicit false

namespace dec2flt_model

-- [TABLET NODE: DecimalSeqBulkMixedStop]
theorem DecimalSeqBulkMixedStop (s : Slice Std.U8) (i : Std.Usize)
    (a : Array Std.U8 768#usize) (digits : List Nat)
    (marker : Nat) (tail : List Nat)
    (hs : s.val.map (fun b => b.val) =
      digits.map (fun z => 48 + z) ++ marker :: tail)
    (hdigits : forall z, z ∈ digits -> z < 10)
    (hshort : digits.length < 8) (hlen : 8 <= s.val.length)
    (hmarker : marker = 69 \/ marker = 101)
    (hi : i.val + 8 < 768) :
    num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop3.body s i a =
      ok (done (s, i, a)) := by
-- BODY
  obtain ⟨i', hi', hi'val⟩ := Aeneas.Std.WP.spec_imp_exists
    (UScalar.add_spec (x := i) (y := 8#usize) (by
      have hbits := Dec2Flt.configured_x86_64_numBits
      simp [UScalar.max, hbits]
      omega))
  change i'.val = i.val + 8 at hi'val
  obtain ⟨w, hw, hwbytes⟩ := NumberHelperReadEightBytes s hlen
  have hindex : digits.length < s.val.length := by omega
  have hmarkerByte : (s.val[digits.length]'hindex).val = marker := by
    have hm := congrArg List.head?
      (congrArg (List.drop digits.length) hs)
    simp [List.map_drop] at hm
    rw [List.getElem?_eq_getElem hindex] at hm
    rcases hm with ⟨b, hb, hbval⟩
    have hb' := Option.some.inj hb
    rw [hb']
    exact hbval
  have hfalse : num.imp.dec2flt.common.is_8digits w = ok false := by
    cases hb : num.imp.dec2flt.common.is_8digits w with
    | fail err =>
        unfold num.imp.dec2flt.common.is_8digits at hb
        simp [Aeneas.Std.lift] at hb
    | div =>
        unfold num.imp.dec2flt.common.is_8digits at hb
        simp [Aeneas.Std.lift] at hb
    | ok b =>
        cases b with
        | false => rfl
        | true =>
            exfalso
            have hlanes := NumberHelperEightDigitWord w hb digits.length hshort
            rw [hwbytes digits.length hshort, hmarkerByte] at hlanes
            rcases hmarker with rfl | rfl <;> omega
  unfold num.imp.dec2flt.decimal_seq.parse_decimal_seq_loop3.body
  simp [hlen, hi', hi'val,
    num.imp.dec2flt.decimal_seq.DecimalSeq.MAX_DIGITS.eq_def,
    hi, hw, hfalse]

end dec2flt_model
