// Cycle-safe lazy $ref resolver over the source tree. Only internal
// references (`#` and `#/...`) are supported at this layer; external documents
// produce a located error diagnostic.

///|
pub struct Resolver {
  priv root : Node
  /// ref string -> resolved node (`Some`) or cached failure (`None`).
  priv cache : Map[String, Node?]
  /// Diagnostics sink shared with the decoding pass.
  priv diags : Diagnostics
}

///|
pub fn Resolver::new(root : Node, diags : Diagnostics) -> Resolver {
  { root, cache: Map([]), diags, }
}

///|
/// Percent-decode a URI fragment component (RFC 6901 §6) via
/// `moonbitlang/core/encoding/percent`. Returns `None` on malformed `%`
/// escapes or invalid UTF-8 sequences.
fn percent_decode(text : String) -> String? {
  if !text.contains("%") {
    return Some(text)
  }
  Some(@percent.decode(text[:])) catch {
    _ => None
  }
}

///|
/// Decode a single URI-fragment JSON Pointer segment (percent-decode per
/// RFC 6901 §6, then strict `~1`/`~0` unescape per RFC 6901 §4).
/// Returns `None` if either percent-decoding or JSON Pointer unescaping fails.
pub fn decode_fragment_segment(seg : StringView) -> String? {
  match percent_decode(seg.to_owned()) {
    Some(decoded) => json_pointer_unescape_strict(decoded[:])
    None => None
  }
}

///|
/// Normalize a `#...` fragment ref into a JSON pointer string (stripping `#`).
fn ref_to_diag_pointer(ref_ : String) -> String {
  if ref_.has_prefix("#") {
    ref_[1:].to_owned()
  } else {
    ""
  }
}

///|
/// Resolve a raw `$ref` string (`#` or `#/components/schemas/Foo`) to the
/// node it points at. Both hits and failures are cached so repeated lookups
/// never emit duplicate diagnostics. Does NOT follow `$ref` aliases at the
/// target — use `resolve_ref_chain` for that.
pub fn Resolver::resolve(self : Resolver, ref_ : String) -> Node? {
  match self.cache.get(ref_) {
    Some(cached) => return cached
    None => ()
  }
  // Only internal references (`#` or `#/...`)
  if ref_ != "#" && !ref_.has_prefix("#/") {
    self.diags.error(
      "E-external-ref",
      "",
      "external references are not supported at this layer: \"\{ref_}\"",
    )
    self.cache[ref_] = None
    return None
  }
  let result = self.resolve_pointer(ref_)
  self.cache[ref_] = result
  result
}

///|
/// Parse an RFC 6901 §4 array index (`"0"` or `[1-9][0-9]*`, no leading zeros).
fn parse_array_index(key : String) -> Int32? {
  if key.is_empty() {
    return None
  }
  if key.length() > 1 && key[0] == '0' {
    return None
  }
  for ch in key {
    if !(ch is ('0'..<='9')) {
      return None
    }
  }
  match parse_int64_text(key) {
    Some(v) => if v >= 0L && v <= 2147483647L { Some(v.to_int()) } else { None }
    None => None
  }
}

///|
/// Walk `#` or `#/a/b/c` through the tree (URI fragment percent-decoding +
/// RFC 6901 unescaping).
fn Resolver::resolve_pointer(self : Resolver, ref_ : String) -> Node? {
  if ref_ == "#" {
    return Some(self.root)
  }
  let diag_ptr = ref_to_diag_pointer(ref_)
  let raw_pointer = ref_[2:].to_owned()
  let mut current = self.root
  for raw_segment in raw_pointer.split("/") {
    let seg_str = raw_segment.to_owned()
    let decoded = match percent_decode(seg_str) {
      Some(s) => s
      None => {
        self.diags.error(
          "E-dangling-ref",
          diag_ptr,
          "invalid percent-encoding in $ref: \"\{ref_}\"",
        )
        return None
      }
    }
    let key = match json_pointer_unescape_strict(decoded[:]) {
      Some(k) => k
      None => {
        self.diags.error(
          "E-dangling-ref",
          diag_ptr,
          "invalid JSON Pointer escape in $ref: \"\{ref_}\"",
        )
        return None
      }
    }
    match current {
      Object(obj) =>
        match obj.get(key) {
          Some(child) => current = child
          None => {
            self.diags.error(
              "E-dangling-ref",
              diag_ptr,
              "$ref points at a missing location: \"\{ref_}\" (no key \"\{key}\")",
            )
            return None
          }
        }
      Array(items) =>
        match parse_array_index(key) {
          Some(index) if index >= 0 && index < items.length() =>
            current = items[index]
          _ => {
            self.diags.error(
              "E-dangling-ref",
              diag_ptr,
              "$ref points at a missing array index: \"\{ref_}\"",
            )
            return None
          }
        }
      _ => {
        self.diags.error(
          "E-dangling-ref",
          diag_ptr,
          "$ref walks into a scalar at \"\{ref_}\"",
        )
        return None
      }
    }
  }
  Some(current)
}

///|
/// Resolve a `$ref` value's target and follow any chain of `$ref` aliases
/// (including objects with ignored sibling keys). Uses a visited set to detect
/// cycles immediately and caps chain depth at 64 hops.
pub fn Resolver::resolve_ref_chain(self : Resolver, ref_ : String) -> Node? {
  let visited : Map[String, Unit] = Map([])
  let mut current_ref = ref_
  let mut hops = 0
  while hops <= 64 {
    if visited.contains(current_ref) {
      self.diags.error(
        "E-ref-cycle",
        ref_to_diag_pointer(current_ref),
        "circular $ref chain through \"\{current_ref}\"",
      )
      return None
    }
    visited[current_ref] = ()
    let node = match self.resolve(current_ref) {
      Some(node) => node
      None => return None
    }
    let next : String? = match node {
      Object(obj) =>
        match obj.get("$ref") {
          Some(Str(next_ref)) => Some(next_ref)
          _ => None
        }
      _ => None
    }
    match next {
      Some(next_ref) => {
        current_ref = next_ref
        hops += 1
      }
      None => return Some(node)
    }
  }
  self.diags.error(
    "E-deep-ref-chain",
    ref_to_diag_pointer(ref_),
    "$ref chain through \"\{ref_}\" exceeded maximum depth of 64 hops",
  )
  None
}