///|
priv struct ArrayShape {
  minimum : Int64
  maximum : Int64?
  prefix : Array[CompiledSchema]
  items : CompiledSchema
  inhabited : Bool
}

///|
fn compile_array(
  fields : Map[String, Json],
  depth : Int32,
  integer_work : Ref[Int32],
) -> ArrayShape raise SchemaIssue {
  let mut minimum = 0L
  let mut maximum = None
  let prefix : Array[CompiledSchema] = []
  let mut items = all_values
  for key, value in fields {
    match key {
      "type" => ()
      "minItems" => minimum = nonnegative_length(value, key)
      "maxItems" => maximum = Some(nonnegative_length(value, key))
      "prefixItems" =>
        for schema in nonempty_array(value, key) {
          prefix.push(compile_shape(schema, depth + 1, integer_work))
        }
      "items" => items = compile_shape(value, depth + 1, integer_work)
      _ => check_annotation(key, value)
    }
  }

  // An impossible element rule forbids every length that reaches that position.
  for index in 0.. Bool {
  self.minimum <= length && length <= self.maximum.unwrap_or(length)
}

///|
fn ArrayShape::item(self : ArrayShape, index : Int32) -> CompiledSchema {
  if index < self.prefix.length() {
    self.prefix[index]
  } else {
    self.items
  }
}

///|
fn array_witness(
  source : ArrayShape,
  target : ArrayShape,
  work : Ref[Int32],
) -> Witness? raise SchemaIssue {
  if !source.inhabited {
    return None
  }
  if !target.allows_length(source.minimum) {
    return Some(ArrayWitness(source, source.minimum, None))
  }

  // Compare every distinct position rule once. The last position represents
  // the entire tail, because no later index uses a different rule.
  let tail_index = source.prefix.length().max(target.prefix.length())
  let mut oversized = None
  for index in 0..<=tail_index {
    let length = source.minimum.max(index.to_int64() + 1L)
    if !source.allows_length(length) || !target.allows_length(length) {
      break
    }
    spend_comparison_work(work, 1)
    if find_witness(source.item(index), target.item(index), work) is Some(value) {
      let candidate = ArrayWitness(source, length, Some((index, value)))
      if witness_size_floor(candidate) <= output_size_limit.to_int64() {
        return Some(candidate)
      }
      // Keep the proof of incompatibility even if no smaller witness follows.
      oversized = Some(candidate)
    }
  }

  if target.maximum is Some(limit) && source.allows_length(limit + 1L) {
    return Some(ArrayWitness(source, limit + 1L, None))
  }
  oversized
}

///|
fn render_array(
  shape : ArrayShape,
  length : Int64,
  replacement : (Int32, Witness)?,
  budget : Ref[Int32],
) -> Json raise SchemaIssue {
  if length > budget.val.to_int64() {
    raise Unsupported("counterexample exceeds the output size limit")
  }
  let items : Array[Json] = []
  for index in 0.. Some(value)
      _ => example_witness(shape.item(index))
    }
    guard item is Some(value) else {
      raise Unsupported(
        "cannot render a witness for an empty array item schema",
      )
    }
    items.push(render_witness(value, budget))
  }
  Json::array(items)
}