///|
priv struct EqualityArrayCursor {
  left : Array[Json]
  right : Array[Json]
  mut index : Int32
}

///|
priv enum EqualityFrame {
  Arrays(EqualityArrayCursor)
  Objects(Iter[(String, Json)], Map[String, Json])
}

///|
// Keep one cursor per open container. Comparing siblings reuses that cursor;
// shared references still consume the same per-occurrence work budget.
fn json_equal(
  left : Json,
  right : Json,
  state : EvalState,
  // A caller may reuse scratch within one operation; defaults are fresh per call.
  stack~ : Array[EqualityFrame] = [],
) -> Bool raise JmesPathError {
  stack.clear()
  compare~: for a = left, b = right {
    state.tick()
    match (a, b) {
      (Null, Null) | (True, True) | (False, False) => ()
      (Number(x, ..), Number(y, ..)) => if x != y { return false }
      (String(x), String(y)) => {
        state.charge(Int32::max(x.length(), y.length()))
        if x != y {
          return false
        }
      }
      (Array(x), Array(y)) => {
        if x.length() != y.length() {
          return false
        }
        // A single child has no remaining siblings to resume.
        if x.length() == 1 {
          continue compare~ x[0], y[0]
        }
        stack.push(Arrays({ left: x, right: y, index: 0, }))
      }
      (Object(x), Object(y)) => {
        if x.length() != y.length() {
          return false
        }
        if x.length() == 1 && x.iter().next() is Some((key, value)) {
          state.charge(key.length())
          guard y.get(key) is Some(other_value) else { return false }
          continue compare~ value, other_value
        }
        stack.push(Objects(x.iter(), y))
      }
      _ => return false
    }
    while !stack.is_empty() {
      match stack[stack.length() - 1] {
        Arrays(cursor) =>
          if cursor.index < cursor.left.length() {
            let index = cursor.index
            cursor.index += 1
            continue compare~ cursor.left[index], cursor.right[index]
          }
        Objects(entries, other) =>
          if entries.next() is Some((key, value)) {
            state.charge(key.length())
            guard other.get(key) is Some(other_value) else { return false }
            continue compare~ value, other_value
          }
      }
      stack.pop() |> ignore
    }
    break compare~
  }
  true
}