///|
fn value_kind_name(v : Value) -> String {
  match v {
    Top => "_"
    Bottom(_) => "_|_"
    Null => "null"
    BoolKind | Bool(_) => "bool"
    NumKind(b) => b.kind.format()
    Int(_) => "int"
    Float(_) => "float"
    StringKind(_, _) | String(_) => "string"
    BytesKind(_) | Bytes(_) => "bytes"
    Struct(_) => "struct"
    List(_) => "list"
    Disjunction(_) => "disjunction"
    Constrained(inner, _) => value_kind_name(inner)
  }
}

///|
fn merge_field_constraint(
  a : @syntax.FieldConstraint,
  b : @syntax.FieldConstraint,
) -> @syntax.FieldConstraint {
  match (a, b) {
    (Normal, _) | (_, Normal) => Normal
    (Required, _) | (_, Required) => Required
    (Optional, Optional) => Optional
  }
}

///|
fn key_unified_matches(
  val : Value,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Result[Bool, CueError] {
  match val {
    Bottom(errs) =>
      match first_resource_limit_error(errs) {
        Some(limit_err) => Err(limit_err)
        None => Ok(false)
      }
    Constrained(inner, cs) => {
      match key_unified_matches(inner, budget, validator?) {
        Err(e) => return Err(e)
        Ok(false) => return Ok(false)
        Ok(true) => ()
      }
      match validate_constraints_value(inner, cs, budget, validator?) {
        Ok(_) => Ok(true)
        Err(errs) =>
          match first_resource_limit_error(errs) {
            Some(limit_err) => Err(limit_err)
            None => Ok(false)
          }
      }
    }
    Disjunction(d) => {
      for item in d.items {
        match key_unified_matches(item.value, budget, validator?) {
          Err(e) => return Err(e)
          Ok(true) => return Ok(true)
          Ok(false) => ()
        }
      }
      Ok(false)
    }
    _ => Ok(true)
  }
}

///|
fn key_matches(
  key_constraint : Value,
  name : String,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Result[Bool, CueError] {
  let u = unify(String(name), key_constraint, budget, validator?)
  key_unified_matches(u, budget, validator?)
}

///|
fn sorted_strings_contain(sorted : Array[String], target : String) -> Bool {
  let mut lo = 0
  let mut hi = sorted.length()
  while lo < hi {
    let mid = lo + (hi - lo) / 2
    let cmp = sorted[mid].compare(target)
    if cmp == 0 {
      return true
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid
    }
  }
  false
}

///|
fn field_allowed_by_rule(
  name : String,
  rule : AllowedSet,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Result[Bool, CueError] {
  if rule.allow_all || sorted_strings_contain(rule.fields, name) {
    return Ok(true)
  }
  for pat_key in rule.patterns {
    match key_matches(pat_key, name, budget, validator?) {
      Err(e) => return Err(e)
      Ok(true) => return Ok(true)
      Ok(false) => ()
    }
  }
  Ok(false)
}

///|
fn is_sorted_strings(arr : Array[String]) -> Bool {
  for i in 1.. 0 {
      return false
    }
  }
  true
}

///|
fn check_struct_closedness_normalized(
  s : StructValue,
  rules : Array[AllowedSet],
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Value {
  if rules.is_empty() {
    return Struct(s)
  }
  let raw_errs : Array[CueError] = []
  for f in s.fields {
    match budget.consume_step() {
      Err(e) => return bottom_err(ResourceLimit, e.message())
      Ok(_) => ()
    }
    if f.kind != Regular || f.constraint == Optional {
      continue
    }
    for rule in rules {
      match budget.consume_step() {
        Err(e) => return bottom_err(ResourceLimit, e.message())
        Ok(_) => ()
      }
      match field_allowed_by_rule(f.name, rule, budget, validator?) {
        Err(limit_err) => return Bottom([limit_err])
        Ok(true) => ()
        Ok(false) => {
          let err = CueError::new(
            FieldNotAllowed,
            "field `\{f.name}` not allowed in closed struct",
          ).with_prefix(f.name)
          raw_errs.push(err)
          break
        }
      }
    }
  }
  if raw_errs.is_empty() {
    Struct(s)
  } else {
    Bottom(dedup_sorted_errors(raw_errs))
  }
}

///|
/// Validates that every regular non-optional field in `s` is permitted by every
/// `AllowedSet` in `s.closed_rules` (hidden fields and definitions are exempt).
/// Handles unsorted `AllowedSet.fields` safely by sorting unsorted rules at most once.
pub fn check_struct_closedness(
  s : StructValue,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Value {
  if s.closed_rules.is_empty() {
    return Struct(s)
  }
  let mut first_unsorted = -1
  for i, rule in s.closed_rules {
    if !rule.allow_all && !is_sorted_strings(rule.fields) {
      first_unsorted = i
      break
    }
  }
  if first_unsorted < 0 {
    return check_struct_closedness_normalized(
      s,
      s.closed_rules,
      budget,
      validator?,
    )
  }
  let prepared_rules : Array[AllowedSet] = []
  for i in 0.. Int32? {
  for i, f in fields {
    if f.kind == kind && f.name == name {
      return Some(i)
    }
  }
  None
}

///|
fn unify_structs(
  a : StructValue,
  b : StructValue,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Value {
  let merged_fields : Array[StructField] = []
  for fa in a.fields {
    merged_fields.push(fa)
  }
  for fb in b.fields {
    match find_field_index(merged_fields, fb.kind, fb.name) {
      Some(idx) => {
        let fa = merged_fields[idx]
        let merged_constraint = merge_field_constraint(
          fa.constraint,
          fb.constraint,
        )
        let unified_val = if merged_constraint == Optional {
          let (uv, trapped) = budget.with_matcher_fatal_trap(fn() {
            unify(fa.value, fb.value, budget, validator?)
          })
          budget.mark_deferred_matcher_fatal(uv, trapped)
        } else {
          unify(fa.value, fb.value, budget, validator?)
        }
        match unified_val {
          Bottom(errs) =>
            match first_resource_limit_error(errs) {
              Some(limit_err) => return Bottom([limit_err])
              None => ()
            }
          _ => ()
        }
        merged_fields[idx] = {
          name: fa.name,
          kind: fa.kind,
          constraint: merged_constraint,
          value: unified_val,
        }
      }
      None => merged_fields.push(fb)
    }
  }
  let all_patterns : Array[PatternConstraint] = []
  for p in a.patterns {
    all_patterns.push(p)
  }
  for p in b.patterns {
    all_patterns.push(p)
  }
  let all_rules : Array[AllowedSet] = []
  for r in a.closed_rules {
    all_rules.push(r)
  }
  for r in b.closed_rules {
    all_rules.push(r)
  }
  let all_deferred : Array[Int32] = []
  for id in a.deferred_ids {
    all_deferred.push(id)
  }
  for id in b.deferred_ids {
    all_deferred.push(id)
  }
  let dedup_pats = match
    dedup_patterns_preserving_deferred(all_patterns, budget) {
    Ok(ps) => ps
    Err(rl) => return Bottom([rl])
  }
  let norm = StructValue::normalized(
    merged_fields,
    dedup_pats,
    all_rules,
    a.allow_ellipsis && b.allow_ellipsis,
    deferred_ids=all_deferred,
  )
  let final_fields = norm.fields.copy()
  for i, f in final_fields {
    if f.kind != Regular {
      continue
    }
    let mut cur_val = f.value
    for pat in norm.patterns {
      match key_matches(pat.key_constraint, f.name, budget, validator?) {
        Err(limit_err) => return Bottom([limit_err])
        Ok(true) => {
          cur_val = if f.constraint == Optional {
            let (uv, trapped) = budget.with_matcher_fatal_trap(fn() {
              unify(cur_val, pat.value_constraint, budget, validator?)
            })
            budget.mark_deferred_matcher_fatal(uv, trapped)
          } else {
            unify(cur_val, pat.value_constraint, budget, validator?)
          }
          match cur_val {
            Bottom(errs) =>
              match first_resource_limit_error(errs) {
                Some(limit_err) => return Bottom([limit_err])
                None => ()
              }
            _ => ()
          }
        }
        Ok(false) => ()
      }
    }
    final_fields[i] = { ..f, value: cur_val, }
  }
  let result_struct : StructValue = { ..norm, fields: final_fields, }
  let raw_errs : Array[CueError] = []
  let mut saw_bottom = false
  for f in result_struct.fields {
    if f.constraint == Optional {
      continue
    }
    match f.value {
      Bottom(ferrs) => {
        match budget.replay_deferred_matcher_fatal_prefixed(ferrs, f.name) {
          Some(limit_err) => return Bottom([limit_err])
          None => ()
        }
        saw_bottom = true
        for err in normalize_bottom_errors(ferrs) {
          raw_errs.push(err.with_prefix(f.name))
        }
      }
      _ => ()
    }
  }
  match
    check_struct_closedness_normalized(
      result_struct,
      result_struct.closed_rules,
      budget,
      validator?,
    ) {
    Bottom(cerrs) => {
      match first_resource_limit_error(cerrs) {
        Some(limit_err) => return Bottom([limit_err])
        None => ()
      }
      saw_bottom = true
      for err in normalize_bottom_errors(cerrs) {
        raw_errs.push(err)
      }
    }
    _ => ()
  }
  if saw_bottom {
    Bottom(dedup_sorted_errors(raw_errs))
  } else {
    Struct(result_struct)
  }
}

///|
fn unify_lists(
  a : ListValue,
  b : ListValue,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Value {
  let na = a.elems.length()
  let nb = b.elems.length()
  let max_len = if na >= nb { na } else { nb }
  let elems : Array[Value] = []
  let raw_errs : Array[CueError] = []
  let mut saw_bottom = false
  for i in 0.. unify(a.elems[i], t, budget, validator?)
        None => {
          let (lo, hi) = if na <= nb { (na, nb) } else { (nb, na) }
          return bottom_err(
            ValueConflict,
            "incompatible list lengths: \{lo} and \{hi}",
          )
        }
      }
    } else {
      match a.tail {
        Some(t) => unify(t, b.elems[i], budget, validator?)
        None => {
          let (lo, hi) = if na <= nb { (na, nb) } else { (nb, na) }
          return bottom_err(
            ValueConflict,
            "incompatible list lengths: \{lo} and \{hi}",
          )
        }
      }
    }
    match elem {
      Bottom(eerrs) => {
        match first_resource_limit_error(eerrs) {
          Some(limit_err) => return Bottom([limit_err])
          None => ()
        }
        let seg = i.to_string()
        match budget.replay_deferred_matcher_fatal_prefixed(eerrs, seg) {
          Some(limit_err) => return Bottom([limit_err])
          None => ()
        }
        saw_bottom = true
        for err in normalize_bottom_errors(eerrs) {
          raw_errs.push(err.with_prefix(seg))
        }
      }
      _ => ()
    }
    elems.push(elem)
  }
  if saw_bottom {
    return Bottom(dedup_sorted_errors(raw_errs))
  }
  let tail = match (a.tail, b.tail) {
    (Some(ta), Some(tb)) => {
      let (ut, trapped) = budget.with_matcher_fatal_trap(fn() {
        unify(ta, tb, budget, validator?)
      })
      let marked = budget.mark_deferred_matcher_fatal(ut, trapped)
      match marked {
        Bottom(terrs) =>
          match first_resource_limit_error(terrs) {
            Some(limit_err) => return Bottom([limit_err])
            None => Some(marked)
          }
        _ => Some(marked)
      }
    }
    _ => None
  }
  List({ elems, tail, })
}

///|
fn unify_num_concrete_with_bounds(nb : NumBounds, nv : NumValue) -> Value {
  match nb.matches(nv) {
    Ok(_) =>
      match nv {
        Int(n) => Int(n)
        Float(d) => Float(d)
      }
    Err(msg) => {
      let kind = match (nb.kind, nv) {
        (Int, Float(_)) | (Float, Int(_)) => TypeConflict
        _ => BoundsConflict
      }
      bottom_err(kind, msg)
    }
  }
}

///|
fn unify_string_with_kind(
  sb : StringBounds,
  rc : RegexConstraints,
  s : String,
) -> Value {
  match sb.matches(s) {
    Err(msg) => return bottom_err(BoundsConflict, msg)
    Ok(_) => ()
  }
  match rc.matches(s) {
    Err(msg) => return bottom_err(RegexConflict, msg)
    Ok(_) => ()
  }
  String(s)
}

///|
/// Lattice meet (`&`) on two CUE values.
///
/// Satisfies commutativity, associativity, idempotence, `Top` identity, and
/// `Bottom` absorption while enforcing `budget` step, depth, and branch limits.
pub fn unify(
  a : Value,
  b : Value,
  budget : EvalBudget,
  validator? : (String, String, Array[Value], Value, EvalBudget) -> BuiltinValidationResult,
) -> Value {
  match budget.consume_step() {
    Err(e) => return bottom_err(ResourceLimit, e.message())
    Ok(_) => ()
  }
  match budget.enter_depth() {
    Err(e) => return bottom_err(ResourceLimit, e.message())
    Ok(_) => ()
  }
  let res = match (a, b) {
    (Bottom(ea), Bottom(eb)) => {
      let merged = merge_errors(
        normalize_bottom_errors(ea),
        normalize_bottom_errors(eb),
      )
      budget.propagate_deferred_matcher_fatal_pair(ea, eb, merged)
      Bottom(merged)
    }
    (Bottom(e), _) | (_, Bottom(e)) => Bottom(normalize_bottom_errors(e))
    (Top, x) | (x, Top) => x
    (Disjunction(_), _) | (_, Disjunction(_)) =>
      unify_disjunction(a, b, budget, validator?)
    (Constrained(va, ca), Constrained(vb, cb)) => {
      let combined : Array[ValidatorConstraint] = []
      for c in ca {
        combined.push(c)
      }
      for c in cb {
        combined.push(c)
      }
      make_constrained(unify(va, vb, budget, validator?), combined, budget)
    }
    (Constrained(va, ca), other) =>
      make_constrained(unify(va, other, budget, validator?), ca, budget)
    (other, Constrained(vb, cb)) =>
      make_constrained(unify(other, vb, budget, validator?), cb, budget)
    (Null, Null) => Null
    (BoolKind, BoolKind) => BoolKind
    (BoolKind, Bool(v)) | (Bool(v), BoolKind) => Bool(v)
    (Bool(x), Bool(y)) =>
      if x == y {
        Bool(x)
      } else {
        bottom_err(ValueConflict, "conflicting values false and true")
      }
    (NumKind(ba), NumKind(bb)) =>
      match ba.unify(bb) {
        Ok(u) => NumKind(u)
        Err(msg) => {
          let kind = match ba.kind.unify(bb.kind) {
            None => TypeConflict
            Some(_) => BoundsConflict
          }
          bottom_err(kind, msg)
        }
      }
    (NumKind(nb), Int(n)) | (Int(n), NumKind(nb)) =>
      unify_num_concrete_with_bounds(nb, NumValue::int(n))
    (NumKind(nb), Float(d)) | (Float(d), NumKind(nb)) =>
      unify_num_concrete_with_bounds(nb, NumValue::Float(d))
    (Int(x), Int(y)) =>
      if x == y {
        Int(x)
      } else {
        let (lo, hi) = if x <= y { (x, y) } else { (y, x) }
        bottom_err(ValueConflict, "conflicting values \{lo} and \{hi}")
      }
    (Float(x), Float(y)) =>
      if x == y {
        Float(x)
      } else {
        let (lo, hi) = if x.compare(y) <= 0 { (x, y) } else { (y, x) }
        bottom_err(
          ValueConflict,
          "conflicting values \{lo.format_cue()} and \{hi.format_cue()}",
        )
      }
    (StringKind(ba, ra), StringKind(bb, rb)) =>
      match ba.unify(bb) {
        Err(msg) => bottom_err(BoundsConflict, msg)
        Ok(bu) =>
          match ra.unify(rb) {
            Err(msg) => bottom_err(RegexConflict, msg)
            Ok(ru) => StringKind(bu, ru)
          }
      }
    (StringKind(sb, rc), String(s)) | (String(s), StringKind(sb, rc)) =>
      unify_string_with_kind(sb, rc, s)
    (String(x), String(y)) =>
      if x == y {
        String(x)
      } else {
        let (lo, hi) = if compare_cue_string(x, y) <= 0 {
          (x, y)
        } else {
          (y, x)
        }
        bottom_err(
          ValueConflict,
          "conflicting values \{format_cue_string_lit(lo)} and \{format_cue_string_lit(hi)}",
        )
      }
    (BytesKind(ba), BytesKind(bb)) =>
      match ba.unify(bb) {
        Ok(bu) => BytesKind(bu)
        Err(msg) => bottom_err(BoundsConflict, msg)
      }
    (BytesKind(bb), Bytes(bs)) | (Bytes(bs), BytesKind(bb)) =>
      match bb.matches(bs) {
        Ok(_) => Bytes(bs)
        Err(msg) => bottom_err(BoundsConflict, msg)
      }
    (Bytes(x), Bytes(y)) =>
      if x == y {
        Bytes(x)
      } else {
        let (lo, hi) = if compare_cue_bytes(x, y) <= 0 {
          (x, y)
        } else {
          (y, x)
        }
        bottom_err(
          ValueConflict,
          "conflicting values \{format_cue_bytes_lit(lo)} and \{format_cue_bytes_lit(hi)}",
        )
      }
    (Struct(sa), Struct(sb)) => unify_structs(sa, sb, budget, validator?)
    (List(la), List(lb)) => unify_lists(la, lb, budget, validator?)
    _ => {
      let ka = value_kind_name(a)
      let kb = value_kind_name(b)
      let (first, second) = if ka <= kb { (ka, kb) } else { (kb, ka) }
      bottom_err(TypeConflict, "conflicting types \{first} and \{second}")
    }
  }
  budget.leave_depth()
  res
}