// backward_object_scanner.hako — BackwardObjectScannerBox
// Responsibility: extract last JSON object in a segment by scanning backward

using selfhost.vm.boxes.result_box as Result

static box BackwardObjectScannerBox {
  // Returns Ok(obj_string) or Err(label)
  scan_last_object(seg, budget) {
    local n = seg.length()
    local steps = 0
    // trim trailing spaces/commas
    local e = n - 1
    loop(e >= 0) {
      if steps >= budget { return Result.Err("scan budget exceeded (trim)") }
      steps = steps + 1
      local ch = seg.substring(e, e+1)
      if ch == " " || ch == "
" || ch == "
" || ch == "	" || ch == "," { e = e - 1  continue }
      break
    }
    // find last '}'
    loop(e >= 0) {
      if steps >= budget { return Result.Err("scan budget exceeded (find end)") }
      steps = steps + 1
      if seg.substring(e, e+1) == "}" { break }
      e = e - 1
    }
    if e < 0 { return Result.Err("no closing brace") }
    // match '{'
    local depth = 1
    local s = e - 1
    loop(s >= 0) {
      if steps >= budget { return Result.Err("scan budget exceeded (match start)") }
      steps = steps + 1
      local ch2 = seg.substring(s, s+1)
      if ch2 == "}" { depth = depth + 1 } else { if ch2 == "{" { depth = depth - 1  if depth == 0 { break } } }
      s = s - 1
    }
    if s < 0 { return Result.Err("no opening brace") }
    return Result.Ok(seg.substring(s, e+1))
  }
}
