// lower_return_int_box.hako — Return(Int) → const+ret

using selfhost.shared.json.utils.json_frag as JsonFragBox

static box LowerReturnIntBox {
  try_lower(program_json) {
    local s = "" + program_json
    local k_ret = JsonFragBox.index_of_from(s, "\"type\":\"Return\"", 0)
    if k_ret < 0 { return null }
    // Find expr object
    local k_expr = JsonFragBox.index_of_from(s, "\"expr\":{", k_ret)
    if k_expr < 0 { return null }
    // Check that expr.type is directly Int (not Binary, Logical, Var, etc)
    // Tolerant: type must be near expr start
    local kt = JsonFragBox.index_of_from(s, "\"type\":\"Int\"", k_expr)
    if kt < 0 || kt > k_expr + 64 { return null }
    // Now extract the value
    local k_int = kt
    local kv = JsonFragBox.index_of_from(s, "\"value\":", k_int); if kv < 0 { return null }
    local val = JsonFragBox.read_int_after(s, kv + 8)
    if val == null { return null }
    local debug_on = 0
    if env.get("HAKO_MIR_BUILDER_DEBUG") == "1" || env.get("NYASH_CLI_VERBOSE") == "1" {
      debug_on = 1
      print("[mirbuilder/registry:return.int val=" + val + "]")
    }
    // Emit minimal MIR JSON v0 (functions as array; blocks use id field)
    // Shape expected by src/runner/mir_json_v0.rs::parse_mir_v0_to_module
    local mir = "{\"functions\":[{\"name\":\"main\",\"params\":[],\"locals\":[],\"blocks\":[{\"id\":0,\"instructions\":[{\"op\":\"const\",\"dst\":1,\"value\":{\"type\":\"i64\",\"value\":" + val + "}},{\"op\":\"ret\",\"value\":1}]}]}]}"
    return mir
  }
}
