// InstFieldExtractorBox - Common instruction field extraction utilities
// Eliminates repetitive JsonFieldExtractor.extract_ calls across handlers

using selfhost.vm.hakorune-vm.json_field_extractor as JsonFieldExtractor
using selfhost.vm.boxes.result_box as Result

static box InstFieldExtractorBox {
  // Extract dst register (most common pattern)
  static extract_dst(inst_json) {
    return JsonFieldExtractor.extract_int(inst_json, "dst")
  }
  
  // Extract binary operation fields (lhs, rhs, operation)
  static extract_binary_ops(inst_json) {
    local result = {}
    result.lhs = JsonFieldExtractor.extract_int(inst_json, "lhs")
    result.rhs = JsonFieldExtractor.extract_int(inst_json, "rhs")
    result.operation = JsonFieldExtractor.extract_string(inst_json, "operation")
    // Handle alternative op_kind field
    if result.operation == null {
      result.operation = JsonFieldExtractor.extract_string(inst_json, "op_kind")
    }
    return result
  }
  
  // Extract comparison fields (lhs, rhs, kind) and normalize to operation
  static extract_compare_ops(inst_json) {
    local result = {}
    result.lhs = JsonFieldExtractor.extract_int(inst_json, "lhs")
    result.rhs = JsonFieldExtractor.extract_int(inst_json, "rhs")
    result.kind = JsonFieldExtractor.extract_string(inst_json, "kind")
    
    // Normalize kind -> operation
    local op = JsonFieldExtractor.extract_string(inst_json, "operation")
    if op == null && result.kind != null {
      if result.kind == "Eq" { op = "==" }
      else if result.kind == "Ne" { op = "!=" }
      else if result.kind == "Lt" { op = "<" }
      else if result.kind == "Le" { op = "<=" }
      else if result.kind == "Gt" { op = ">" }
      else if result.kind == "Ge" { op = ">=" }
    }
    result.operation = op
    return result
  }
  
  // Extract unary operation fields (operand, op_kind)
  static extract_unary_ops(inst_json) {
    local result = {}
    result.operand = JsonFieldExtractor.extract_int(inst_json, "operand")
    result.op_kind = JsonFieldExtractor.extract_string(inst_json, "op_kind")
    return result
  }
  
  // Extract copy operation fields (src)
  static extract_copy_ops(inst_json) {
    local result = {}
    result.src = JsonFieldExtractor.extract_int(inst_json, "src")
    return result
  }
  
  // Extract box call fields (box, method, args_count)
  static extract_boxcall_ops(inst_json) {
    local result = {}
    result.box_id = JsonFieldExtractor.extract_int(inst_json, "box")
    result.method_name = JsonFieldExtractor.extract_string(inst_json, "method")
    result.args_count = JsonFieldExtractor.extract_int(inst_json, "args_count")
    return result
  }
}
