// json_scan.hako — JsonScanBox
// Escape-aware JSON structure scanning helpers.

using selfhost.shared.json.core.string_scan as StringScanBox
using selfhost.shared.common.string_helpers as StringHelpers

static box JsonScanBox {
  // minimal string→int (delegate to shared helper)
  _str_to_int(s) { return StringHelpers.to_i64(s) }
  // Seek the end index (inclusive) of an object starting at `start` (must be '{').
  seek_obj_end(text, start) {
    if text == null { return -1 }
    if start < 0 || start >= text.length() { return -1 }
    if text.substring(start, start+1) != "{" { return -1 }
    local n = text.length()
    local depth = 0
    local i = start
    local in_str = 0
    loop (i < n) {
      local ch = StringScanBox.read_char(text, i)
      if in_str == 1 {
        if ch == "\\" {
          i = i + 2
          continue
        }
        if ch == "\"" {
          in_str = 0
          i = i + 1
          continue
        }
        i = i + 1
        continue
      }
      if ch == "\"" {
        local j = StringScanBox.find_quote(text, i+1)
        if j < 0 { return -1 }
        i = j + 1
        continue
      }
      if ch == "{" {
        depth = depth + 1
      } else if ch == "}" {
        depth = depth - 1
        if depth == 0 { return i }
      }
      i = i + 1
    }
    return -1
  }

  // Seek the end index (inclusive) of an array starting at `start` (must be '[').
  seek_array_end(text, start) {
    if text == null { return -1 }
    // Normalize start to integer (defensive against stringified input)
    local start_s = "" + start
    local start_i = me._str_to_int(start_s)
    local n = text.length()
    if start_i < 0 || start_i >= n { return -1 }
    local first_ch = text.substring(start_i, start_i+1)
    if first_ch != "[" { return -1 }
    // main loop (escape-aware)
    local depth = 0
    local i = start_i
    local in_str = 0
    loop (i < n) {
      local ch = StringScanBox.read_char(text, i)
      if in_str == 1 {
        if ch == "\\" {
          i = i + 2
          continue
        }
        if ch == "\"" {
          in_str = 0
          i = i + 1
          continue
        }
        i = i + 1
        continue
      }
      if ch == "\"" {
        local j = StringScanBox.find_quote(text, i+1)
        if j < 0 { return -1 }
        i = j + 1
        continue
      }
      if ch == "[" {
        depth = depth + 1
      } else if ch == "]" {
        depth = depth - 1
        if depth == 0 { return i }
      }
      i = i + 1
    }
    return -1
  }

  // Search for either plain or escaped key pattern starting at `pos`.
  find_key_dual(text, plain, escaped, pos) {
    if text == null { return -1 }
    if pos < 0 { pos = 0 }
    local p = StringScanBox.index_of_from(text, plain, pos)
    if p >= 0 { return p }
    return StringScanBox.index_of_from(text, escaped, pos)
  }
}
