///|
/// Raised when a runtime `Value` conversion or construction fails.
#derive(Eq, Debug)
pub(all) suberror ValueError {
  /// Invalid decimal number during JSON or YAML conversion.
  InvalidNumber(DecimalError)
  /// Invalid JSON source text.
  InvalidJson(message~ : String)
  /// Invalid YAML source text.
  InvalidYaml(message~ : String)
  /// Multiple YAML documents when a single value was expected.
  MultipleYamlDocuments(count~ : Int32)
}

///|
pub impl Show for ValueError with fn output(self, logger) {
  match self {
    InvalidNumber(err) => Show::output(err, logger)
    InvalidJson(message~) => logger.write_string("invalid JSON: \{message}")
    InvalidYaml(message~) => logger.write_string("invalid YAML: \{message}")
    MultipleYamlDocuments(count~) =>
      logger.write_string("expected one YAML document, found \{count}")
  }
}

///|
/// Explicit lexicographic Unicode code-point string comparison, independent of
/// string length, matching OPA's Go string ordering across all four targets.
fn cmp_string_lex(a : String, b : String) -> Int32 {
  let len_a = a.length()
  let len_b = b.length()
  let min_len = if len_a < len_b { len_a } else { len_b }
  for i in 0.. RegoSet {
  { items: ReadOnlyArray::from_array([]), }
}

///|
/// Constructs a canonical Rego set from arbitrary values, sorting and
/// deduplicating them under OPA's total `Value` order.
pub fn RegoSet::of(values : ArrayView[Value]) -> RegoSet {
  if values.is_empty() {
    return RegoSet::empty()
  }
  let sorted = values.to_owned()
  sorted.sort()
  let unique : Array[Value] = [sorted[0]]
  for i in 1.. ReadOnlyArray[Value] {
  self.items
}

///|
/// Number of distinct elements in this set.
pub fn RegoSet::length(self : RegoSet) -> Int32 {
  self.items.length()
}

///|
/// Reports whether this set is empty.
pub fn RegoSet::is_empty(self : RegoSet) -> Bool {
  self.items.is_empty()
}

///|
/// Binary search membership check in O(log n).
pub fn RegoSet::contains(self : RegoSet, target : Value) -> Bool {
  let mut lo = 0
  let mut hi = self.items.length() - 1
  while lo <= hi {
    let mid = lo + (hi - lo) / 2
    let cmp = self.items[mid].compare(target)
    if cmp == 0 {
      return true
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid - 1
    }
  }
  false
}

///|
/// Returns a new set with `item` inserted.
pub fn RegoSet::insert(self : RegoSet, item : Value) -> RegoSet {
  if self.contains(item) {
    return self
  }
  let out : Array[Value] = []
  let mut inserted = false
  for elem in self.items {
    if !inserted && item.compare(elem) < 0 {
      out.push(item)
      inserted = true
    }
    out.push(elem)
  }
  if !inserted {
    out.push(item)
  }
  { items: ReadOnlyArray::from_array(out), }
}

///|
/// Set union (`self | other`).
pub fn RegoSet::union(self : RegoSet, other : RegoSet) -> RegoSet {
  let a = self.items
  let b = other.items
  let out : Array[Value] = []
  let mut i = 0
  let mut j = 0
  while i < a.length() && j < b.length() {
    let c = a[i].compare(b[j])
    if c < 0 {
      out.push(a[i])
      i += 1
    } else if c > 0 {
      out.push(b[j])
      j += 1
    } else {
      out.push(a[i])
      i += 1
      j += 1
    }
  }
  while i < a.length() {
    out.push(a[i])
    i += 1
  }
  while j < b.length() {
    out.push(b[j])
    j += 1
  }
  { items: ReadOnlyArray::from_array(out), }
}

///|
/// Set intersection (`self & other`).
pub fn RegoSet::intersection(self : RegoSet, other : RegoSet) -> RegoSet {
  let a = self.items
  let b = other.items
  let out : Array[Value] = []
  let mut i = 0
  let mut j = 0
  while i < a.length() && j < b.length() {
    let c = a[i].compare(b[j])
    if c < 0 {
      i += 1
    } else if c > 0 {
      j += 1
    } else {
      out.push(a[i])
      i += 1
      j += 1
    }
  }
  { items: ReadOnlyArray::from_array(out), }
}

///|
/// Set difference (`self - other`).
pub fn RegoSet::diff(self : RegoSet, other : RegoSet) -> RegoSet {
  let a = self.items
  let b = other.items
  let out : Array[Value] = []
  let mut i = 0
  let mut j = 0
  while i < a.length() && j < b.length() {
    let c = a[i].compare(b[j])
    if c < 0 {
      out.push(a[i])
      i += 1
    } else if c > 0 {
      j += 1
    } else {
      i += 1
      j += 1
    }
  }
  while i < a.length() {
    out.push(a[i])
    i += 1
  }
  { items: ReadOnlyArray::from_array(out), }
}

///|
pub impl Compare for RegoSet with fn compare(self, other) {
  let a = self.items
  let b = other.items
  let min_len = if a.length() < b.length() { a.length() } else { b.length() }
  for i in 0.. RegoObject {
  { entries: ReadOnlyArray::from_array([]), }
}

///|
/// Constructs a canonical Rego object from key-value pairs. When duplicate keys
/// appear in `pairs`, the later entry wins.
pub fn RegoObject::of(pairs : ArrayView[(Value, Value)]) -> RegoObject {
  if pairs.is_empty() {
    return RegoObject::empty()
  }
  // Stable deduplication keeping the last value per key, then sorting by key.
  let indexed : Array[(Value, Int32, Value)] = []
  for i in 0.. {
    let kc = a.0.compare(b.0)
    if kc != 0 {
      kc
    } else {
      a.1.compare(b.1)
    }
  })
  let unique : Array[(Value, Value)] = []
  for i in 0.. RegoObject {
  let raw : Array[(Value, Value)] = []
  for pair in pairs {
    raw.push((Value::String(pair.0), pair.1))
  }
  RegoObject::of(raw)
}

///|
/// Returns the sorted `(key, value)` entries of this object.
pub fn RegoObject::entries(self : RegoObject) -> ReadOnlyArray[(Value, Value)] {
  self.entries
}

///|
/// Number of key-value entries in this object.
pub fn RegoObject::length(self : RegoObject) -> Int32 {
  self.entries.length()
}

///|
/// Reports whether this object is empty.
pub fn RegoObject::is_empty(self : RegoObject) -> Bool {
  self.entries.is_empty()
}

///|
/// Binary search lookup by key in O(log n).
pub fn RegoObject::get(self : RegoObject, key : Value) -> Value? {
  let mut lo = 0
  let mut hi = self.entries.length() - 1
  while lo <= hi {
    let mid = lo + (hi - lo) / 2
    let cmp = self.entries[mid].0.compare(key)
    if cmp == 0 {
      return Some(self.entries[mid].1)
    } else if cmp < 0 {
      lo = mid + 1
    } else {
      hi = mid - 1
    }
  }
  None
}

///|
/// Lookup by string key.
pub fn RegoObject::get_string(self : RegoObject, key : String) -> Value? {
  self.get(Value::String(key))
}

///|
/// Returns a new object with `(key, value)` inserted or updated.
pub fn RegoObject::insert(
  self : RegoObject,
  key : Value,
  value : Value,
) -> RegoObject {
  let out : Array[(Value, Value)] = []
  let mut placed = false
  for entry in self.entries {
    let c = key.compare(entry.0)
    if c == 0 {
      out.push((key, value))
      placed = true
    } else if !placed && c < 0 {
      out.push((key, value))
      out.push(entry)
      placed = true
    } else {
      out.push(entry)
    }
  }
  if !placed {
    out.push((key, value))
  }
  { entries: ReadOnlyArray::from_array(out), }
}

///|
/// Returns a new object with `key` removed when present.
pub fn RegoObject::remove(self : RegoObject, key : Value) -> RegoObject {
  let out : Array[(Value, Value)] = []
  for entry in self.entries {
    if entry.0 != key {
      out.push(entry)
    }
  }
  { entries: ReadOnlyArray::from_array(out), }
}

///|
pub impl Compare for RegoObject with fn compare(self, other) {
  let a = self.entries
  let b = other.entries
  let min_len = if a.length() < b.length() { a.length() } else { b.length() }
  for i in 0.. Int32 {
  match self {
    Null => 0
    Bool(_) => 1
    Number(_) => 2
    String(_) => 3
    Array(_) => 4
    Object(_) => 5
    Set(_) => 6
  }
}

///|
/// OPA `type_name` string for this value.
pub fn Value::type_name(self : Value) -> String {
  match self {
    Null => "null"
    Bool(_) => "boolean"
    Number(_) => "number"
    String(_) => "string"
    Array(_) => "array"
    Object(_) => "object"
    Set(_) => "set"
  }
}

///|
/// Constructs a `Value::Number` from an `Int32`.
pub fn Value::int(n : Int32) -> Value {
  Number(Decimal::from_int(n))
}

///|
/// Constructs a `Value::Array` from an immutable copy of `items`.
pub fn Value::array(items : ArrayView[Value]) -> Value {
  Array(ReadOnlyArray::from_array(items.to_owned()))
}

///|
/// Constructs a `Value::Set` from `items`.
pub fn Value::set(items : ArrayView[Value]) -> Value {
  Set(RegoSet::of(items))
}

///|
/// Constructs a `Value::Object` from `(key, value)` pairs.
pub fn Value::object(pairs : ArrayView[(Value, Value)]) -> Value {
  Object(RegoObject::of(pairs))
}

///|
/// Constructs a `Value::Object` from string-keyed pairs.
pub fn Value::string_object(pairs : ArrayView[(String, Value)]) -> Value {
  Object(RegoObject::from_strings(pairs))
}

///|
/// Total deterministic order across all `Value` variants matching OPA v1.23.0.
pub impl Compare for Value with fn compare(self, other) {
  let r1 = self.rank()
  let r2 = other.rank()
  if r1 != r2 {
    return r1.compare(r2)
  }
  match (self, other) {
    (Null, Null) => 0
    (Bool(a), Bool(b)) => a.compare(b)
    (Number(a), Number(b)) => a.compare(b)
    (String(a), String(b)) => cmp_string_lex(a, b)
    (Array(a), Array(b)) => {
      let min_len = if a.length() < b.length() {
        a.length()
      } else {
        b.length()
      }
      for i in 0.. a.compare(b)
    (Set(a), Set(b)) => a.compare(b)
    _ => 0
  }
}

///|
pub extend Value with Compare::{compare}

///|
/// Formats a `Value` as an OPA Rego literal (used inside collections and for
/// display).
pub fn Value::format_rego(self : Value) -> String {
  let buf = StringBuilder()
  self.write_rego(buf)
  buf.to_string()
}

///|
fn write_json_escaped(buf : StringBuilder, s : String) -> Unit {
  buf.write_char('"')
  for i in 0.. buf.write_string("\\\"")
      0x5C => buf.write_string("\\\\")
      0x08 => buf.write_string("\\b")
      0x0C => buf.write_string("\\f")
      0x0A => buf.write_string("\\n")
      0x0D => buf.write_string("\\r")
      0x09 => buf.write_string("\\t")
      _ if c < 0x20 => {
        let hex = "0123456789abcdef"
        buf.write_string("\\u00")
        buf.write_char(
          hex.code_unit_at((c >> 4) & 0xF).to_int().unsafe_to_char(),
        )
        buf.write_char(hex.code_unit_at(c & 0xF).to_int().unsafe_to_char())
      }
      _ => buf.write_string(s[i:i + 1].to_owned())
    }
  }
  buf.write_char('"')
}

///|
fn Value::write_rego(self : Value, buf : StringBuilder) -> Unit {
  match self {
    Null => buf.write_string("null")
    Bool(true) => buf.write_string("true")
    Bool(false) => buf.write_string("false")
    Number(d) => buf.write_string(d.to_string())
    String(s) => write_json_escaped(buf, s)
    Array(items) => {
      buf.write_char('[')
      for i in 0.. 0 {
          buf.write_string(", ")
        }
        items[i].write_rego(buf)
      }
      buf.write_char(']')
    }
    Set(set) => {
      let items = set.items()
      if items.is_empty() {
        buf.write_string("set()")
      } else {
        buf.write_char('{')
        for i in 0.. 0 {
            buf.write_string(", ")
          }
          items[i].write_rego(buf)
        }
        buf.write_char('}')
      }
    }
    Object(obj) => {
      let entries = obj.entries()
      buf.write_char('{')
      for i in 0.. 0 {
          buf.write_string(", ")
        }
        entries[i].0.write_rego(buf)
        buf.write_string(": ")
        entries[i].1.write_rego(buf)
      }
      buf.write_char('}')
    }
  }
}

///|
/// Formats a `Value` for Rego template string interpolation (`$"..."`):
/// top-level strings render unquoted, while nested collections use OPA's
/// canonical Rego formatting (`[1, "a"]`, `set()`, `{42}`, `{"a": "b"}`).
pub fn Value::format_template(self : Value) -> String {
  match self {
    String(s) => s
    _ => self.format_rego()
  }
}

///|
pub impl Show for Value with fn output(self, logger) {
  logger.write_string(self.format_rego())
}