// Component schema lowering, field-type lowering, inline promotion,
// string enums, and record field construction.

///|
/// Idempotent wrapper preventing double-wrapped `Optional(Optional(T))`.
fn make_optional(ft : FieldType) -> FieldType {
  match ft {
    Optional(_) => ft
    other => FieldType::Optional(other)
  }
}

///|
/// Build the definition for one component schema.
fn IrBuilder::build_component_def(
  self : IrBuilder,
  component : String,
) -> TypeDef? raise @spec.SpecError {
  let pointer = "/components/schemas/\{component}"
  let mb_name = self.moonbit_component_name(component)
  // Handle bare component-level `$ref` aliases cleanly (and guard cycles!).
  let schema = match self.component_schemas.get(component) {
    Some(@spec.Item(s)) => s
    Some(@spec.Ref(target)) =>
      match self.resolve_schema_ref_component(target.ref_, pointer) {
        Some(target_comp) => {
          let target_mb = self.moonbit_component_name(target_comp)
          if target_comp == component ||
            target_mb == mb_name ||
            self.alias_in_progress.contains(target_mb) {
            self.diags.error(
              "E-ref-cycle",
              pointer,
              "cyclic bare type alias \"\{component}\" -> \"\{target_comp}\"; falling back to JSON",
            )
            return Some(
              Alias({
                name: mb_name,
                target: JsonValue,
                docs: [],
                example: None,
                deprecated: false,
                source: component,
              }),
            )
          }
          self.alias_in_progress.push(mb_name)
          let target_name = self.ensure_component(target_comp)
          self.pop_alias_guard(mb_name)
          let sibling_nullable = target.siblings
            .iter()
            .any(fn(pair) { pair.0 == "nullable" && pair.1 is @spec.Bool(true) })
          return Some(
            Alias({
              name: mb_name,
              target: if sibling_nullable {
                make_optional(Named(target_name))
              } else {
                Named(target_name)
              },
              docs: [],
              example: None,
              deprecated: false,
              source: component,
            }),
          )
        }
        None => return None
      }
    None => return None
  }
  self.build_schema_def(component, schema, mb_name, pointer)
}

///|
/// Build a `TypeDef` for any named schema (either a component schema or a
/// promoted internal JSON-pointer target such as `#/$defs/...`).
fn IrBuilder::build_schema_def(
  self : IrBuilder,
  component : String,
  schema : @spec.Schema,
  mb_name : String,
  pointer : String,
) -> TypeDef? raise @spec.SpecError {
  let docs = docs_from_option(schema.description)
  match
    ext_str(schema.extras, "x-moonbit-deprecated-message", pointer, self.diags) {
    Some(msg) => docs.push("Deprecated: \{msg}")
    None => ()
  }
  if schema.not is Some(_) {
    docs.push("Constraint: must not match negated schema (`not`).")
  }
  // 1. Encoding A discriminator unions (cached from Pass 2)
  if self.discriminated_unions.contains(component) {
    return self.build_discriminated_union(component, schema, mb_name, docs)
  }
  // 2. oneOf / anyOf (nullable [X, null], Encoding B tagged union, or untagged union)
  if schema.one_of is Some(_) {
    return self.build_one_of_def(component, schema, mb_name, docs, pointer)
  }
  if schema.any_of is Some(_) {
    return self.build_any_of_def(component, schema, mb_name, docs, pointer)
  }
  // 3. allOf (single-$ref alias or merged record)
  if schema.all_of is Some(_) {
    return self.build_all_of(component, schema, mb_name, docs, pointer)
  }
  // 3b. OpenAPI 3.1 multi-type arrays (e.g. `type: ["string", "integer"]`)
  let multi_types : Array[String] = []
  for t in schema.types {
    if t != "null" {
      multi_types.push(t)
    }
  }
  if multi_types.length() >= 2 {
    return self.build_multi_type_def(
      component, schema, multi_types, mb_name, docs, pointer,
    )
  }
  // 4. Plain / inferred schema shapes
  let effective_type : String? = match schema.type_ {
    Some(t) => Some(t)
    None =>
      if !schema.properties.is_empty() ||
        schema.additional_properties is Some(_) {
        Some("object")
      } else if schema.items is Some(_) {
        Some("array")
      } else {
        None
      }
  }
  fn wrap_nullable(target : FieldType) -> FieldType {
    if schema.nullable {
      make_optional(target)
    } else {
      target
    }
  }

  fn wrap_nullable_string_enum(values : Array[@spec.Node]) -> TypeDef {
    if schema.nullable {
      let inner_name = self.type_namer.unique_type(mb_name + "Value")
      let inner_def = self.string_enum_def(
        component, inner_name, values, schema, pointer,
      )
      match inner_def {
        Alias(_) =>
          Alias({
            name: mb_name,
            target: FieldType::Optional(JsonValue),
            docs,
            example: schema.example,
            deprecated: schema.deprecated,
            source: component,
          })
        _ => {
          self.add_def(inner_def)
          Alias({
            name: mb_name,
            target: FieldType::Optional(Named(inner_name)),
            docs,
            example: schema.example,
            deprecated: schema.deprecated,
            source: component,
          })
        }
      }
    } else {
      self.string_enum_def(component, mb_name, values, schema, pointer)
    }
  }

  match effective_type {
    Some("object") =>
      if !schema.properties.is_empty() {
        match schema.additional_properties {
          Some(@spec.AdditionalProperties::Schema(_)) =>
            self.diags.unsupported(
              "W-additional-properties", pointer, "object has both properties and typed additionalProperties; additionalProperties ignored",
            )
          _ => ()
        }
        match
          self.fields_of_properties(schema, pointer~, name_context=mb_name) {
          Some(fields) =>
            if schema.nullable {
              let inner_name = self.type_namer.unique_type(mb_name + "Value")
              self.add_def(
                Record({
                  name: inner_name,
                  fields,
                  docs,
                  example: None,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
              Some(
                Alias({
                  name: mb_name,
                  target: FieldType::Optional(Named(inner_name)),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            } else {
              Some(
                Record({
                  name: mb_name,
                  fields,
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
          None => None
        }
      } else {
        match schema.additional_properties {
          Some(@spec.AdditionalProperties::Schema(value_schema)) =>
            match
              self.field_type_of_ref(
                value_schema,
                pointer=@spec.pointer_join(pointer, "additionalProperties"),
                name_context=mb_name + ".Value",
              ) {
              Some(val_type) =>
                Some(
                  Alias({
                    name: mb_name,
                    target: wrap_nullable(MapTo(val_type)),
                    docs,
                    example: schema.example,
                    deprecated: schema.deprecated,
                    source: component,
                  }),
                )
              None => None
            }
          Some(@spec.AdditionalProperties::Allowed(_)) | None =>
            Some(
              Alias({
                name: mb_name,
                target: wrap_nullable(JsonValue),
                docs,
                example: schema.example,
                deprecated: schema.deprecated,
                source: component,
              }),
            )
        }
      }
    Some("array") =>
      match schema.items {
        Some(items_ref) =>
          match
            self.field_type_of_ref(
              items_ref,
              pointer=@spec.pointer_join(pointer, "items"),
              name_context=mb_name + ".Item",
            ) {
            Some(item_type) =>
              Some(
                Alias({
                  name: mb_name,
                  target: wrap_nullable(List(item_type)),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            None => None
          }
        None => {
          self.diags.warning(
            "W-missing-items", pointer, "array schema omits items; defaulting to Array[Json]",
          )
          Some(
            Alias({
              name: mb_name,
              target: wrap_nullable(List(JsonValue)),
              docs,
              example: schema.example,
              deprecated: schema.deprecated,
              source: component,
            }),
          )
        }
      }
    Some("string") =>
      match schema.enum_ {
        Some(values) => Some(wrap_nullable_string_enum(values))
        None =>
          Some(
            Alias({
              name: mb_name,
              target: wrap_nullable(Prim(Str(schema.format.unwrap_or("")))),
              docs,
              example: schema.example,
              deprecated: schema.deprecated,
              source: component,
            }),
          )
      }
    Some("integer") =>
      Some(
        Alias({
          name: mb_name,
          target: wrap_nullable(Prim(Int(infer_int_format(schema)))),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    Some("number") =>
      Some(
        Alias({
          name: mb_name,
          target: wrap_nullable(Prim(Num(schema.format.unwrap_or("")))),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    Some("boolean") =>
      Some(
        Alias({
          name: mb_name,
          target: wrap_nullable(Prim(Bool)),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    Some("char") =>
      Some(
        Alias({
          name: mb_name,
          target: wrap_nullable(Prim(Str("char"))),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    Some("null") =>
      Some(
        Alias({
          name: mb_name,
          target: FieldType::Optional(JsonValue),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    Some(other) => {
      self.diags.unsupported(
        "W-schema-type",
        pointer,
        "schema type \"\{other}\" is not modeled; kept as JSON",
      )
      Some(
        Alias({
          name: mb_name,
          target: wrap_nullable(JsonValue),
          docs,
          example: schema.example,
          deprecated: schema.deprecated,
          source: component,
        }),
      )
    }
    None =>
      match schema.enum_ {
        Some(values) =>
          match classify_untyped_enum(values) {
            AllStrings(has_null) =>
              if has_null && !schema.nullable {
                let inner_name = self.type_namer.unique_type(mb_name + "Value")
                let inner_def = self.string_enum_def(
                  component,
                  inner_name,
                  values,
                  schema,
                  pointer,
                  allow_null=true,
                )
                self.add_def(inner_def)
                Some(
                  Alias({
                    name: mb_name,
                    target: FieldType::Optional(Named(inner_name)),
                    docs,
                    example: schema.example,
                    deprecated: schema.deprecated,
                    source: component,
                  }),
                )
              } else {
                Some(wrap_nullable_string_enum(values))
              }
            AllInts(fmt, has_null) => {
              let target = if schema.nullable || has_null {
                FieldType::Optional(Prim(Int(fmt)))
              } else {
                Prim(Int(fmt))
              }
              Some(
                Alias({
                  name: mb_name,
                  target,
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
            AllNums(has_null) => {
              let target = if schema.nullable || has_null {
                FieldType::Optional(Prim(Num("")))
              } else {
                Prim(Num(""))
              }
              Some(
                Alias({
                  name: mb_name,
                  target,
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
            AllBools(has_null) => {
              let target = if schema.nullable || has_null {
                FieldType::Optional(Prim(Bool))
              } else {
                Prim(Bool)
              }
              Some(
                Alias({
                  name: mb_name,
                  target,
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
            Mixed(has_null) => {
              self.diags.unsupported(
                "W-enum-mixed", pointer, "enum contains mixed or non-scalar values; kept as JSON",
              )
              let target = if schema.nullable || has_null {
                FieldType::Optional(JsonValue)
              } else {
                JsonValue
              }
              Some(
                Alias({
                  name: mb_name,
                  target,
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
          }
        None =>
          match schema.const_ {
            Some(@spec.Str(_) as s) => Some(wrap_nullable_string_enum([s]))
            Some(@spec.Bool(_)) =>
              Some(
                Alias({
                  name: mb_name,
                  target: wrap_nullable(Prim(Bool)),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            Some(@spec.Number(raw)) => {
              let num_ft = if !raw.contains(".") &&
                !raw.contains("e") &&
                !raw.contains("E") {
                let (w, neg) = bound_int_width(raw)
                let fmt = if w >= 2 && !neg {
                  "uint64"
                } else if w >= 1 {
                  "int64"
                } else {
                  ""
                }
                Prim(Int(fmt))
              } else {
                Prim(Num(""))
              }
              Some(
                Alias({
                  name: mb_name,
                  target: wrap_nullable(num_ft),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
            Some(@spec.Null) =>
              Some(
                Alias({
                  name: mb_name,
                  target: FieldType::Optional(JsonValue),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            _ => {
              if schema.not is Some(_) {
                self.diags.unsupported(
                  "W-schema-not", pointer, "standalone `not` schema cannot be statically represented; kept as JSON",
                )
              }
              Some(
                Alias({
                  name: mb_name,
                  target: wrap_nullable(JsonValue),
                  docs,
                  example: schema.example,
                  deprecated: schema.deprecated,
                  source: component,
                }),
              )
            }
          }
      }
  }
}

///|
fn decimal_exceeds(digits : String, limit : String) -> Bool {
  let mut start = 0
  while start < digits.length() && digits.code_unit_at(start).to_int() == 0x30 {
    start += 1
  }
  let norm = if start == digits.length() {
    "0"
  } else {
    digits[start:].to_owned()
  }
  if norm.length() != limit.length() {
    norm.length() > limit.length()
  } else {
    norm > limit
  }
}

///|
/// Classify an integer bound text (including scientific notation such as
/// `5e9`, `9.5e18`, `0e20`):
/// - `0`: fits in signed `Int32` (`[-2147483648, 2147483647]`)
/// - `1`: requires `Int64` (exceeds `Int32`, fits in `Int64`)
/// - `2`: positive value exceeding `Int64::MAX` (needs `UInt64`)
fn bound_int_width(raw : String) -> (Int32, Bool) {
  let s = raw.trim().to_owned()
  let len = s.length()
  if len == 0 {
    return (0, false)
  }
  let mut i = 0
  let mut neg = false
  let first = s.code_unit_at(0).to_int()
  if first == 0x2D {
    neg = true
    i = 1
  } else if first == 0x2B {
    i = 1
  }
  let int_buf = StringBuilder()
  while i < len {
    let c = s.code_unit_at(i).to_int()
    if c >= 0x30 && c <= 0x39 {
      int_buf.write_char(c.unsafe_to_char())
      i += 1
    } else {
      break
    }
  }
  let int_part = int_buf.to_string()
  let frac_buf = StringBuilder()
  if i < len && s.code_unit_at(i).to_int() == 0x2E {
    i += 1
    while i < len {
      let c = s.code_unit_at(i).to_int()
      if c >= 0x30 && c <= 0x39 {
        frac_buf.write_char(c.unsafe_to_char())
        i += 1
      } else {
        break
      }
    }
  }
  let frac_part = frac_buf.to_string()
  if int_part.is_empty() && frac_part.is_empty() {
    return (0, neg)
  }
  let mut exp_val : Int32 = 0
  if i < len &&
    (s.code_unit_at(i).to_int() == 0x65 || s.code_unit_at(i).to_int() == 0x45) {
    i += 1
    let mut exp_neg = false
    if i < len {
      let ec = s.code_unit_at(i).to_int()
      if ec == 0x2D {
        exp_neg = true
        i += 1
      } else if ec == 0x2B {
        i += 1
      }
    }
    while i < len {
      let c = s.code_unit_at(i).to_int()
      if c >= 0x30 && c <= 0x39 {
        if exp_val < 1000 {
          exp_val = exp_val * 10 + (c - 0x30)
        }
        i += 1
      } else {
        break
      }
    }
    if exp_neg {
      exp_val = -exp_val
    }
  }
  // Combine mantissa digits and apply decimal shift `exp_val`.
  let all_digits = int_part + frac_part
  // Strip leading zeros to check zero-mantissa (`0e20`, `0.0e30`).
  let mut first_nz : Int32 = 0
  while first_nz < all_digits.length() &&
        all_digits.code_unit_at(first_nz).to_int() == 0x30 {
    first_nz += 1
  }
  if first_nz == all_digits.length() {
    return (0, false)
  }
  // Number of integer digits = int_part.length() + exp_val - first_nz
  let sig_digits = all_digits[first_nz:].to_owned()
  let int_digit_count = int_part.length() + exp_val - first_nz
  if int_digit_count <= 0 {
    return (0, neg)
  }
  if int_digit_count > 20 {
    return if neg { (1, true) } else { (2, false) }
  }
  let expanded = StringBuilder()
  for k in 0.. String {
  let bounds : Array[String?] = [
    constraints.minimum,
    constraints.maximum,
    constraints.exclusive_minimum,
    constraints.exclusive_maximum,
  ]
  let mut max_width = 0
  let mut any_neg = false
  for b_opt in bounds {
    match b_opt {
      Some(b) => {
        let (w, neg) = bound_int_width(b)
        if w > max_width {
          max_width = w
        }
        if neg {
          any_neg = true
        }
      }
      None => ()
    }
  }
  if max_width >= 2 && !any_neg {
    "uint64"
  } else if max_width >= 1 {
    "int64"
  } else {
    ""
  }
}

///|
/// Infer the integer format for `type: integer`: preserves explicit `format`,
/// and promotes unformatted integers whose `minimum`/`maximum` bounds exceed
/// `Int32` (such as JS/Zod safe integer `±9007199254740991`) to `"int64"` or
/// `"uint64"`.
fn infer_int_format(schema : @spec.Schema) -> String {
  match schema.format {
    Some(f) if f != "" => return f
    _ => ()
  }
  infer_int_format_from_bounds(schema.constraints)
}

///|
priv enum UntypedEnumKind {
  AllStrings(Bool)
  AllInts(String, Bool)
  AllNums(Bool)
  AllBools(Bool)
  Mixed(Bool)
}

///|
fn classify_untyped_enum(values : Array[@spec.Node]) -> UntypedEnumKind {
  let mut has_str = false
  let mut has_int = false
  let mut has_num = false
  let mut has_bool = false
  let mut has_other = false
  let mut has_null = false
  let mut max_int_width = 0
  let mut any_neg = false
  for value in values {
    match value {
      @spec.Null => has_null = true
      @spec.Str(_) => has_str = true
      @spec.Bool(_) => has_bool = true
      @spec.Number(raw) =>
        if !raw.contains(".") && !raw.contains("e") && !raw.contains("E") {
          has_int = true
          let (w, neg) = bound_int_width(raw)
          if w > max_int_width {
            max_int_width = w
          }
          if neg {
            any_neg = true
          }
        } else {
          has_num = true
        }
      _ => has_other = true
    }
  }
  if has_str && !has_int && !has_num && !has_bool && !has_other {
    AllStrings(has_null)
  } else if has_int && !has_str && !has_num && !has_bool && !has_other {
    let fmt = if max_int_width >= 2 && !any_neg {
      "uint64"
    } else if max_int_width >= 1 {
      "int64"
    } else {
      ""
    }
    AllInts(fmt, has_null)
  } else if (has_int || has_num) && !has_str && !has_bool && !has_other {
    AllNums(has_null)
  } else if has_bool && !has_str && !has_int && !has_num && !has_other {
    AllBools(has_null)
  } else {
    Mixed(has_null)
  }
}

///|
/// Build a string-enum definition with pre-computed PascalCase variant names
/// and a collision-free open fallback variant name (`Unknown` or `UnknownValue`).
fn IrBuilder::string_enum_def(
  self : IrBuilder,
  source : String,
  mb_name : String,
  values : Array[@spec.Node],
  schema : @spec.Schema,
  pointer : String,
  allow_null~ : Bool = false,
) -> TypeDef {
  let docs = docs_from_option(schema.description)
  let variant_namer = @name.Namer::new()
  let seen_wires : Map[String, Unit] = Map([])
  let variants : Array[StringEnumVariant] = []
  let mut skipped_non_strings = 0
  let permit_null = schema.nullable || allow_null
  for value in values {
    match value {
      @spec.Str(text) =>
        if !seen_wires.contains(text) {
          seen_wires[text] = ()
          let name = variant_namer.unique_type(@name.ident_pascal(text))
          variants.push({ name, wire: text, })
        }
      @spec.Null if permit_null => ()
      _ => skipped_non_strings += 1
    }
  }
  if variants.is_empty() {
    self.diags.error(
      "E-enum", pointer, "string enum has no string values; kept as JSON",
    )
    return Alias({
      name: mb_name,
      target: JsonValue,
      docs,
      example: schema.example,
      deprecated: schema.deprecated,
      source,
    })
  }
  if skipped_non_strings > 0 {
    self.diags.warning(
      "W-enum-non-string",
      pointer,
      "string enum contained \{skipped_non_strings} non-string value(s); skipped",
    )
  }
  let is_open = ext_bool(schema.extras, "x-moonbit-open", pointer, self.diags).unwrap_or(
    self.options.open_string_enums,
  )
  let unknown_variant = if is_open {
    Some(allocate_unknown_variant(variant_namer))
  } else {
    None
  }
  StringEnum({
    name: mb_name,
    variants,
    open: is_open,
    unknown_variant,
    docs,
    example: schema.example,
    deprecated: schema.deprecated,
    source,
  })
}

///|
/// Lower a schema reference used as a property/param/item/map-value type.
/// Named components stay references (and are validated for existence); inline
/// structures are promoted.
fn IrBuilder::field_type_of_ref(
  self : IrBuilder,
  schema_ref : @spec.RefOr[@spec.Schema],
  pointer~ : String,
  name_context~ : String,
) -> FieldType? raise @spec.SpecError {
  match schema_ref {
    @spec.Ref(target) => {
      let sibling_nullable = target.siblings
        .iter()
        .any(fn(pair) { pair.0 == "nullable" && pair.1 is @spec.Bool(true) })
      let resolved : FieldType? = match ref_component(target.ref_) {
        Some(component) =>
          if self.component_schemas.contains(component) {
            let mb_name = self.ensure_component(component)
            Some(Named(mb_name))
          } else {
            self.diags.error(
              "E-dangling-ref",
              pointer,
              "$ref points to missing component schema \"\{component}\"",
            )
            None
          }
        None =>
          // Support general internal JSON pointers (e.g. OAS 3.1 `#/$defs/Foo`)
          // with cycle-safe caching so recursive `#/$defs/Node` never overflows!
          if target.ref_.has_prefix("#/") {
            match self.internal_ref_names.get(target.ref_) {
              Some(cached_name) => Some(Named(cached_name))
              None =>
                match self.resolver.resolve_ref_chain(target.ref_) {
                  Some(node) => {
                    let segs : Array[String] = []
                    for s in target.ref_[2:].split("/") {
                      segs.push(s.to_owned())
                    }
                    let tail = if !segs.is_empty() {
                      @spec.json_pointer_unescape(segs[segs.length() - 1][:])
                    } else {
                      name_context
                    }
                    let promoted = self.type_namer.unique_type(
                      @name.ident_pascal(tail),
                    )
                    self.internal_ref_names[target.ref_] = promoted
                    match @spec.decode_schema(node, pointer, self.diags) {
                      Some(@spec.Item(s)) => {
                        let def_opt = self.build_schema_def(
                          target.ref_,
                          s,
                          promoted,
                          pointer,
                        )
                        match def_opt {
                          Some(def) => self.add_def(def)
                          None => self.add_json_fallback(promoted, target.ref_)
                        }
                        Some(Named(promoted))
                      }
                      Some(@spec.Ref(nested)) => {
                        self.internal_ref_names.remove(target.ref_)
                        self.field_type_of_ref(
                          @spec.Ref(nested),
                          pointer~,
                          name_context~,
                        )
                      }
                      None => {
                        self.internal_ref_names.remove(target.ref_)
                        None
                      }
                    }
                  }
                  None => None
                }
            }
          } else {
            self.diags.error(
              "E-external-ref",
              pointer,
              "external or non-schema references are not supported: \"\{target.ref_}\"",
            )
            None
          }
      }
      match resolved {
        Some(ft) => Some(if sibling_nullable { make_optional(ft) } else { ft })
        None => None
      }
    }
    @spec.Item(schema) =>
      self.field_type_of_schema(schema, pointer~, name_context~)
  }
}

///|
/// Lower an inline schema used in a value position.
fn IrBuilder::field_type_of_schema(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> FieldType? raise @spec.SpecError {
  fn wrap_nullable(ft : FieldType) -> FieldType {
    if schema.nullable {
      make_optional(ft)
    } else {
      ft
    }
  }

  // 1. oneOf / anyOf
  match schema.one_of {
    Some(members) =>
      match unwrap_nullable_one_of(members) {
        Some(other) =>
          match self.field_type_of_ref(other, pointer~, name_context~) {
            Some(inner) => return Some(make_optional(inner))
            None => return None
          }
        None => {
          let promoted = self.promote_one_of(schema, pointer~, name_context~)
          let has_null = schema.nullable ||
            members.iter().any(is_null_one_of_member)
          // Avoid double-wrapping if promoted already became Alias(Optional(...))
          let already_opt = match self.types.get(promoted) {
            Some(Alias(a)) => a.target is Optional(_)
            _ => false
          }
          return Some(
            if has_null && !already_opt {
              make_optional(Named(promoted))
            } else {
              Named(promoted)
            },
          )
        }
      }
    None => ()
  }
  match schema.any_of {
    Some(members) =>
      match unwrap_nullable_one_of(members) {
        Some(other) =>
          match self.field_type_of_ref(other, pointer~, name_context~) {
            Some(inner) => return Some(make_optional(inner))
            None => return None
          }
        None => {
          let promoted = self.promote_any_of(schema, pointer~, name_context~)
          let has_null = schema.nullable ||
            members.iter().any(is_null_one_of_member)
          let already_opt = match self.types.get(promoted) {
            Some(Alias(a)) => a.target is Optional(_)
            _ => false
          }
          return Some(
            if has_null && !already_opt {
              make_optional(Named(promoted))
            } else {
              Named(promoted)
            },
          )
        }
      }
    None => ()
  }
  // 1b. OpenAPI 3.1 multi-type arrays (e.g. `type: ["string", "integer"]`)
  let multi_types : Array[String] = []
  for t in schema.types {
    if t != "null" {
      multi_types.push(t)
    }
  }
  if multi_types.length() >= 2 {
    let promoted = self.promote_multi_type(
      schema,
      multi_types,
      pointer~,
      name_context~,
    )
    let already_opt = match self.types.get(promoted) {
      Some(Alias(a)) => a.target is Optional(_)
      _ => false
    }
    return Some(
      if schema.nullable && !already_opt {
        FieldType::Optional(Named(promoted))
      } else {
        Named(promoted)
      },
    )
  }
  // 2. allOf: unwrap single-$ref metadata/nullable wrappers directly without
  // polluting the registry with spurious aliases!
  if schema.all_of is Some(_) {
    match unwrap_single_ref_all_of(schema) {
      Some(unwrapped) =>
        match self.resolve_all_of_ref_name(unwrapped.ref_str, pointer) {
          Some(mb_name) =>
            return Some(
              if unwrapped.nullable {
                FieldType::Optional(Named(mb_name))
              } else {
                Named(mb_name)
              },
            )
          None => return None
        }
      None => {
        let promoted = self.promote_all_of(schema, pointer~, name_context~)
        let already_opt = match self.types.get(promoted) {
          Some(Alias(a)) => a.target is Optional(_)
          _ => false
        }
        return Some(
          if schema.nullable && !already_opt {
            FieldType::Optional(Named(promoted))
          } else {
            Named(promoted)
          },
        )
      }
    }
  }
  // 3. Plain / inferred shapes
  let effective_type : String? = match schema.type_ {
    Some(t) => Some(t)
    None =>
      if !schema.properties.is_empty() ||
        schema.additional_properties is Some(_) {
        Some("object")
      } else if schema.items is Some(_) {
        Some("array")
      } else {
        None
      }
  }
  let inner : FieldType? = match effective_type {
    Some("object") =>
      if !schema.properties.is_empty() {
        match schema.additional_properties {
          Some(@spec.AdditionalProperties::Schema(_)) =>
            self.diags.unsupported(
              "W-additional-properties", pointer, "inline object has both properties and typed additionalProperties; additionalProperties ignored",
            )
          _ => ()
        }
        let promoted = self.promote_inline_object(
          schema,
          pointer~,
          name_context~,
        )
        Some(Named(promoted))
      } else {
        match schema.additional_properties {
          Some(@spec.AdditionalProperties::Schema(value_schema)) =>
            match
              self.field_type_of_ref(
                value_schema,
                pointer=@spec.pointer_join(pointer, "additionalProperties"),
                name_context=name_context + ".Value",
              ) {
              Some(value_type) => Some(MapTo(value_type))
              None => return None
            }
          Some(@spec.AdditionalProperties::Allowed(_)) | None => Some(JsonValue)
        }
      }
    Some("array") =>
      match schema.items {
        Some(items_ref) =>
          match
            self.field_type_of_ref(
              items_ref,
              pointer=@spec.pointer_join(pointer, "items"),
              name_context=name_context + ".Item",
            ) {
            Some(item_type) => Some(List(item_type))
            None => return None
          }
        None => {
          self.diags.warning(
            "W-missing-items", pointer, "array schema omits items; defaulting to Array[Json]",
          )
          Some(List(JsonValue))
        }
      }
    Some("string") =>
      match schema.enum_ {
        Some(values) => {
          let promoted = self.promote_string_enum(
            schema,
            values,
            pointer~,
            name_context~,
          )
          Some(Named(promoted))
        }
        None => Some(Prim(Str(schema.format.unwrap_or(""))))
      }
    Some("integer") => Some(Prim(Int(infer_int_format(schema))))
    Some("number") => Some(Prim(Num(schema.format.unwrap_or(""))))
    Some("boolean") => Some(Prim(Bool))
    Some("char") => Some(Prim(Str("char")))
    Some("null") => Some(FieldType::Optional(JsonValue))
    Some(other) => {
      self.diags.unsupported(
        "W-schema-type",
        pointer,
        "schema type \"\{other}\" is not modeled; kept as JSON",
      )
      Some(JsonValue)
    }
    None =>
      match schema.enum_ {
        Some(values) =>
          match classify_untyped_enum(values) {
            AllStrings(has_null) => {
              let promoted = self.promote_string_enum(
                schema,
                values,
                pointer~,
                name_context~,
              )
              Some(
                if has_null && !schema.nullable {
                  FieldType::Optional(Named(promoted))
                } else {
                  Named(promoted)
                },
              )
            }
            AllInts(fmt, has_null) =>
              Some(
                if has_null && !schema.nullable {
                  FieldType::Optional(Prim(Int(fmt)))
                } else {
                  Prim(Int(fmt))
                },
              )
            AllNums(has_null) =>
              Some(
                if has_null && !schema.nullable {
                  FieldType::Optional(Prim(Num("")))
                } else {
                  Prim(Num(""))
                },
              )
            AllBools(has_null) =>
              Some(
                if has_null && !schema.nullable {
                  FieldType::Optional(Prim(Bool))
                } else {
                  Prim(Bool)
                },
              )
            Mixed(has_null) => {
              self.diags.unsupported(
                "W-enum-mixed", pointer, "enum contains mixed or non-scalar values; kept as JSON",
              )
              Some(
                if has_null && !schema.nullable {
                  FieldType::Optional(JsonValue)
                } else {
                  JsonValue
                },
              )
            }
          }
        None =>
          match schema.const_ {
            Some(@spec.Str(_) as s) => {
              let promoted = self.promote_string_enum(
                schema,
                [s],
                pointer~,
                name_context~,
              )
              Some(Named(promoted))
            }
            Some(@spec.Bool(_)) => Some(Prim(Bool))
            Some(@spec.Number(raw)) =>
              if !raw.contains(".") && !raw.contains("e") && !raw.contains("E") {
                let (w, neg) = bound_int_width(raw)
                let fmt = if w >= 2 && !neg {
                  "uint64"
                } else if w >= 1 {
                  "int64"
                } else {
                  ""
                }
                Some(Prim(Int(fmt)))
              } else {
                Some(Prim(Num("")))
              }
            Some(@spec.Null) => Some(FieldType::Optional(JsonValue))
            _ => {
              if schema.not is Some(_) {
                self.diags.unsupported(
                  "W-schema-not", pointer, "standalone `not` schema cannot be statically represented; kept as JSON",
                )
              }
              Some(JsonValue)
            }
          }
      }
  }
  match inner {
    Some(field_type) => Some(wrap_nullable(field_type))
    None => None
  }
}

///|
fn IrBuilder::promote_inline_object(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> String raise @spec.SpecError {
  // Reserve name upfront BEFORE recursing into fields so nested promotions
  // can never collide with this name.
  let promoted = self.reserve_promotion_name(name_context)
  match self.fields_of_properties(schema, pointer~, name_context=promoted) {
    Some(fields) =>
      self.add_def(
        Record({
          name: promoted,
          fields,
          docs: docs_from_option(schema.description),
          example: schema.example,
          deprecated: schema.deprecated,
          source: name_context,
        }),
      )
    None =>
      self.add_json_fallback(
        promoted,
        name_context,
        docs=docs_from_option(schema.description),
      )
  }
  promoted
}

///|
fn IrBuilder::promote_one_of(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> String raise @spec.SpecError {
  let promoted = self.reserve_promotion_name(name_context)
  let docs = docs_from_option(schema.description)
  match self.build_one_of_def(name_context, schema, promoted, docs, pointer) {
    Some(def) => self.add_def(def)
    None => self.add_json_fallback(promoted, name_context, docs~)
  }
  promoted
}

///|
fn IrBuilder::promote_any_of(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> String raise @spec.SpecError {
  let promoted = self.reserve_promotion_name(name_context)
  let docs = docs_from_option(schema.description)
  match self.build_any_of_def(name_context, schema, promoted, docs, pointer) {
    Some(def) => self.add_def(def)
    None => self.add_json_fallback(promoted, name_context, docs~)
  }
  promoted
}

///|
fn IrBuilder::promote_multi_type(
  self : IrBuilder,
  schema : @spec.Schema,
  non_null_types : Array[String],
  pointer~ : String,
  name_context~ : String,
) -> String raise @spec.SpecError {
  let promoted = self.reserve_promotion_name(name_context)
  let docs = docs_from_option(schema.description)
  match
    self.build_multi_type_def(
      name_context, schema, non_null_types, promoted, docs, pointer,
    ) {
    Some(def) => self.add_def(def)
    None => self.add_json_fallback(promoted, name_context, docs~)
  }
  promoted
}

///|
fn IrBuilder::promote_all_of(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> String raise @spec.SpecError {
  let promoted = self.reserve_promotion_name(name_context)
  let docs = docs_from_option(schema.description)
  match self.build_all_of(name_context, schema, promoted, docs, pointer) {
    Some(def) => self.add_def(def)
    None => self.add_json_fallback(promoted, name_context, docs~)
  }
  promoted
}

///|
fn IrBuilder::promote_string_enum(
  self : IrBuilder,
  schema : @spec.Schema,
  values : Array[@spec.Node],
  pointer~ : String,
  name_context~ : String,
) -> String {
  let promoted = self.reserve_promotion_name(name_context)
  self.add_def(
    self.string_enum_def(name_context, promoted, values, schema, pointer),
  )
  promoted
}

///|
/// Build record fields from `schema.properties` + `schema.required`, in source
/// order. Returns `None` if any property fails to decode.
fn IrBuilder::fields_of_properties(
  self : IrBuilder,
  schema : @spec.Schema,
  pointer~ : String,
  name_context~ : String,
) -> Array[FieldIR]? raise @spec.SpecError {
  let fields : Array[FieldIR] = []
  let field_namer = @name.Namer::new()
  let props_ptr = @spec.pointer_join(pointer, "properties")
  for entry in schema.properties {
    let (prop_name, prop_ref) = entry
    let prop_ptr = @spec.pointer_join(props_ptr, prop_name)
    let is_req = schema.required.contains(prop_name)
    // `x-moonbit-ignore: true` omits optional fields from the record.
    let ignored = match prop_ref {
      @spec.Item(ps) =>
        !is_req &&
        ext_bool(ps.extras, "x-moonbit-ignore", prop_ptr, self.diags).unwrap_or(
          false,
        )
      @spec.Ref(_) => false
    }
    if ignored {
      continue
    }
    let field = match
      self.field_from_property(
        prop_name,
        prop_ref,
        is_req,
        field_namer,
        pointer=prop_ptr,
        name_context=name_context + "." + prop_name,
      ) {
      Some(f) => f
      None => return None
    }
    fields.push(field)
  }
  Some(fields)
}

///|
/// Compute 4-state `Presence` from `(required, nullable)`.
fn compute_presence(required : Bool, nullable : Bool) -> Presence {
  match (required, nullable) {
    (true, false) => Required
    (true, true) => RequiredNullable
    (false, false) => Optional
    (false, true) => OptionalNullable
  }
}

///|
/// Strip one top-level `FieldType::Optional` wrapper so `FieldIR.type_` and
/// `ParamIR.type_` always hold the unwrapped base type while `Presence` is the
/// single source of truth for optionality/nullability.
fn unwrap_optional_type(ft : FieldType) -> (FieldType, Bool) {
  match ft {
    Optional(inner) => (inner, true)
    other => (other, false)
  }
}

///|
/// Recursively inspect a schema or `$ref` (following bare `$ref`, single-ref
/// `allOf`, `[X, null]` `oneOf`/`anyOf`, and `#/$defs/...`) to collect
/// inherited `(read_only, write_only)` flags without infinite recursion.
fn IrBuilder::effective_access_flags(
  self : IrBuilder,
  sref : @spec.RefOr[@spec.Schema],
  visited : Array[String],
) -> (Bool, Bool) {
  if visited.length() > 32 {
    return (false, false)
  }
  match sref {
    @spec.Ref(target) => {
      let mut ro = false
      let mut wo = false
      for sib in target.siblings {
        if sib.0 == "readOnly" && sib.1 is @spec.Bool(true) {
          ro = true
        } else if sib.0 == "writeOnly" && sib.1 is @spec.Bool(true) {
          wo = true
        }
      }
      if visited.contains(target.ref_) {
        return (ro, wo)
      }
      let next_visited = visited.copy()
      next_visited.push(target.ref_)
      match ref_component(target.ref_) {
        Some(comp) =>
          match self.component_schemas.get(comp) {
            Some(inner_ref) => {
              let (iro, iwo) = self.effective_access_flags(
                inner_ref, next_visited,
              )
              (ro || iro, wo || iwo)
            }
            None => (ro, wo)
          }
        None =>
          if target.ref_.has_prefix("#/") {
            match self.resolver.resolve(target.ref_) {
              Some(@spec.Object(obj)) => {
                if obj.get("readOnly") is Some(@spec.Bool(true)) {
                  ro = true
                }
                if obj.get("writeOnly") is Some(@spec.Bool(true)) {
                  wo = true
                }
                (ro, wo)
              }
              _ => (ro, wo)
            }
          } else {
            (ro, wo)
          }
      }
    }
    @spec.Item(s) => {
      let mut ro = s.read_only
      let mut wo = s.write_only
      match unwrap_single_ref_all_of(s) {
        Some(unwrapped) => {
          if unwrapped.read_only {
            ro = true
          }
          if unwrapped.write_only {
            wo = true
          }
          let (iro, iwo) = self.effective_access_flags(
            @spec.Ref({
              ref_: unwrapped.ref_str,
              summary: None,
              description: None,
              siblings: [],
            }),
            visited,
          )
          return (ro || iro, wo || iwo)
        }
        None => ()
      }
      let nullable_inner = match s.one_of {
        Some(ms) => unwrap_nullable_one_of(ms)
        None =>
          match s.any_of {
            Some(ms) => unwrap_nullable_one_of(ms)
            None => None
          }
      }
      match nullable_inner {
        Some(inner_ref) => {
          let (iro, iwo) = self.effective_access_flags(inner_ref, visited)
          (ro || iro, wo || iwo)
        }
        None => (ro, wo)
      }
    }
  }
}

///|
/// Build one immutable `FieldIR` from a property, extracting `description`,
/// `default`, `example`, `deprecated`, and unwrapping single-`$ref` `allOf`
/// wrappers cleanly.
fn IrBuilder::field_from_property(
  self : IrBuilder,
  wire_name : String,
  prop_ref : @spec.RefOr[@spec.Schema],
  required : Bool,
  field_namer : @name.Namer,
  pointer~ : String,
  name_context~ : String,
) -> FieldIR? raise @spec.SpecError {
  let mut description : String? = None
  let mut default : @spec.Node? = None
  let mut example : @spec.Node? = None
  let mut deprecated = false
  let (init_ro, init_wo) = self.effective_access_flags(prop_ref, [])
  let mut read_only = init_ro
  let mut write_only = init_wo
  let mut constraints = @spec.SchemaConstraints::empty()
  let mut nullable = false
  let raw_type : FieldType = match prop_ref {
    @spec.Item(s) => {
      description = s.description
      default = s.default
      example = s.example
      deprecated = s.deprecated
      if s.read_only {
        read_only = true
      }
      if s.write_only {
        write_only = true
      }
      constraints = s.constraints
      if s.nullable {
        nullable = true
      }
      // Unwrap single-$ref allOf wrapper so we keep metadata & avoid T??
      match unwrap_single_ref_all_of(s) {
        Some(unwrapped) => {
          if unwrapped.nullable {
            nullable = true
          }
          if description is None {
            description = unwrapped.description
          }
          if default is None {
            default = unwrapped.default
          }
          if example is None {
            example = unwrapped.example
          }
          if unwrapped.deprecated {
            deprecated = true
          }
          if unwrapped.read_only {
            read_only = true
          }
          if unwrapped.write_only {
            write_only = true
          }
          match self.resolve_all_of_ref_name(unwrapped.ref_str, pointer) {
            Some(mb_name) => Named(mb_name)
            None => return None
          }
        }
        None =>
          match self.field_type_of_schema(s, pointer~, name_context~) {
            Some(ft) => ft
            None => return None
          }
      }
    }
    @spec.Ref(target) => {
      if target.description is Some(_) {
        description = target.description
      }
      for sib in target.siblings {
        if sib.0 == "readOnly" && sib.1 is @spec.Bool(true) {
          read_only = true
        } else if sib.0 == "writeOnly" && sib.1 is @spec.Bool(true) {
          write_only = true
        } else if sib.0 == "deprecated" && sib.1 is @spec.Bool(true) {
          deprecated = true
        }
      }
      match self.field_type_of_ref(prop_ref, pointer~, name_context~) {
        Some(ft) => ft
        None => return None
      }
    }
  }
  let (base_type, was_opt) = unwrap_optional_type(raw_type)
  if was_opt {
    nullable = true
  }
  let presence = compute_presence(required, nullable)
  let custom_field_name : String? = match prop_ref {
    @spec.Item(s) => ext_str(s.extras, "x-moonbit-name", pointer, self.diags)
    @spec.Ref(t) => ext_str(t.siblings, "x-moonbit-name", pointer, self.diags)
  }
  let name = field_namer.unique(
    match custom_field_name {
      Some(cn) => @name.ident_snake(cn)
      None => @name.ident_snake(wire_name)
    },
  )
  Some({
    name,
    wire: wire_name,
    type_: base_type,
    presence,
    default,
    example,
    deprecated,
    read_only,
    write_only,
    constraints,
    docs: docs_from_option(description),
  })
}