// The internal document tree. Both adapters (YAML and JSON) produce this;
// the model decoder walks it and diagnostics carry JSON-pointer locations
// built from the walk path (the YAML parser exposes no per-node positions).

///|
/// Hard failure: the source cannot be parsed at all (the message includes
/// line/column for YAML when the parser reported them).
#derive(Debug, Eq)
pub(all) suberror SpecError {
  SpecError(String)
}

///|
/// A non-fatal issue found while parsing the source (e.g. duplicate keys or
/// unquoted numeric YAML keys).
#derive(Debug, Eq)
pub(all) struct SourceIssue {
  code : String
  pointer : String
  message : String
}

///|
/// Internal scalar/collection tree. `Number` carries the scalar's exact text
/// (JSON keeps the literal representation via `preserve_number_repr=true`;
/// YAML materialises Int32-fitting integers as `Number` and out-of-range
/// integers as `Str` per `bobzhang/yaml`, so numeric accessors accept both).
#derive(Debug, Eq)
pub(all) enum Node {
  Null
  Bool(Bool)
  Number(String)
  Str(String)
  Array(Array[Node])
  Object(ObjectNode)
}

///|
/// An ordered object: entries keep source order, so emission and pointer
/// construction are deterministic.
#derive(Debug, Eq)
pub(all) struct ObjectNode {
  entries : Array[(String, Node)]
}

///|
pub fn ObjectNode::new() -> ObjectNode {
  { entries: [], }
}

///|
pub fn ObjectNode::length(self : ObjectNode) -> Int32 {
  self.entries.length()
}

///|
/// Look up a key (last value wins, iterating backwards for O(1) early exit).
pub fn ObjectNode::get(self : ObjectNode, key : String) -> Node? {
  let mut i = self.entries.length() - 1
  while i >= 0 {
    let (k, v) = self.entries[i]
    if k == key {
      return Some(v)
    }
    i -= 1
  }
  None
}

///|
/// True when the key exists.
pub fn ObjectNode::contains(self : ObjectNode, key : String) -> Bool {
  self.get(key) is Some(_)
}

///|
/// Keys in source order.
pub fn ObjectNode::keys(self : ObjectNode) -> Array[String] {
  let out : Array[String] = []
  for entry in self.entries {
    out.push(entry.0)
  }
  out
}

///|
pub fn Node::as_str(self : Node) -> String? {
  match self {
    Str(s) => Some(s)
    _ => None
  }
}

///|
pub fn Node::as_bool(self : Node) -> Bool? {
  match self {
    Bool(b) => Some(b)
    _ => None
  }
}

///|
/// Numeric text of a `Number` node (scalar text exactly as materialised).
pub fn Node::as_number_text(self : Node) -> String? {
  match self {
    Number(text) => Some(text)
    _ => None
  }
}

///|
pub fn Node::as_array(self : Node) -> Array[Node]? {
  match self {
    Array(items) => Some(items)
    _ => None
  }
}

///|
pub fn Node::as_object(self : Node) -> ObjectNode? {
  match self {
    Object(obj) => Some(obj)
    _ => None
  }
}

///|
/// Parse as `Int32`. Accepts `Number` nodes and decimal-integer `Str` nodes
/// (needed because `bobzhang/yaml` returns non-`Int32` integers as `String`).
pub fn Node::as_int32(self : Node) -> Int32? {
  match self {
    Number(text) | Str(text) =>
      match parse_int64_text(text) {
        Some(v) =>
          if v >= -2147483648L && v <= 2147483647L {
            Some(v.to_int())
          } else {
            None
          }
        None => None
      }
    _ => None
  }
}

///|
/// Parse as `Int64` (full signed 64-bit range, including `Int64::MIN`).
/// Accepts `Number` nodes and decimal-integer `Str` nodes.
pub fn Node::as_int64(self : Node) -> Int64? {
  match self {
    Number(text) | Str(text) => parse_int64_text(text)
    _ => None
  }
}

///|
/// Parse as `UInt64` (full unsigned 64-bit range `0..=18446744073709551615`).
/// Accepts `Number` nodes and decimal-integer `Str` nodes.
pub fn Node::as_uint64(self : Node) -> UInt64? {
  match self {
    Number(text) | Str(text) => parse_uint64_text(text)
    _ => None
  }
}

///|
/// Parse as `Double` via the core JSON parser (handles exponents and exact
/// representations; accepts `Number` and numeric `Str` nodes).
pub fn Node::as_double(self : Node) -> Double? {
  match self {
    Number(text) | Str(text) =>
      try {
        match @json.parse(text) {
          @json.Number(d, ..) => Some(d)
          _ => None
        }
      } catch {
        _ => None
      }
    _ => None
  }
}

///|
/// Convert a `Node` to `@json.Json`, preserving exact numeric literal text
/// via `@json.Json::number(_, repr=...)` so 64-bit integer examples round-trip
/// losslessly.
pub fn Node::to_json(self : Node) -> @json.Json {
  match self {
    Null => @json.Json::null()
    Bool(b) => @json.Json::boolean(b)
    Str(s) => @json.Json::string(s)
    Number(text) =>
      match self.as_double() {
        Some(d) => @json.Json::number(d, repr=text)
        None => @json.Json::string(text)
      }
    Array(items) => @json.Json::array(items.map(fn(x) { x.to_json() }))
    Object(obj) => {
      let map : Map[String, @json.Json] = Map([])
      for entry in obj.entries {
        let (k, v) = entry
        map[k] = v.to_json()
      }
      @json.Json::object(map)
    }
  }
}

///|
fn is_signed_ascii_decimal(text : String) -> Bool {
  if text.is_empty() {
    return false
  }
  let mut started = false
  let mut saw_digit = false
  for ch in text {
    if !started {
      started = true
      if ch == '-' || ch == '+' {
        continue
      }
    }
    if !(ch is ('0'..<='9')) {
      return false
    }
    saw_digit = true
  }
  saw_digit
}

///|
fn is_unsigned_ascii_decimal(text : String) -> Bool {
  if text.is_empty() {
    return false
  }
  for ch in text {
    if !(ch is ('0'..<='9')) {
      return false
    }
  }
  true
}

///|
/// Overflow-checked signed 64-bit decimal parser supporting the full range
/// `[-9223372036854775808, 9223372036854775807]` via `moonbitlang/core/string`.
fn parse_int64_text(text : String) -> Int64? {
  if !is_signed_ascii_decimal(text) {
    return None
  }
  Some(@string.parse_int64(text[:], radix=10)) catch {
    _ => None
  }
}

///|
/// Overflow-checked unsigned 64-bit decimal parser (`0..=18446744073709551615`)
/// via `moonbitlang/core/string`.
fn parse_uint64_text(text : String) -> UInt64? {
  if !is_unsigned_ascii_decimal(text) {
    return None
  }
  Some(@string.parse_uint64(text[:], radix=10)) catch {
    _ => None
  }
}

///|
/// JSON-pointer escape per RFC 6901 (`~` → `~0`, `/` → `~1`).
pub fn json_pointer_escape(segment : String) -> String {
  let out = StringBuilder()
  for ch in segment {
    if ch == '~' {
      out.write_string("~0")
    } else if ch == '/' {
      out.write_string("~1")
    } else {
      out.write_char(ch)
    }
  }
  out.to_string()
}

///|
/// Strict RFC 6901 JSON-pointer unescape: returns `None` on invalid escape
/// sequences (e.g. `~2` or trailing `~`).
fn json_pointer_unescape_strict(segment : StringView) -> String? {
  let out = StringBuilder()
  let mut saw_tilde = false
  for ch in segment {
    if saw_tilde {
      if ch == '0' {
        out.write_char('~')
      } else if ch == '1' {
        out.write_char('/')
      } else {
        return None
      }
      saw_tilde = false
    } else if ch == '~' {
      saw_tilde = true
    } else {
      out.write_char(ch)
    }
  }
  if saw_tilde {
    return None
  }
  Some(out.to_string())
}

///|
/// JSON-pointer unescape per RFC 6901 (`~1` → `/`, `~0` → `~`).
pub fn json_pointer_unescape(segment : StringView) -> String {
  let out = StringBuilder()
  let mut saw_tilde = false
  for ch in segment {
    if saw_tilde {
      if ch == '0' {
        out.write_char('~')
      } else if ch == '1' {
        out.write_char('/')
      } else {
        out.write_char('~')
        out.write_char(ch)
      }
      saw_tilde = false
    } else if ch == '~' {
      saw_tilde = true
    } else {
      out.write_char(ch)
    }
  }
  if saw_tilde {
    out.write_char('~')
  }
  out.to_string()
}

///|
/// Append one escaped segment to a JSON pointer (`""` + `"a"` → `"/a"`,
/// `"/a"` + `"b/c"` → `"/a/b~1c"`).
pub fn pointer_join(pointer : String, segment : String) -> String {
  pointer + "/" + json_pointer_escape(segment)
}