// lower_return_bool_box.hako — Return(Bool) → const(1/0) + ret

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

static box LowerReturnBoolBox {
  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 }
    // Restrict to Return(expr=Bool …): require expr 開始直後に Bool が来る
    // 例: "expr":{"type":"Bool","value":true}
    local k_expr = JsonFragBox.index_of_from(s, "\"expr\":", k_ret)
    if k_expr < 0 { return null }
    local k_bool = JsonFragBox.index_of_from(s, "\"type\":\"Bool\"", k_expr)
    if k_bool < 0 { return null }
    // Ensure this Bool belongs to the same expr (次の '}' までに value があることを確認)
    local k_val = JsonFragBox.index_of_from(s, "\"value\":", k_bool)
    if k_val < 0 { return null }
    local is_true = JsonFragBox.read_bool_after(s, k_val+8)
    if is_true == null { return null }
    local v = is_true == 1 ? 1 : 0
    // Emit MIR v0 as JSON string (functions[]/name="main"/blocks.id)
    local json = "{\"functions\":[{\"name\":\"main\",\"params\":[],\"locals\":[],\"blocks\":[{\"id\":0,\"instructions\":[" +
                "{\"op\":\"const\",\"dst\":1,\"value\":{\"type\":\"i64\",\"value\":" + v + "}}," +
                "{\"op\":\"ret\",\"value\":1}]}]}]}"
    return json
  }
}
