// allOf lowering: single-$ref wrapper unwrapping, multi-$ref & inline record
// merging, `{required: [...]}` overrides, and alias chain unwrapping.

///|
/// True if an inline `allOf` item carries no structural object/array/combinator
/// definition (only metadata like `nullable`, `description`, `default`,
/// `example`, or scalar validation constraints like `maxLength`/`pattern`).
fn is_metadata_only_all_of_item(item : @spec.Schema) -> Bool {
  item.properties.is_empty() &&
  item.required.is_empty() &&
  item.all_of is None &&
  item.one_of is None &&
  item.any_of is None &&
  item.enum_ is None &&
  item.const_ is None &&
  item.items is None &&
  item.additional_properties is None
}

///|
/// True if an inline `allOf` item carries a non-object schema definition
/// (primitive scalar, enum/const, array, typed map, multi-type, or oneOf/anyOf)
/// with no object `properties` of its own.
fn is_non_object_inline_all_of_item(item : @spec.Schema) -> Bool {
  if !item.properties.is_empty() || item.all_of is Some(_) {
    return false
  }
  match item.type_ {
    Some(t) if t != "object" => return true
    _ => ()
  }
  item.types.length() >= 2 ||
  item.enum_ is Some(_) ||
  item.const_ is Some(_) ||
  item.items is Some(_) ||
  item.additional_properties is Some(_) ||
  item.one_of is Some(_) ||
  item.any_of is Some(_)
}

///|
/// Result of unwrapping a single-`$ref` `allOf` wrapper at property/value
/// position (`allOf: [$ref: Foo, {nullable: true}, {description: "..."}]`).
priv struct UnwrappedAllOfRef {
  ref_str : String
  nullable : Bool
  description : String?
  default : @spec.Node?
  example : @spec.Node?
  deprecated : Bool
  read_only : Bool
  write_only : Bool
}

///|
/// If `schema` is an inline `allOf` wrapper around a single `$ref` plus only
/// metadata/nullable markers (and no outer properties), unwrap it so we do NOT
/// synthesize a spurious named `Alias` type or double-wrap `T??`.
fn unwrap_single_ref_all_of(schema : @spec.Schema) -> UnwrappedAllOfRef? {
  let members = match schema.all_of {
    Some(m) => m
    None => return None
  }
  if !schema.properties.is_empty() ||
    !schema.required.is_empty() ||
    schema.one_of is Some(_) ||
    schema.any_of is Some(_) {
    return None
  }
  let mut ref_str : String? = None
  let mut nullable = schema.nullable
  let mut description = schema.description
  let mut default = schema.default
  let mut example = schema.example
  let mut deprecated = schema.deprecated
  let mut read_only = schema.read_only
  let mut write_only = schema.write_only
  for branch in members {
    match branch {
      @spec.Ref(target) =>
        match ref_str {
          None => {
            ref_str = Some(target.ref_)
            for sib in target.siblings {
              if sib.0 == "nullable" && sib.1 is @spec.Bool(true) {
                nullable = true
              } else 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
              }
            }
          }
          // Multiple $refs -> genuine composition, not a single-ref wrapper
          Some(_) => return None
        }
      @spec.Item(item) => {
        if !is_metadata_only_all_of_item(item) {
          return None
        }
        if item.nullable {
          nullable = true
        }
        if description is None && item.description is Some(_) {
          description = item.description
        }
        if default is None && item.default is Some(_) {
          default = item.default
        }
        if example is None && item.example is Some(_) {
          example = item.example
        }
        if item.deprecated {
          deprecated = true
        }
        if item.read_only {
          read_only = true
        }
        if item.write_only {
          write_only = true
        }
      }
    }
  }
  match ref_str {
    Some(r) =>
      Some({
        ref_str: r,
        nullable,
        description,
        default,
        example,
        deprecated,
        read_only,
        write_only,
      })
    None => None
  }
}

///|
/// Resolve a `$ref` inside `allOf`: handles both top-level component schema
/// refs (`#/components/schemas/Foo`) and general internal sub-schema JSON
/// pointers (e.g. `#/components/schemas/Tag/allOf/0`, `#/$defs/Base`).
/// Returns the MoonBit type name of the resolved target.
fn IrBuilder::resolve_all_of_ref_name(
  self : IrBuilder,
  ref_str : String,
  pointer : String,
) -> String? raise @spec.SpecError {
  match ref_component(ref_str) {
    Some(comp) =>
      if self.component_schemas.contains(comp) {
        Some(self.ensure_component(comp))
      } else {
        self.diags.error(
          "E-dangling-ref",
          pointer,
          "$ref points to missing component schema \"\{comp}\"",
        )
        None
      }
    None =>
      if ref_str.has_prefix("#/") {
        match
          self.field_type_of_ref(
            @spec.Ref({
              ref_: ref_str,
              summary: None,
              description: None,
              siblings: [],
            }),
            pointer~,
            name_context="AllOfRef",
          ) {
          Some(Named(name)) => Some(name)
          _ => None
        }
      } else {
        self.diags.error(
          "E-external-ref",
          pointer,
          "external or non-schema references are not supported: \"\{ref_str}\"",
        )
        None
      }
  }
}

///|
/// Lower a component or promoted `allOf` schema:
/// - Single `$ref` (+ metadata/constraints/nullable) -> `Alias(Named(T) | Optional(Named(T)))`
/// - Multiple `$ref`s and/or inline objects -> merged `Record` (or nullable
///   inner `Record` + `Alias(Optional(Named(inner)))`).
fn IrBuilder::build_all_of(
  self : IrBuilder,
  source : String,
  schema : @spec.Schema,
  mb_name : String,
  docs : Array[String],
  pointer : String,
) -> TypeDef? raise @spec.SpecError {
  let members = match schema.all_of {
    Some(m) => m
    None => return None
  }
  let mut nullable = schema.nullable
  let raw_refs : Array[@spec.RefTarget] = []
  let inline_objects : Array[@spec.Schema] = []
  let inline_non_objects : Array[@spec.Schema] = []
  let extra_required : Array[String] = schema.required.copy()
  let mut merged_docs = docs
  let mut merged_example = schema.example
  let mut merged_deprecated = schema.deprecated
  fn collect_branches(
    branches : Array[@spec.RefOr[@spec.Schema]],
    depth : Int32,
  ) -> Unit {
    if depth > 16 {
      return
    }
    for branch in branches {
      match branch {
        @spec.Ref(target) => {
          if merged_docs.is_empty() && target.description is Some(_) {
            merged_docs = docs_from_option(target.description)
          }
          for sib in target.siblings {
            if sib.0 == "nullable" && sib.1 is @spec.Bool(true) {
              nullable = true
            } else if sib.0 == "deprecated" && sib.1 is @spec.Bool(true) {
              merged_deprecated = true
            }
          }
          raw_refs.push(target)
        }
        @spec.Item(item) => {
          if item.nullable &&
            (
              is_metadata_only_all_of_item(item) ||
              is_non_object_inline_all_of_item(item)
            ) {
            nullable = true
          }
          if merged_docs.is_empty() && item.description is Some(_) {
            merged_docs = docs_from_option(item.description)
          }
          if merged_example is None && item.example is Some(_) {
            merged_example = item.example
          }
          if item.deprecated {
            merged_deprecated = true
          }
          for req in item.required {
            if !extra_required.contains(req) {
              extra_required.push(req)
            }
          }
          // Flatten nested inline `allOf` branches recursively so parent refs
          // and properties inside nested `allOf` are never silently dropped.
          match item.all_of {
            Some(nested) => {
              if item.nullable {
                nullable = true
              }
              collect_branches(nested, depth + 1)
              if !item.properties.is_empty() {
                inline_objects.push(item)
              }
            }
            None =>
              if is_non_object_inline_all_of_item(item) {
                inline_non_objects.push(item)
              } else if !is_metadata_only_all_of_item(item) {
                // Items that ONLY carry `required` (no properties/type/combinators)
                // are already captured in `extra_required`.
                if !item.properties.is_empty() ||
                  item.type_ is Some(_) ||
                  item.one_of is Some(_) ||
                  item.any_of is Some(_) {
                  inline_objects.push(item)
                }
              }
          }
        }
      }
    }
  }

  collect_branches(members, 0)
  // Single-$ref alias (only when there is exactly ONE ref and no inline props/required):
  // check `alias_in_progress` BEFORE resolving the target ref so mutual cycles
  // (`A -> B -> A`) are caught cleanly without false positives on recursive structs.
  if inline_objects.is_empty() &&
    inline_non_objects.is_empty() &&
    schema.properties.is_empty() &&
    extra_required.is_empty() &&
    raw_refs.length() == 1 {
    let target_ref = raw_refs[0].ref_
    let target_mb_opt : String? = match ref_component(target_ref) {
      Some(c) => Some(self.moonbit_component_name(c))
      None => None
    }
    match target_mb_opt {
      Some(tmb) if tmb == mb_name || self.alias_in_progress.contains(tmb) => {
        self.diags.error(
          "E-ref-cycle",
          pointer,
          "cyclic allOf alias \"\{mb_name}\" -> \"\{tmb}\"; falling back to JSON",
        )
        return Some(
          Alias({
            name: mb_name,
            target: JsonValue,
            docs: merged_docs,
            example: merged_example,
            deprecated: merged_deprecated,
            source,
          }),
        )
      }
      _ => ()
    }
    self.alias_in_progress.push(mb_name)
    let resolved = self.resolve_all_of_ref_name(target_ref, pointer)
    self.pop_alias_guard(mb_name)
    match resolved {
      Some(payload_name) => {
        let target = if payload_name == mb_name {
          self.diags.error(
            "E-ref-cycle",
            pointer,
            "cyclic allOf alias \"\{mb_name}\"; falling back to JSON",
          )
          JsonValue
        } else if nullable {
          make_optional(Named(payload_name))
        } else {
          Named(payload_name)
        }
        return Some(
          Alias({
            name: mb_name,
            target,
            docs: merged_docs,
            example: merged_example,
            deprecated: merged_deprecated,
            source,
          }),
        )
      }
      None => return None
    }
  }
  let payload_ref_names : Array[String] = []
  for target in raw_refs {
    match self.resolve_all_of_ref_name(target.ref_, pointer) {
      Some(mb_parent) => payload_ref_names.push(mb_parent)
      None => return None
    }
  }
  // Inline non-object allOf (e.g. `allOf: [{ type: "string", nullable: true }]`
  // or `allOf: [{ type: "array", items: ... }, { description: "..." }]`).
  if payload_ref_names.is_empty() &&
    inline_objects.is_empty() &&
    schema.properties.is_empty() &&
    !inline_non_objects.is_empty() {
    let base = inline_non_objects[0]
    match
      self.field_type_of_schema(base, pointer~, name_context=mb_name + "Value") {
      Some(ft) => {
        let already_opt = match ft {
          Optional(_) => true
          Named(n) =>
            match self.types.get(n) {
              Some(Alias(a)) => a.target is Optional(_)
              _ => false
            }
          _ => false
        }
        let target = if (nullable || base.nullable) && !already_opt {
          FieldType::Optional(ft)
        } else {
          ft
        }
        return Some(
          Alias({
            name: mb_name,
            target,
            docs: merged_docs,
            example: merged_example,
            deprecated: merged_deprecated,
            source,
          }),
        )
      }
      None => return None
    }
  }
  // Merged record across outer properties + inline objects + all parent $refs
  let field_namer = @name.Namer::new()
  let fields : Array[FieldIR] = []
  let wire_index : Map[String, Int32] = Map([])
  fn merge_inline_schema(src : @spec.Schema) -> Bool raise @spec.SpecError {
    for entry in src.properties {
      let (prop_name, prop_ref) = entry
      let is_req = src.required.contains(prop_name) ||
        extra_required.contains(prop_name)
      let prop_ptr = @spec.pointer_join(
        @spec.pointer_join(pointer, "properties"),
        prop_name,
      )
      match wire_index.get(prop_name) {
        Some(idx) => {
          // Re-use a fresh namer so overriding the same wire property preserves
          // its original MoonBit identifier instead of allocating `_2`.
          let prev = fields[idx]
          let keep_req = is_req || prev.presence.is_required()
          let scratch_namer = @name.Namer::new()
          let field = match
            self.field_from_property(
              prop_name,
              prop_ref,
              keep_req,
              scratch_namer,
              pointer=prop_ptr,
              name_context=mb_name + "." + prop_name,
            ) {
            Some(f) => f
            None => return false
          }
          fields[idx] = { ..field, name: prev.name, }
        }
        None => {
          let field = match
            self.field_from_property(
              prop_name,
              prop_ref,
              is_req,
              field_namer,
              pointer=prop_ptr,
              name_context=mb_name + "." + prop_name,
            ) {
            Some(f) => f
            None => return false
          }
          wire_index[prop_name] = fields.length()
          fields.push(field)
        }
      }
    }
    true
  }

  if !schema.properties.is_empty() {
    if !merge_inline_schema(schema) {
      self.diags.error(
        "E-allOf", pointer, "allOf outer properties could not be decoded; kept as JSON",
      )
      return None
    }
  }
  for inline in inline_objects {
    if !merge_inline_schema(inline) {
      self.diags.error(
        "E-allOf", pointer, "allOf inline member has undecodable properties; kept as JSON",
      )
      return None
    }
  }
  let mut non_record_parent : String? = None
  for parent_name in payload_ref_names {
    match self.unwrapped_record(parent_name) {
      Some(parent_fields) =>
        for pf in parent_fields {
          match wire_index.get(pf.wire) {
            Some(idx) => {
              // Preserve parent `required` constraint when an inline member
              // overrides a field's type/docs without repeating `required`.
              let existing = fields[idx]
              if pf.presence.is_required() && !existing.presence.is_required() {
                let upgraded = match existing.presence {
                  Optional => Presence::Required
                  OptionalNullable => Presence::RequiredNullable
                  other => other
                }
                fields[idx] = { ..existing, presence: upgraded, }
              }
              continue
            }
            None => ()
          }
          let upgraded_presence = if extra_required.contains(pf.wire) {
            match pf.presence {
              Optional => Presence::Required
              OptionalNullable => Presence::RequiredNullable
              other => other
            }
          } else {
            pf.presence
          }
          wire_index[pf.wire] = fields.length()
          fields.push({
            ..pf,
            name: field_namer.unique(pf.name),
            presence: upgraded_presence,
          })
        }
      None =>
        if payload_ref_names.length() == 1 && fields.is_empty() {
          non_record_parent = Some(parent_name)
        } else {
          self.diags.unsupported(
            "W-allOf-non-record",
            pointer,
            "allOf parent \"\{parent_name}\" is not a record; fields not merged",
          )
        }
    }
  }
  match non_record_parent {
    Some(parent_name) =>
      return Some(
        Alias({
          name: mb_name,
          target: if nullable {
            make_optional(Named(parent_name))
          } else {
            Named(parent_name)
          },
          docs: merged_docs,
          example: merged_example,
          deprecated: merged_deprecated,
          source,
        }),
      )
    None => ()
  }
  if nullable {
    let inner_name = self.type_namer.unique_type(mb_name + "Value")
    self.add_def(
      Record({
        name: inner_name,
        fields,
        docs: merged_docs,
        example: None,
        deprecated: merged_deprecated,
        source,
      }),
    )
    return Some(
      Alias({
        name: mb_name,
        target: FieldType::Optional(Named(inner_name)),
        docs: merged_docs,
        example: merged_example,
        deprecated: merged_deprecated,
        source,
      }),
    )
  }
  Some(
    Record({
      name: mb_name,
      fields,
      docs: merged_docs,
      example: merged_example,
      deprecated: merged_deprecated,
      source,
    }),
  )
}

///|
/// The fields of a named record, unwrapping alias chains up to 32 hops.
fn IrBuilder::unwrapped_record(
  self : IrBuilder,
  name : String,
) -> Array[FieldIR]? {
  let mut current = name
  let mut hops = 0
  while hops <= 32 {
    match self.types.get(current) {
      Some(Record(data)) => return Some(data.fields)
      Some(Alias(alias_)) =>
        match alias_.target {
          Named(inner) | Optional(Named(inner)) => {
            current = inner
            hops += 1
            continue
          }
          _ => return None
        }
      _ => return None
    }
  }
  None
}