///|
/// CUE predeclared types, global builtins (`len`, `close`, `and`, `or`, `div`, `mod`, `quo`, `rem`),
/// and core standard library packages (`strings`, `list`, `math`).

///|
/// Resolve a predeclared CUE type identifier (including bounded integer types like `uint16`).
pub fn lookup_predeclared_type(name : String) -> Value? {
  match name {
    "_" => Some(VTop)
    "null" => Some(VNull)
    "bool" => Some(VBasic(BoolKind))
    "int" => Some(VBasic(IntKind))
    "float" => Some(VBasic(FloatKind))
    "number" => Some(VBasic(NumberKind))
    "string" => Some(VBasic(StringKind))
    "bytes" => Some(VBasic(BytesKind))
    "uint" =>
      Some(unify(VBasic(IntKind), VBound({ op: BGte, scalar: SInt(0L), })))
    "uint8" | "byte" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(0L), }),
            VBound({ op: BLte, scalar: SInt(255L), }),
          ),
        ),
      )
    "uint16" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(0L), }),
            VBound({ op: BLte, scalar: SInt(65535L), }),
          ),
        ),
      )
    "uint32" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(0L), }),
            VBound({ op: BLte, scalar: SInt(4294967295L), }),
          ),
        ),
      )
    "int8" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(-128L), }),
            VBound({ op: BLte, scalar: SInt(127L), }),
          ),
        ),
      )
    "int16" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(-32768L), }),
            VBound({ op: BLte, scalar: SInt(32767L), }),
          ),
        ),
      )
    "int32" | "rune" =>
      Some(
        unify(
          VBasic(IntKind),
          unify(
            VBound({ op: BGte, scalar: SInt(-2147483648L), }),
            VBound({ op: BLte, scalar: SInt(2147483647L), }),
          ),
        ),
      )
    "int64" => Some(VBasic(IntKind))
    "uint64" =>
      Some(unify(VBasic(IntKind), VBound({ op: BGte, scalar: SInt(0L), })))
    "float32" | "float64" => Some(VBasic(FloatKind))
    _ => None
  }
}

///|
/// Euclidean integer division (`div`) and modulo (`mod`) per CUE spec:
/// `b > 0 => 0 <= a mod b < b`, `b < 0 => 0 <= a mod b < |b|`.
pub fn cue_int_div(a : Int64, b : Int64) -> (Int64, Int64) raise CueError {
  if b == 0L {
    raise CueError::new(EvalError, "division by zero")
  }
  let mut q = a / b
  let mut r = a % b
  if r < 0L {
    if b > 0L {
      r = r + b
      q = q - 1L
    } else {
      r = r - b
      q = q + 1L
    }
  }
  (q, r)
}

///|
/// Truncated integer division (`quo`) and remainder (`rem`) per CUE spec.
pub fn cue_int_quo(a : Int64, b : Int64) -> (Int64, Int64) raise CueError {
  if b == 0L {
    raise CueError::new(EvalError, "division by zero")
  }
  (a / b, a % b)
}

///|
/// Recursively mark a struct (and its nested structs) as closed (`close(...)`).
pub fn close_value(v : Value) -> Value {
  match v {
    VStruct(s) => {
      let next_fields : Array[StructField] = []
      for f in s.fields {
        next_fields.push({ ..f, value: close_value(f.value), })
      }
      VStruct({ ..s, fields: next_fields, is_closed: true, })
    }
    VDisjunction(ds) => {
      let next : Array[Disjunct] = []
      for d in ds {
        next.push({ value: close_value(d.value), is_default: d.is_default, })
      }
      VDisjunction(next)
    }
    _ => v
  }
}

///|
/// Evaluate global CUE builtin calls: `len`, `close`, `and`, `or`, `div`, `mod`, `quo`, `rem`.
pub fn eval_global_builtin(
  name : String,
  args : Array[Value],
  span : Span,
) -> Value {
  match name {
    "len" => {
      if args.length() != 1 {
        return Value::bottom(
          EvalError,
          "len() expects 1 argument, got \{args.length()}",
          span=Some(span),
        )
      }
      match resolve_default_shallow(args[0]) {
        VString(s) => VInt(string_utf8_len(s).to_int64())
        VBytes(b) => VInt(b.length().to_int64())
        VList(l) =>
          if l.open_tail is Some(_) {
            Value::bottom(
              IncompleteError,
              "len() called on open list",
              span=Some(span),
            )
          } else {
            VInt(l.elems.length().to_int64())
          }
        VStruct(s) => {
          let mut count = 0L
          for f in s.fields {
            if !f.is_definition && !f.is_hidden && f.constraint == Regular {
              count += 1L
            }
          }
          VInt(count)
        }
        VBottom(_) as b => b
        other =>
          Value::bottom(
            EvalError,
            "invalid argument to len(): \{format_value(other)}",
            span=Some(span),
          )
      }
    }
    "close" => {
      if args.length() != 1 {
        return Value::bottom(
          EvalError,
          "close() expects 1 argument, got \{args.length()}",
          span=Some(span),
        )
      }
      close_value(args[0])
    }
    "and" => {
      if args.length() != 1 {
        return Value::bottom(
          EvalError,
          "and() expects 1 list argument, got \{args.length()}",
          span=Some(span),
        )
      }
      match resolve_default_shallow(args[0]) {
        VList(l) => {
          let mut acc : Value = VTop
          for elem in l.elems {
            acc = unify(acc, elem)
          }
          acc
        }
        VBottom(_) as b => b
        other =>
          Value::bottom(
            EvalError,
            "and() expects a list, got \{format_value(other)}",
            span=Some(span),
          )
      }
    }
    "or" => {
      if args.length() != 1 {
        return Value::bottom(
          EvalError,
          "or() expects 1 list argument, got \{args.length()}",
          span=Some(span),
        )
      }
      match resolve_default_shallow(args[0]) {
        VList(l) => {
          if l.elems.is_empty() {
            return Value::bottom(
              ConflictError,
              "or() of empty list is bottom",
              span=Some(span),
            )
          }
          let ds : Array[Disjunct] = []
          for elem in l.elems {
            ds.push({ value: elem, is_default: false, })
          }
          make_disjunction(ds)
        }
        VBottom(_) as b => b
        other =>
          Value::bottom(
            EvalError,
            "or() expects a list, got \{format_value(other)}",
            span=Some(span),
          )
      }
    }
    "div" | "mod" | "quo" | "rem" => {
      if args.length() != 2 {
        return Value::bottom(
          EvalError,
          "\{name}() expects 2 arguments, got \{args.length()}",
          span=Some(span),
        )
      }
      match
        (resolve_default_shallow(args[0]), resolve_default_shallow(args[1])) {
        (VInt(a), VInt(b)) => {
          let res : Result[(Int64, Int64), CueError] = Ok(
            if name == "div" || name == "mod" {
              cue_int_div(a, b)
            } else {
              cue_int_quo(a, b)
            },
          ) catch {
            e => Err(e)
          }
          match res {
            Ok((q, r)) =>
              if name == "div" || name == "quo" {
                VInt(q)
              } else {
                VInt(r)
              }
            Err(e) => VBottom([e])
          }
        }
        (VBottom(_) as b, _) | (_, VBottom(_) as b) => b
        _ =>
          Value::bottom(
            EvalError,
            "\{name}() expects two integer arguments",
            span=Some(span),
          )
      }
    }
    _ =>
      Value::bottom(
        EvalError,
        "unknown builtin function '\{name}'",
        span=Some(span),
      )
  }
}

///|
/// Evaluate CUE standard library package calls (`strings.*`, `list.*`, `math.*`).
pub fn eval_stdlib_call(
  pkg_path : String,
  func_name : String,
  args : Array[Value],
  span : Span,
) -> Value {
  match pkg_path {
    "strings" => eval_strings_pkg(func_name, args, span)
    "list" => eval_list_pkg(func_name, args, span)
    "math" => eval_math_pkg(func_name, args, span)
    _ =>
      Value::bottom(
        EvalError,
        "unsupported standard library package '\{pkg_path}'",
        span=Some(span),
      )
  }
}

///|
fn eval_strings_pkg(
  func_name : String,
  args : Array[Value],
  span : Span,
) -> Value {
  match func_name {
    "HasPrefix" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VString(p)) => VBool(s.has_prefix(p))
            _ =>
              Value::bottom(
                EvalError,
                "strings.HasPrefix expects (string, string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.HasPrefix expects 2 arguments",
            span=Some(span),
          )
      }
    "HasSuffix" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VString(p)) => VBool(s.has_suffix(p))
            _ =>
              Value::bottom(
                EvalError,
                "strings.HasSuffix expects (string, string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.HasSuffix expects 2 arguments",
            span=Some(span),
          )
      }
    "Contains" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VString(sub)) => VBool(s.contains(sub))
            _ =>
              Value::bottom(
                EvalError,
                "strings.Contains expects (string, string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.Contains expects 2 arguments",
            span=Some(span),
          )
      }
    "ToLower" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VString(s) => VString(s.to_lower())
            _ =>
              Value::bottom(
                EvalError,
                "strings.ToLower expects (string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.ToLower expects 1 argument",
            span=Some(span),
          )
      }
    "ToUpper" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VString(s) => VString(s.to_upper())
            _ =>
              Value::bottom(
                EvalError,
                "strings.ToUpper expects (string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.ToUpper expects 1 argument",
            span=Some(span),
          )
      }
    "TrimSpace" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VString(s) => VString(s.trim().to_owned())
            _ =>
              Value::bottom(
                EvalError,
                "strings.TrimSpace expects (string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.TrimSpace expects 1 argument",
            span=Some(span),
          )
      }
    "Split" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VString(sep)) => {
              let elems : Array[Value] = []
              for part in s.split(sep) {
                elems.push(VString(part.to_owned()))
              }
              VList({ elems, open_tail: None, })
            }
            _ =>
              Value::bottom(
                EvalError,
                "strings.Split expects (string, string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.Split expects 2 arguments",
            span=Some(span),
          )
      }
    "Join" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VList(l), VString(sep)) => {
              let buf = StringBuilder()
              for i = 0; i < l.elems.length(); i = i + 1 {
                if i > 0 {
                  buf.write_string(sep)
                }
                match resolve_default_shallow(l.elems[i]) {
                  VString(s) => buf.write_string(s)
                  _ =>
                    return Value::bottom(
                      EvalError,
                      "strings.Join list elements must be strings",
                      span=Some(span),
                    )
                }
              }
              VString(buf.to_string())
            }
            _ =>
              Value::bottom(
                EvalError,
                "strings.Join expects ([...string], string)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.Join expects 2 arguments",
            span=Some(span),
          )
      }
    "MinRunes" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VInt(min_n)) =>
              VBool(s.to_array().length().to_int64() >= min_n)
            _ =>
              Value::bottom(
                EvalError,
                "strings.MinRunes expects (string, int)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.MinRunes expects 2 arguments",
            span=Some(span),
          )
      }
    "MaxRunes" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VString(s), VInt(max_n)) =>
              VBool(s.to_array().length().to_int64() <= max_n)
            _ =>
              Value::bottom(
                EvalError,
                "strings.MaxRunes expects (string, int)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "strings.MaxRunes expects 2 arguments",
            span=Some(span),
          )
      }
    _ =>
      Value::bottom(
        EvalError,
        "unknown function 'strings.\{func_name}'",
        span=Some(span),
      )
  }
}

///|
fn eval_list_pkg(func_name : String, args : Array[Value], span : Span) -> Value {
  match func_name {
    "Contains" =>
      match args {
        [a, b] =>
          match resolve_default_shallow(a) {
            VList(l) => {
              let target = resolve_default_shallow(b)
              for elem in l.elems {
                if resolve_default_shallow(elem) == target {
                  return VBool(true)
                }
              }
              VBool(false)
            }
            _ =>
              Value::bottom(
                EvalError,
                "list.Contains expects (list, value)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.Contains expects 2 arguments",
            span=Some(span),
          )
      }
    "UniqueItems" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VList(l) => {
              for i = 0; i < l.elems.length(); i = i + 1 {
                let ei = resolve_default_shallow(l.elems[i])
                for j = i + 1; j < l.elems.length(); j = j + 1 {
                  if ei == resolve_default_shallow(l.elems[j]) {
                    return VBool(false)
                  }
                }
              }
              VBool(true)
            }
            _ =>
              Value::bottom(
                EvalError,
                "list.UniqueItems expects (list)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.UniqueItems expects 1 argument",
            span=Some(span),
          )
      }
    "MinItems" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VList(l), VInt(n)) => VBool(l.elems.length().to_int64() >= n)
            _ =>
              Value::bottom(
                EvalError,
                "list.MinItems expects (list, int)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.MinItems expects 2 arguments",
            span=Some(span),
          )
      }
    "MaxItems" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VList(l), VInt(n)) => VBool(l.elems.length().to_int64() <= n)
            _ =>
              Value::bottom(
                EvalError,
                "list.MaxItems expects (list, int)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.MaxItems expects 2 arguments",
            span=Some(span),
          )
      }
    "Concat" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VList(outer) => {
              let out : Array[Value] = []
              for item in outer.elems {
                match resolve_default_shallow(item) {
                  VList(inner) =>
                    for x in inner.elems {
                      out.push(x)
                    }
                  _ =>
                    return Value::bottom(
                      EvalError,
                      "list.Concat expects a list of lists",
                      span=Some(span),
                    )
                }
              }
              VList({ elems: out, open_tail: None, })
            }
            _ =>
              Value::bottom(
                EvalError,
                "list.Concat expects (list)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.Concat expects 1 argument",
            span=Some(span),
          )
      }
    "Repeat" =>
      match args {
        [a, b] =>
          match (resolve_default_shallow(a), resolve_default_shallow(b)) {
            (VList(l), VInt(n)) => {
              if n < 0L {
                return Value::bottom(
                  EvalError,
                  "list.Repeat count must be non-negative",
                  span=Some(span),
                )
              }
              let out : Array[Value] = []
              for _i = 0L; _i < n; _i = _i + 1L {
                for e in l.elems {
                  out.push(e)
                }
              }
              VList({ elems: out, open_tail: None, })
            }
            _ =>
              Value::bottom(
                EvalError,
                "list.Repeat expects (list, int)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.Repeat expects 2 arguments",
            span=Some(span),
          )
      }
    "Sum" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VList(l) => {
              let mut is_float = false
              let mut isum : Int64 = 0L
              let mut fsum : Double = 0.0
              for item in l.elems {
                match resolve_default_shallow(item) {
                  VInt(i) => {
                    isum += i
                    fsum += i.to_double()
                  }
                  VFloat(f) => {
                    is_float = true
                    fsum += f
                  }
                  _ =>
                    return Value::bottom(
                      EvalError,
                      "list.Sum expects list of numbers",
                      span=Some(span),
                    )
                }
              }
              if is_float {
                VFloat(fsum)
              } else {
                VInt(isum)
              }
            }
            _ =>
              Value::bottom(
                EvalError,
                "list.Sum expects (list)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "list.Sum expects 1 argument",
            span=Some(span),
          )
      }
    _ =>
      Value::bottom(
        EvalError,
        "unknown function 'list.\{func_name}'",
        span=Some(span),
      )
  }
}

///|
fn eval_math_pkg(func_name : String, args : Array[Value], span : Span) -> Value {
  match func_name {
    "Abs" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VInt(i) => VInt(if i < 0L { -i } else { i })
            VFloat(f) => VFloat(if f < 0.0 { -f } else { f })
            _ =>
              Value::bottom(
                EvalError,
                "math.Abs expects (number)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "math.Abs expects 1 argument",
            span=Some(span),
          )
      }
    "Floor" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VInt(i) => VFloat(i.to_double())
            VFloat(f) => VFloat(f.floor())
            _ =>
              Value::bottom(
                EvalError,
                "math.Floor expects (number)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "math.Floor expects 1 argument",
            span=Some(span),
          )
      }
    "Ceil" =>
      match args {
        [a] =>
          match resolve_default_shallow(a) {
            VInt(i) => VFloat(i.to_double())
            VFloat(f) => VFloat(f.ceil())
            _ =>
              Value::bottom(
                EvalError,
                "math.Ceil expects (number)",
                span=Some(span),
              )
          }
        _ =>
          Value::bottom(
            EvalError,
            "math.Ceil expects 1 argument",
            span=Some(span),
          )
      }
    _ =>
      Value::bottom(
        EvalError,
        "unknown function 'math.\{func_name}'",
        span=Some(span),
      )
  }
}

///|
/// Resolve a single default choice from a disjunction (used by concrete ops and export).
pub fn resolve_default_shallow(val : Value) -> Value {
  match val {
    VDisjunction(ds) => {
      let mut found : Value? = None
      let mut count = 0
      for d in ds {
        if d.is_default {
          found = Some(d.value)
          count += 1
        }
      }
      if count == 1 {
        resolve_default_shallow(found.unwrap())
      } else {
        val
      }
    }
    _ => val
  }
}

///|
fn string_utf8_len(s : String) -> Int32 {
  let mut n = 0
  for ch in s {
    let cp = ch.to_int()
    if cp <= 0x7F {
      n += 1
    } else if cp <= 0x7FF {
      n += 2
    } else if cp <= 0xFFFF {
      n += 3
    } else {
      n += 4
    }
  }
  n
}