// lower_method_array_get_set_box.hako — Minimal structural MIR for ArrayBox set/get
using selfhost.shared.json.utils.json_frag as JsonFragBox
using "hako.mir.builder.internal.pattern_util" as PatternUtilBox

static box LowerMethodArrayGetSetBox {
  try_lower(program_json) {
    if program_json == null { return null }
    local s = "" + program_json
    if JsonFragBox.index_of_from(s, "\"type\":\"New\"", 0) < 0 { return null }
    if JsonFragBox.index_of_from(s, "\"class\":\"ArrayBox\"", 0) < 0 { return null }
    // Reverse-lookup (safe subset): prefer Local(Int) for index, Local(String) for value
    local n = s.length()
    local idx = PatternUtilBox.find_any_local_int_before(s, n)
    if idx == null { idx = "2" }
    local sval = PatternUtilBox.find_any_local_string_before(s, n)
    // Emit MIR v1 JSON: new Array -> r1, const idx -> r2, const val -> r3, set(r1,r2,r3), get(r1,r2)->r4, const 0->r5, ret r5
    local json = "{\"kind\":\"MIR\",\"schema_version\":\"1.0\",\"functions\":[{\"name\":\"main\",\"blocks\":[{\"id\":0,\"instructions\":[" +
               // new array -> r1
               "{\"op\":\"mir_call\",\"dst\":1,\"mir_call\":{\"callee\":{\"type\":\"Constructor\",\"box_type\":\"ArrayBox\"},\"args\":[],\"effects\":[]}}," +
               // const idx -> r2
               "{\"op\":\"const\",\"dst\":2,\"value\":{\"type\":\"i64\",\"value\":" + idx + "}}," +
               // const val -> r3 (string when available, else i64=3)
               (sval != null ? ("{\\\"op\\\":\\\"const\\\",\\\"dst\\\":3,\\\"value\\\":{\\\"type\\\":\\\"string\\\",\\\"value\\\":\\\"" + sval + "\\\"}},") : "{\\\"op\\\":\\\"const\\\",\\\"dst\\\":3,\\\"value\\\":{\\\"type\\\":\\\"i64\\\",\\\"value\\\":3}},") +
               // set(r1, r2, r3)
               "{\"op\":\"mir_call\",\"mir_call\":{\"callee\":{\"type\":\"Method\",\"box_name\":\"ArrayBox\",\"method\":\"set\",\"receiver\":1},\"args\":[2,3],\"effects\":[]}}," +
               // get(r1, r2) -> r4
               "{\"op\":\"mir_call\",\"dst\":4,\"mir_call\":{\"callee\":{\"type\":\"Method\",\"box_name\":\"ArrayBox\",\"method\":\"get\",\"receiver\":1},\"args\":[2],\"effects\":[]}}," +
               // const 0 -> r5, ret r5
                "{\"op\":\"const\",\"dst\":5,\"value\":{\"type\":\"i64\",\"value\":0}}," +
                "{\"op\":\"ret\",\"value\":5}]}]}]}"
    return json
  }
}
