// JsonFieldExtractorBox - Extract fields from JSON MIR instructions
// Centralizes JSON field parsing logic

using selfhost.shared.common.string_helpers as StringHelpers
using selfhost.shared.common.string_ops as StringOps

static box JsonFieldExtractor {
  // Extract integer field from JSON
  // json: JSON string (e.g., '{"dst":1,"src":2}')
  // field_name: field name (e.g., "dst")
  // Returns: integer value or null if not found
  extract_int(json, field_name) {
    local key = "\"" + field_name + "\":"
    local start = json.indexOf(key)
    if start < 0 {
      return null
    }
    start = start + key.length()
    // skip whitespace
    loop(start < json.length()) {
      local ch = json.substring(start, start+1)
      if ch == " " || ch == "\n" || ch == "\r" || ch == "\t" { start = start + 1  continue }
      break
    }
    // Case 1: plain integer (e.g., "dst":3)
    {
      local digits = StringHelpers.read_digits(json, start)
      if digits != "" {
        return StringHelpers.to_i64(digits)
      }
    }
    // Case 2: wrapped i64 (e.g., "dst":{"type":"i64","value":3})
    if json.substring(start, start+1) == "{" {
      local key_val = "\"value\":"
      local val_pos = StringOps.index_of_from(json, key_val, start)
      if val_pos >= 0 {
        val_pos = val_pos + key_val.length()
        // skip whitespace
        loop(val_pos < json.length()) {
          local ch2 = json.substring(val_pos, val_pos+1)
          if ch2 == " " || ch2 == "\n" || ch2 == "\r" || ch2 == "\t" { val_pos = val_pos + 1  continue }
          break
        }
        local digits2 = StringHelpers.read_digits(json, val_pos)
        if digits2 != "" { return StringHelpers.to_i64(digits2) }
      }
    }
    return null
  }

  // Extract string field from JSON
  // json: JSON string
  // field_name: field name (e.g., "op")
  // Returns: string value or null if not found
  extract_string(json, field_name) {
    local key = "\"" + field_name + "\":\""
    local start = json.indexOf(key)
    if start < 0 {
      return null
    }
    start = start + key.length()

    local end_pos = StringOps.index_of_from(json, "\"", start)
    if end_pos < 0 {
      return null
    }

    return json.substring(start, end_pos)
  }
}
