///|
fn single_domain_kind(domain : NonNullDomain) -> String? {
  match domain {
    Scalar(Integers(_)) => Some("integer")
    Scalar(Numbers) => Some("number")
    Scalar(Strings(_)) => Some("string")
    Scalar(Booleans(_)) => Some("boolean")
    Record(_) => Some("object")
    Sequence(_) => Some("array")
    AnyNonNull | NoNonNull | Alternatives(_) => None
  }
}

///|
fn add_alternative(
  groups : Map[String, Array[NonNullDomain]],
  domain : NonNullDomain,
) -> Unit {
  if single_domain_kind(domain) is Some(kind) && has_non_null_value(domain) {
    match groups.get(kind) {
      None => groups[kind] = [domain]
      Some(group) => group.push(domain)
    }
  }
}

///|
fn combine_alternatives(
  groups : Map[String, Array[NonNullDomain]],
  universal : Int32,
  keyword : String,
) -> NonNullDomain raise SchemaIssue {
  let exclusive = keyword == "oneOf"
  if universal > 0 {
    if exclusive && (universal > 1 || !groups.is_empty()) {
      raise Unsupported(
        "oneOf overlaps a branch accepting every non-null value",
      )
    }
    return AnyNonNull
  }
  if groups.contains("number") && groups.contains("integer") {
    if exclusive {
      raise Unsupported("oneOf overlaps integer and number branches")
    }
    groups.remove("integer")
  }
  let choices : Map[String, NonNullDomain] = Map([])
  for kind, group in groups {
    match group {
      [domain] => choices[kind] = domain
      [first, ..] if !exclusive && kind == "number" => choices[kind] = first
      _ =>
        raise Unsupported("\{keyword} has multiple inhabited \{kind} branches")
    }
  }
  collapse_alternatives(choices)
}

///|
fn branch_for_kind(
  choices : Map[String, NonNullDomain],
  kind : String,
) -> NonNullDomain {
  match choices.get(kind) {
    Some(domain) => domain
    None if kind == "integer" => choices.get("number").unwrap_or(NoNonNull)
    None => NoNonNull
  }
}

///|
fn compile_type_filter(value : Json) -> Map[String, Unit] raise SchemaIssue {
  let entries = match value {
    String(_) => [value]
    Array(items) if !items.is_empty() => items
    _ => raise Unsupported("type must be a string or a nonempty type array")
  }
  let allowed : Map[String, Unit] = Map([])
  for entry in entries {
    match entry {
      String(
        "integer"
        | "number"
        | "string"
        | "boolean"
        | "object"
        | "array"
        | "null" as kind,
      ) => {
        if allowed.contains(kind) {
          raise Unsupported("type must contain unique type names")
        }
        allowed[kind] = ()
      }
      _ => raise Unsupported("unsupported type in a composed schema")
    }
  }
  if allowed.contains("number") {
    allowed.remove("integer")
  }
  allowed
}

///|
fn collapse_alternatives(choices : Map[String, NonNullDomain]) -> NonNullDomain {
  if choices.length() <= 1 {
    choices.values().next().unwrap_or(NoNonNull)
  } else {
    Alternatives(choices)
  }
}

///|
fn filter_branch_types(
  shape : CompiledSchema,
  allowed : Map[String, Unit]?,
  depth : Int32,
  work : Ref[Int32],
) -> CompiledSchema raise SchemaIssue {
  guard allowed is Some(allowed) else { return shape }
  let non_null = match shape.non_null {
    AnyNonNull => {
      let choices : Map[String, NonNullDomain] = Map([])
      for kind, _ in allowed {
        if kind != "null" {
          choices[kind] = compile_non_null(kind, Map([]), depth, work)
        }
      }
      collapse_alternatives(choices)
    }
    Alternatives(branches) => {
      let choices : Map[String, NonNullDomain] = Map([])
      for _, branch in branches {
        let domain = filter_single_domain(branch, allowed, depth, work)
        if single_domain_kind(domain) is Some(kind) {
          choices[kind] = domain
        }
      }
      collapse_alternatives(choices)
    }
    domain => filter_single_domain(domain, allowed, depth, work)
  }
  { non_null, accepts_null: shape.accepts_null && allowed.contains("null"), }
}

///|
fn filter_single_domain(
  domain : NonNullDomain,
  allowed : Map[String, Unit],
  depth : Int32,
  work : Ref[Int32],
) -> NonNullDomain raise SchemaIssue {
  match single_domain_kind(domain) {
    Some(kind) if allowed.contains(kind) => domain
    Some("integer") if allowed.contains("number") => domain
    Some("number") if allowed.contains("integer") =>
      compile_non_null("integer", Map([]), depth, work)
    _ => NoNonNull
  }
}

///|
fn compile_branch_composition(
  fields : Map[String, Json],
  branches : Json,
  keyword : String,
  depth : Int32,
  work : Ref[Int32],
) -> CompiledSchema raise SchemaIssue {
  for key, value in fields {
    if key != keyword && key != "type" {
      check_annotation(key, value)
    }
  }
  let allowed = match fields.get("type") {
    None => None
    Some(value) => Some(compile_type_filter(value))
  }
  let branches = nonempty_array(branches, keyword)
  if keyword == "allOf" {
    guard branches is [branch] else {
      raise Unsupported("non-integer allOf supports a single branch")
    }
    return filter_branch_types(
      compile_shape(branch, depth + 1, work),
      allowed,
      depth,
      work,
    )
  }
  let exclusive = keyword == "oneOf"
  let mut null_matches = 0
  let mut universal = 0
  let groups : Map[String, Array[NonNullDomain]] = Map([])
  spend_integer_work(work, branches.length())
  for branch in branches {
    let shape = filter_branch_types(
      compile_shape(branch, depth + 1, work),
      allowed,
      depth,
      work,
    )
    if shape.accepts_null {
      null_matches += 1
    }
    match shape.non_null {
      AnyNonNull => universal += 1
      Alternatives(inner) =>
        for _, domain in inner {
          add_alternative(groups, domain)
        }
      domain => add_alternative(groups, domain)
    }
  }
  let non_null = combine_alternatives(groups, universal, keyword)
  let accepts_null = if exclusive {
    null_matches == 1
  } else {
    null_matches > 0
  }
  { non_null, accepts_null, }
}