///|
/// Sentinel values for `VocabStepCache` transitions.
let cache_unseen : Int32 = -2

///|
let cache_dead : Int32 = -1

///|
let cache_overflow : Int32 = -3

///|
let max_cached_states : Int32 = 1024

///|
/// Interning key for `Array[Array[StackFrame]]` with precomputed 32-bit hash.
priv struct StateKey {
  stacks : Array[Array[StackFrame]]
  hash : Int32
}

///|
impl Eq for StateKey with fn equal(self, other) {
  self.hash == other.hash && stack_lists_equal(self.stacks, other.stacks)
}

///|
impl Hash for StateKey with fn hash_combine(self, hasher) {
  hasher.combine_int(self.hash)
}

///|
impl Hash for StateKey with fn hash(self : StateKey) -> Int32 {
  self.hash
}

///|
/// Cached outgoing transitions for one interned `stacks` automaton state.
priv struct CachedState {
  stacks : Array[Array[StackFrame]]
  ascii_next : FixedArray[Int32]
  mut non_ascii_next : Map[Int32, Int32]?
  mut mask_next : Map[UInt32, Int32]?
  mut single_next : Int32
}

///|
/// Per-`mask_vocab` lazy transition & prefix-state cache.
priv struct VocabStepCache {
  grammar : CompiledGrammar
  states : Array[CachedState]
  state_ids : Map[StateKey, Int32]
  scratch : ExpandScratch
}

///|
fn CachedState::new(stacks : Array[Array[StackFrame]]) -> CachedState {
  {
    stacks,
    ascii_next: FixedArray::make(128, cache_unseen),
    non_ascii_next: None,
    mask_next: None,
    single_next: cache_unseen,
  }
}

///|
fn VocabStepCache::new(
  grammar : CompiledGrammar,
  initial_stacks : Array[Array[StackFrame]],
) -> VocabStepCache {
  let states : Array[CachedState] = [CachedState::new(initial_stacks)]
  let state_ids : Map[StateKey, Int32] = Map([])
  let init_key : StateKey = {
    stacks: initial_stacks,
    hash: hash_stack_list(initial_stacks),
  }
  state_ids[init_key] = 0
  { grammar, states, state_ids, scratch: ExpandScratch::new(), }
}

///|
fn VocabStepCache::intern_state(
  self : VocabStepCache,
  stacks : Array[Array[StackFrame]],
) -> Int32 {
  let key : StateKey = { stacks, hash: hash_stack_list(stacks), }
  match self.state_ids.get(key) {
    Some(id) => id
    None => {
      let id = self.states.length()
      if id >= max_cached_states {
        return cache_overflow
      }
      self.states.push(CachedState::new(stacks))
      self.state_ids[key] = id
      id
    }
  }
}

///|
fn VocabStepCache::step(
  self : VocabStepCache,
  state_id : Int32,
  cp : Int32,
) -> Int32 {
  let st = self.states[state_id]
  let is_ascii = cp >= 0 && cp < 128
  if is_ascii {
    let cached = st.ascii_next[cp]
    if cached != cache_unseen {
      return cached
    }
  } else {
    match st.non_ascii_next {
      Some(map) =>
        match map.get(cp) {
          Some(cached) => return cached
          None => ()
        }
      None => ()
    }
  }
  let m = st.stacks.length()
  let next_id = if m == 0 {
    cache_dead
  } else if m == 1 {
    if !stack_top_matches(self.grammar, st.stacks[0], cp) {
      cache_dead
    } else if st.single_next != cache_unseen {
      st.single_next
    } else {
      let next_stacks = step_stacks_with(
        self.grammar,
        st.stacks,
        cp,
        self.scratch,
      )
      let res = if next_stacks.length() == 0 {
        cache_dead
      } else {
        self.intern_state(next_stacks)
      }
      if res != cache_overflow {
        st.single_next = res
      }
      res
    }
  } else if m <= 32 {
    let mut match_mask : UInt32 = 0U
    for i = 0; i < m; i = i + 1 {
      if stack_top_matches(self.grammar, st.stacks[i], cp) {
        match_mask = match_mask | (1U << i)
      }
    }
    if match_mask == 0U {
      cache_dead
    } else {
      let cached_mask = match st.mask_next {
        Some(map) => map.get(match_mask)
        None => None
      }
      match cached_mask {
        Some(id) => id
        None => {
          let next_stacks = step_stacks_with(
            self.grammar,
            st.stacks,
            cp,
            self.scratch,
          )
          let res = if next_stacks.length() == 0 {
            cache_dead
          } else {
            self.intern_state(next_stacks)
          }
          if res != cache_overflow {
            match st.mask_next {
              Some(map) => map[match_mask] = res
              None => {
                let map : Map[UInt32, Int32] = Map([])
                map[match_mask] = res
                st.mask_next = Some(map)
              }
            }
          }
          res
        }
      }
    }
  } else {
    let next_stacks = step_stacks_with(
      self.grammar,
      st.stacks,
      cp,
      self.scratch,
    )
    if next_stacks.length() == 0 {
      cache_dead
    } else {
      self.intern_state(next_stacks)
    }
  }
  if next_id == cache_overflow {
    return cache_overflow
  }
  if is_ascii {
    st.ascii_next[cp] = next_id
  } else if m > 1 {
    match st.non_ascii_next {
      Some(map) => if map.length() < 256 { map[cp] = next_id }
      None => {
        let map : Map[Int32, Int32] = Map([])
        map[cp] = next_id
        st.non_ascii_next = Some(map)
      }
    }
  }
  next_id
}

///|
fn step_stacks_direct(
  grammar : CompiledGrammar,
  start : Array[Array[StackFrame]],
  tok : String,
  from_cu : Int32,
  scratch : ExpandScratch,
) -> Bool {
  match step_str_stacks(grammar, start, tok, from_cu~, scratch~) {
    Some(_) => true
    None => false
  }
}

///|
fn VocabStepCache::step_token(
  self : VocabStepCache,
  tok : String,
  cp0 : Int32,
  next_idx : Int32,
) -> Bool {
  let next0 = self.step(0, cp0)
  if next0 == cache_dead {
    return false
  }
  if next0 == cache_overflow {
    return step_stacks_direct(
      self.grammar,
      self.states[0].stacks,
      tok,
      0,
      self.scratch,
    )
  }
  let mut state_id = next0
  let mut idx = next_idx
  let len = tok.length()
  while idx < len {
    let (cp, adv_idx) = decode_cp_at(tok, idx, len)
    let next_id = self.step(state_id, cp)
    if next_id == cache_dead {
      return false
    }
    if next_id == cache_overflow {
      return step_stacks_direct(
        self.grammar,
        self.states[state_id].stacks,
        tok,
        idx,
        self.scratch,
      )
    }
    state_id = next_id
    idx = adv_idx
  }
  true
}

///|
/// Deep-clone the decoding state for Beam Search, backtracking, or speculative decoding.
pub fn GrammarState::clone(self : GrammarState) -> GrammarState {
  {
    grammar: self.grammar,
    stacks: clone_stacks(self.stacks),
    cached_allowed: self.cached_allowed,
    cached_ascii_map: self.cached_ascii_map,
    scratch: ExpandScratch::new(),
  }
}

///|
/// Compute the normalized union of all Unicode code point ranges legally accepted next.
pub fn GrammarState::allowed_ranges(self : GrammarState) -> Array[CharRange] {
  self.ensure_allowed_ranges().copy()
}

///|
/// Non-mutating check whether a single code point can legally be accepted next.
pub fn GrammarState::can_accept_codepoint(
  self : GrammarState,
  cp : Int32,
) -> Bool {
  if cp < 0 || cp > 0x10FFFF {
    return false
  }
  if cp < 128 {
    return self.ensure_ascii_bitmap()[cp]
  }
  fast_ranges_contains(self.ensure_allowed_ranges(), cp)
}

///|
/// Non-mutating check whether a multi-character token string is legally accepted next.
pub fn GrammarState::can_accept_str(self : GrammarState, s : String) -> Bool {
  let len = s.length()
  if len == 0 {
    return true
  }
  let (cp0, _) = decode_cp_at(s, 0, len)
  if !self.can_accept_codepoint(cp0) {
    return false
  }
  match step_str_stacks(self.grammar, self.stacks, s, scratch=self.scratch) {
    Some(_) => true
    None => false
  }
}

///|
fn is_vocab_token_allowed(
  state : GrammarState,
  tok : String,
  first_allowed : Array[CharRange],
  ascii_ok : FixedArray[Bool],
  cache_ref : Ref[VocabStepCache?],
) -> Bool {
  let len = tok.length()
  if len == 0 {
    return false
  }
  let cu0 = tok[0]
  let u0 = cu0.to_int()
  if u0 < 128 {
    if !ascii_ok[u0] {
      return false
    }
    if len == 1 {
      return true
    }
    let cache = match cache_ref.val {
      Some(c) => c
      None => {
        let c = VocabStepCache::new(state.grammar, state.stacks)
        cache_ref.val = Some(c)
        c
      }
    }
    return cache.step_token(tok, u0, 1)
  }
  let (cp0, next_idx) = decode_cp_at(tok, 0, len)
  if !fast_ranges_contains(first_allowed, cp0) {
    return false
  }
  if next_idx >= len {
    return true
  }
  let cache = match cache_ref.val {
    Some(c) => c
    None => {
      let c = VocabStepCache::new(state.grammar, state.stacks)
      cache_ref.val = Some(c)
      c
    }
  }
  cache.step_token(tok, cp0, next_idx)
}

///|
/// Compute a boolean allow-mask over an LLM token vocabulary.
/// If `eos_token_id` is provided, that token is allowed iff `self.is_complete()`.
pub fn GrammarState::mask_vocab(
  self : GrammarState,
  vocab : Array[String],
  eos_token_id~ : Int32 = -1,
) -> Array[Bool] {
  let first_allowed = self.ensure_allowed_ranges()
  let ascii_ok = self.ensure_ascii_bitmap()
  let complete = self.is_complete()
  let n = vocab.length()
  let mask = Array::make(n, false)
  let cache_ref : Ref[VocabStepCache?] = { val: None, }
  for id = 0; id < n; id = id + 1 {
    if id == eos_token_id {
      mask[id] = complete
    } else if is_vocab_token_allowed(
        self,
        vocab[id],
        first_allowed,
        ascii_ok,
        cache_ref,
      ) {
      mask[id] = true
    }
  }
  mask
}

///|
/// Return the list of allowed token IDs for an LLM vocabulary at the current state.
pub fn GrammarState::allowed_token_ids(
  self : GrammarState,
  vocab : Array[String],
  eos_token_id~ : Int32 = -1,
) -> Array[Int32] {
  let first_allowed = self.ensure_allowed_ranges()
  let ascii_ok = self.ensure_ascii_bitmap()
  let complete = self.is_complete()
  let n = vocab.length()
  let ids : Array[Int32] = []
  let cache_ref : Ref[VocabStepCache?] = { val: None, }
  for id = 0; id < n; id = id + 1 {
    if id == eos_token_id {
      if complete {
        ids.push(id)
      }
    } else if is_vocab_token_allowed(
        self,
        vocab[id],
        first_allowed,
        ascii_ok,
        cache_ref,
      ) {
      ids.push(id)
    }
  }
  ids
}