///|
priv struct ObjectShape {
  required : Map[String, Unit]
  properties : Map[String, CompiledSchema]
  additional : CompiledSchema
  minimum : Int64
  maximum : Int64?
  name_capacity : Int64?
  inhabited : Bool
}

///|
priv enum ObjectMember {
  Include(String, Witness)
  Omit(String)
}

///|
fn compile_object(
  fields : Map[String, Json],
  depth : Int32,
  integer_work : Ref[Int32],
) -> ObjectShape raise SchemaIssue {
  let required : Map[String, Unit] = Map([])
  let properties : Map[String, CompiledSchema] = Map([])
  let mut additional = all_values
  let mut minimum = 0L
  let mut maximum = None
  for key, value in fields {
    match (key, value) {
      ("type", _) => ()
      ("minProperties", _) => minimum = nonnegative_length(value, key)
      ("maxProperties", _) => maximum = Some(nonnegative_length(value, key))
      ("required", Array(items)) =>
        for item in items {
          match item {
            String(name) if !required.contains(name) => required[name] = ()
            _ =>
              raise Unsupported("required must contain unique property names")
          }
        }
      ("required", _) => raise Unsupported("required must be an array")
      ("properties", Object(items)) =>
        for name, schema in items {
          properties[name] = compile_shape(schema, depth + 1, integer_work) catch {
            Unsupported(reason) =>
              raise Unsupported("property \{name}: \{reason}")
          }
        }
      ("properties", _) => raise Unsupported("properties must be an object")
      ("additionalProperties", schema) =>
        additional = compile_shape(schema, depth + 1, integer_work) catch {
          Unsupported(reason) =>
            raise Unsupported("additionalProperties: \{reason}")
        }
      _ => check_annotation(key, value)
    }
  }
  minimum = minimum.max(required.length().to_int64())
  let name_capacity = if has_value(additional) {
    None
  } else {
    let mut count = 0L
    for _, schema in properties {
      if has_value(schema) {
        count += 1L
      }
    }
    maximum = Some(count.min(maximum.unwrap_or(count)))
    Some(count)
  }
  let mut inhabited = minimum <= maximum.unwrap_or(minimum)
  for name, _ in required {
    if !has_value(properties.get(name).unwrap_or(additional)) {
      inhabited = false
      break
    }
  }
  {
    required,
    properties,
    additional,
    minimum,
    maximum,
    name_capacity,
    inhabited,
  }
}

///|
fn ObjectShape::property(self : ObjectShape, name : String) -> CompiledSchema {
  self.properties.get(name).unwrap_or(self.additional)
}

///|
fn ObjectShape::allows_size(self : ObjectShape, size : Int64) -> Bool {
  self.minimum <= size && size <= self.maximum.unwrap_or(size)
}

///|
fn ObjectShape::can_omit(self : ObjectShape, name : String) -> Bool {
  if self.required.contains(name) {
    return false
  }
  match self.name_capacity {
    Some(count) if has_value(self.property(name)) => self.minimum < count
    _ => true
  }
}

///|
fn fresh_object_name(index : Int32) -> String {
  if index == 1 {
    "extra"
  } else {
    "extra\{index}"
  }
}

///|
fn render_object_property(
  schema : CompiledSchema,
  name : String,
  payload : Map[String, Json],
  budget : Ref[Int32],
) -> Unit raise SchemaIssue {
  spend_output_budget(budget, name.length())
  match example_witness(schema) {
    Some(value) => payload[name] = render_witness(value, budget)
    None =>
      raise Unsupported("cannot render a witness for an empty object schema")
  }
}

///|
fn render_object(
  shape : ObjectShape,
  length : Int64,
  selection : ObjectMember?,
  budget : Ref[Int32],
) -> Json raise SchemaIssue {
  if length > budget.val.to_int64() {
    raise Unsupported("counterexample exceeds the output size limit")
  }
  let count = length.to_int()
  let payload : Map[String, Json] = Map([])
  let reserved = match selection {
    Some(Include(name, _)) | Some(Omit(name)) => Some(name)
    None => None
  }
  for name, _ in shape.required {
    if reserved == Some(name) {
      continue
    }
    render_object_property(shape.property(name), name, payload, budget)
  }
  if selection is Some(Include(name, value)) {
    spend_output_budget(budget, name.length())
    payload[name] = render_witness(value, budget)
  }
  if payload.length() < count {
    for name, schema in shape.properties {
      if reserved == Some(name) || payload.contains(name) {
        continue
      }
      if example_witness(schema) is Some(value) &&
        name.length().to_int64() + witness_size_floor(value) <=
        budget.val.to_int64() {
        spend_output_budget(budget, name.length())
        payload[name] = render_witness(value, budget)
      }
      if payload.length() == count {
        break
      }
    }
  }
  if payload.length() < count && shape.name_capacity is Some(_) {
    raise Unsupported("counterexample exceeds the output size limit")
  }
  let mut index = 1
  while payload.length() < count {
    let name = fresh_object_name(index)
    index += 1
    if reserved != Some(name) &&
      !shape.properties.contains(name) &&
      !payload.contains(name) {
      render_object_property(shape.additional, name, payload, budget)
    }
  }
  Json::object(payload)
}

///|
fn object_witness(
  source : ObjectShape,
  target : ObjectShape,
  work : Ref[Int32],
) -> Witness? raise SchemaIssue {
  if !source.inhabited {
    return None
  }
  if !target.inhabited || !target.allows_size(source.minimum) {
    return Some(ObjectWitness(source, source.minimum, None))
  }

  // A minimum count can force otherwise optional names when the name pool is finite.
  spend_comparison_work(work, 1)
  spend_comparison_work(work, target.required.length())
  for name, _ in target.required {
    spend_comparison_work(work, name.length() / 16)
    if source.can_omit(name) {
      return Some(ObjectWitness(source, source.minimum, Some(Omit(name))))
    }
  }

  let optional_size = source.minimum.max(
    source.required.length().to_int64() + 1L,
  )
  let allows_optional = source.allows_size(optional_size)
  spend_comparison_work(work, source.properties.length())
  spend_comparison_work(work, target.properties.length())
  let names : Map[String, Unit] = Map([])
  for name, _ in source.properties {
    spend_comparison_work(work, name.length() / 16)
    names[name] = ()
  }
  for name, _ in target.properties {
    spend_comparison_work(work, name.length() / 16)
    names[name] = ()
  }
  let mut oversized = None
  for name, _ in names {
    let length = if source.required.contains(name) {
      source.minimum
    } else if allows_optional {
      optional_size
    } else {
      continue
    }
    if find_witness(source.property(name), target.property(name), work)
      is Some(value) {
      let candidate = ObjectWitness(source, length, Some(Include(name, value)))
      if witness_size_floor(candidate) <= output_size_limit.to_int64() {
        return Some(candidate)
      }
      oversized = Some(candidate)
    }
  }

  if source.name_capacity is None {
    let mut required_name = None
    spend_comparison_work(work, source.required.length())
    // Outside the declared names there is just one pair of rules to compare.
    for name, _ in source.required {
      spend_comparison_work(work, name.length() / 16)
      if !names.contains(name) {
        required_name = Some(name)
        break
      }
    }
    if (required_name is Some(_) || allows_optional) &&
      find_witness(source.additional, target.additional, work) is Some(value) {
      let (name, length) = match required_name {
        Some(name) => (name, source.minimum)
        None => {
          let mut index = 1
          let mut name = fresh_object_name(index)
          while names.contains(name) {
            spend_comparison_work(work, 1)
            index += 1
            name = fresh_object_name(index)
          }
          (name, optional_size)
        }
      }
      let candidate = ObjectWitness(source, length, Some(Include(name, value)))
      if witness_size_floor(candidate) <= output_size_limit.to_int64() {
        return Some(candidate)
      }
      oversized = Some(candidate)
    }
  }
  if target.maximum is Some(limit) && source.allows_size(limit + 1L) {
    return Some(ObjectWitness(source, limit + 1L, None))
  }
  oversized
}