// Simple weak reference test for Phase 10.2

// Test CPU with fini
box TestCPU {
    init { memory, name }
    
    TestCPU() {
        me.name = "TestCPU"
        print("CPU initialized: " + me.name)
    }
    
    fini() {
        print("CPU fini called - cleaning up memory")
        if (me.memory != null) {
            me.memory.cleanup()
        }
        print("CPU fini complete")
    }
}

// Test Memory with weak reference
box TestMemory {
    init { data, weak cpu_ref }
    
    TestMemory(cpu_instance) {
        me.data = new ArrayBox()
        me.data.push("test_data")
        me.cpu_ref = cpu_instance  // This will be automatically downgraded to weak
        print("Memory initialized with weak CPU reference")
    }
    
    read_data() {
        if (me.cpu_ref != null) {
            print("CPU is alive - returning data")
            return me.data.get(0)
        } else {
            print("CPU is destroyed - access blocked")
            return null
        }
    }
    
    cleanup() {
        print("Memory cleanup called")
        me.data.clear()
    }
}

// Main test
static box Main {
    init { console }
    
    main() {
        me.console = new ConsoleBox()
        me.console.log("🧪 Testing weak references and fini propagation")
        
        // Create CPU and Memory
        local cpu = new TestCPU()
        
        local memory = new TestMemory(cpu)
        
        // Link memory to CPU for fini propagation
        cpu.memory = memory
        
        // Test 1: Normal operation
        me.console.log("Test 1: Normal operation")
        local result1 = memory.read_data()
        me.console.log("Read result: " + result1)
        
        // Test 2: After CPU destruction
        me.console.log("Test 2: Destroying CPU...")
        cpu.fini()
        cpu = null
        
        local result2 = memory.read_data()
        me.console.log("Read after CPU destruction: " + result2)
        
        return "Test complete"
    }
}