// test_barrier.hako — Phase 2 Day 6 Barrier tests
// Expected: Barrier instruction validates fields and succeeds (no-op in Phase 1)

using selfhost.vm.hakorune-vm.hakorune_vm_core as HakoruneVmCore
using selfhost.shared.common.string_helpers as StringHelpers

static box Main {
  main() {
    // Test 1: Barrier Read
    local mir1 = r#"{"functions":[{"name":"test","blocks":[{"id":0,"instructions":[{"op":"const","dst":1,"value":{"type":"i64","value":42}},{"op":"barrier","op_kind":"Read","ptr":1},{"op":"ret","value":1}],"terminator":{"op":"ret","value":1}}]}]}"#

    local result1 = HakoruneVmCore.run(mir1)
    print("Test 1: barrier Read + const 42 → " + StringHelpers.int_to_str(result1))
    if result1 != 42 {
      print("[FAIL] Test 1: expected 42, got " + StringHelpers.int_to_str(result1))
      return 1
    }

    // Test 2: Barrier Write
    local mir2 = r#"{"functions":[{"name":"test","blocks":[{"id":0,"instructions":[{"op":"const","dst":1,"value":{"type":"i64","value":100}},{"op":"barrier","op_kind":"Write","ptr":2},{"op":"ret","value":1}],"terminator":{"op":"ret","value":1}}]}]}"#

    local result2 = HakoruneVmCore.run(mir2)
    print("Test 2: barrier Write + const 100 → " + StringHelpers.int_to_str(result2))
    if result2 != 100 {
      print("[FAIL] Test 2: expected 100, got " + StringHelpers.int_to_str(result2))
      return 1
    }

    // Test 3: Multiple barriers in sequence
    local mir3 = r#"{"functions":[{"name":"test","blocks":[{"id":0,"instructions":[{"op":"const","dst":1,"value":{"type":"i64","value":10}},{"op":"barrier","op_kind":"Read","ptr":1},{"op":"const","dst":2,"value":{"type":"i64","value":32}},{"op":"barrier","op_kind":"Write","ptr":2},{"op":"binop","op_kind":"Add","dst":3,"lhs":1,"rhs":2},{"op":"barrier","op_kind":"Read","ptr":3},{"op":"ret","value":3}],"terminator":{"op":"ret","value":3}}]}]}"#

    local result3 = HakoruneVmCore.run(mir3)
    print("Test 3: barriers + add (10 + 32) → " + StringHelpers.int_to_str(result3))
    if result3 != 42 {
      print("[FAIL] Test 3: expected 42, got " + StringHelpers.int_to_str(result3))
      return 1
    }

    // Test 4: Mixed instructions with barriers
    local mir4 = r#"{"functions":[{"name":"test","blocks":[{"id":0,"instructions":[{"op":"const","dst":1,"value":{"type":"i64","value":5}},{"op":"store","value":1,"ptr":10},{"op":"barrier","op_kind":"Write","ptr":10},{"op":"load","dst":2,"ptr":10},{"op":"barrier","op_kind":"Read","ptr":10},{"op":"binop","op_kind":"Mul","dst":3,"lhs":2,"rhs":1},{"op":"ret","value":3}],"terminator":{"op":"ret","value":3}}]}]}"#

    local result4 = HakoruneVmCore.run(mir4)
    print("Test 4: store, barrier, load, barrier, mul (5 * 5) → " + StringHelpers.int_to_str(result4))
    if result4 != 25 {
      print("[FAIL] Test 4: expected 25, got " + StringHelpers.int_to_str(result4))
      return 1
    }

    print("✅ All Barrier tests PASSED!")
    return 0
  }
}
