///|
/// CUE Value Lattice data types.
///
/// In CUE, types, constraints, defaults, and concrete values all inhabit a single
/// mathematical partial order (a meet-semilattice with top `_` and bottom `_|_`).

///|
#derive(Eq, Debug)
pub(all) enum BasicKind {
  NullKind
  BoolKind
  IntKind
  FloatKind
  NumberKind
  StringKind
  BytesKind
}

///|
pub impl Show for BasicKind with fn output(self, logger) {
  let s = match self {
    NullKind => "null"
    BoolKind => "bool"
    IntKind => "int"
    FloatKind => "float"
    NumberKind => "number"
    StringKind => "string"
    BytesKind => "bytes"
  }
  logger.write_string(s)
}

///|
#derive(Eq, Debug)
pub(all) enum Scalar {
  SNull
  SBool(Bool)
  SInt(Int64)
  SFloat(Double)
  SString(String)
  SBytes(Bytes)
}

///|
pub fn Scalar::kind(self : Scalar) -> BasicKind {
  match self {
    SNull => NullKind
    SBool(_) => BoolKind
    SInt(_) => IntKind
    SFloat(_) => FloatKind
    SString(_) => StringKind
    SBytes(_) => BytesKind
  }
}

///|
pub fn Scalar::is_numeric(self : Scalar) -> Bool {
  match self {
    SInt(_) | SFloat(_) => true
    _ => false
  }
}

///|
pub fn Scalar::as_double(self : Scalar) -> Double? {
  match self {
    SInt(i) => Some(i.to_double())
    SFloat(f) => Some(f)
    _ => None
  }
}

///|
pub fn Scalar::to_value(self : Scalar) -> Value {
  match self {
    SNull => VNull
    SBool(b) => VBool(b)
    SInt(i) => VInt(i)
    SFloat(f) => VFloat(f)
    SString(s) => VString(s)
    SBytes(b) => VBytes(b)
  }
}

///|
pub impl Show for Scalar with fn output(self, logger) {
  match self {
    SNull => logger.write_string("null")
    SBool(b) => logger.write_string(if b { "true" } else { "false" })
    SInt(i) => logger.write_string("\{i}")
    SFloat(f) => logger.write_string("\{f}")
    SString(s) => logger.write_string("\"\{s}\"")
    SBytes(b) => logger.write_string("bytes(\{b.length()})")
  }
}

///|
#derive(Eq, Debug)
pub(all) enum BoundOp {
  BLt
  BLte
  BGt
  BGte
  BNeq
  BMatch
  BNotMatch
}

///|
pub impl Show for BoundOp with fn output(self, logger) {
  let s = match self {
    BLt => "<"
    BLte => "<="
    BGt => ">"
    BGte => ">="
    BNeq => "!="
    BMatch => "=~"
    BNotMatch => "!~"
  }
  logger.write_string(s)
}

///|
#derive(Eq, Debug)
pub(all) struct BoundVal {
  op : BoundOp
  scalar : Scalar
}

///|
pub impl Show for BoundVal with fn output(self, logger) {
  logger.write_string("\{self.op}\{self.scalar}")
}

///|
#derive(Eq, Debug)
pub(all) struct Disjunct {
  value : Value
  is_default : Bool
}

///|
#derive(Eq, Debug)
pub(all) struct StructField {
  name : String
  value : Value
  constraint : FieldConstraint
  is_definition : Bool
  is_hidden : Bool
}

///|
#derive(Eq, Debug)
pub(all) struct PatternConstraint {
  label_pattern : Value
  value : Value
}

///|
#derive(Eq, Debug)
pub(all) struct StructVal {
  fields : Array[StructField]
  patterns : Array[PatternConstraint]
  is_closed : Bool
  embed : Value?
}

///|
pub fn StructVal::empty(is_closed~ : Bool = false) -> StructVal {
  { fields: [], patterns: [], is_closed, embed: None, }
}

///|
pub fn StructVal::get_field(self : StructVal, name : String) -> StructField? {
  for f in self.fields {
    if f.name == name {
      return Some(f)
    }
  }
  None
}

///|
#derive(Eq, Debug)
pub(all) struct ListVal {
  elems : Array[Value]
  open_tail : Value?
}

///|
/// A node in the CUE Value Lattice.
#derive(Eq, Debug)
pub(all) enum Value {
  VTop
  VBottom(Array[CueError])
  VNull
  VBool(Bool)
  VInt(Int64)
  VFloat(Double)
  VString(String)
  VBytes(Bytes)
  VBasic(BasicKind)
  VBound(BoundVal)
  VConjunction(Array[Value])
  VDisjunction(Array[Disjunct])
  VStruct(StructVal)
  VList(ListVal)
}

///|
pub fn Value::bottom(
  kind : ErrorKind,
  message : String,
  path~ : Array[String] = [],
  span~ : Span? = None,
) -> Value {
  VBottom([CueError::new(kind, message, path~, span~)])
}

///|
pub fn Value::is_bottom(self : Value) -> Bool {
  match self {
    VBottom(_) => true
    _ => false
  }
}

///|
pub fn Value::is_top(self : Value) -> Bool {
  match self {
    VTop => true
    _ => false
  }
}

///|
pub fn Value::as_scalar(self : Value) -> Scalar? {
  match self {
    VNull => Some(SNull)
    VBool(b) => Some(SBool(b))
    VInt(i) => Some(SInt(i))
    VFloat(f) => Some(SFloat(f))
    VString(s) => Some(SString(s))
    VBytes(b) => Some(SBytes(b))
    _ => None
  }
}

///|
pub fn Value::is_concrete(self : Value) -> Bool {
  match self {
    VNull | VBool(_) | VInt(_) | VFloat(_) | VString(_) | VBytes(_) => true
    VStruct(s) => {
      match s.embed {
        Some(e) if !e.is_concrete() => return false
        _ => ()
      }
      for f in s.fields {
        if f.is_definition || f.is_hidden {
          continue
        }
        match f.constraint {
          Optional => ()
          Required => return false
          Regular => if !f.value.is_concrete() { return false }
        }
      }
      true
    }
    VList(l) => {
      if l.open_tail is Some(_) {
        return false
      }
      for elem in l.elems {
        if !elem.is_concrete() {
          return false
        }
      }
      true
    }
    _ => false
  }
}

///|
pub fn Value::errors(self : Value) -> Array[CueError] {
  let out : Array[CueError] = []
  collect_errors(self, [], out)
  out
}

///|
fn collect_errors(
  val : Value,
  prefix : Array[String],
  out : Array[CueError],
) -> Unit {
  match val {
    VBottom(errs) =>
      for e in errs {
        let mut prefixed = e
        for i = prefix.length() - 1; i >= 0; i = i - 1 {
          prefixed = prefixed.with_path_prefix(prefix[i])
        }
        out.push(prefixed)
      }
    VStruct(s) => {
      match s.embed {
        Some(e) => collect_errors(e, prefix, out)
        None => ()
      }
      for f in s.fields {
        if f.is_definition {
          continue
        }
        let next = prefix.copy()
        next.push(f.name)
        collect_errors(f.value, next, out)
      }
    }
    VList(l) =>
      for i = 0; i < l.elems.length(); i = i + 1 {
        let next = prefix.copy()
        next.push("[\{i}]")
        collect_errors(l.elems[i], next, out)
      }
    _ => ()
  }
}

///|
/// Returns true if `val` contains any bottom error (directly or nested in regular fields/elements).
pub fn Value::has_error(self : Value) -> Bool {
  !self.errors().is_empty()
}