// Comprehensive weak reference validation test

box Parent {
    init { name }
    
    pack(parentName) {
        me.name = parentName
    }
    
    getName() {
        return me.name
    }
}

box Child {
    init { weak parent, id }
    
    pack(childId) {
        me.id = childId
        me.parent = 0  // Initialize as null
    }
    
    setParent(p) {
        me.parent = p
    }
    
    // Safe check that doesn't call toString on null
    checkParentStatus() {
        local parentRef = me.parent
        
        // Check if we got a valid parent reference
        local console = new ConsoleBox()
        console.log("Child " + me.id.toString() + " checking parent...")
        
        // We expect null after parent drop, which should not cause errors
        return "checked"
    }
    
    getId() {
        return me.id
    }
}

static box Main {
    main() {
        print("=== Comprehensive Weak Reference Validation ===")
        
        local parent1 = new Parent("Parent1")
        local parent2 = new Parent("Parent2")
        
        local child1 = new Child(1)
        local child2 = new Child(2) 
        local child3 = new Child(3)
        
        print("Step 1: Set up multiple weak references")
        child1.setParent(parent1)
        child2.setParent(parent1)  // Two children reference same parent
        child3.setParent(parent2)  // One child references different parent
        
        print("Step 2: Verify all children can access parents")
        child1.checkParentStatus()
        child2.checkParentStatus()
        child3.checkParentStatus()
        
        print("Step 3: Drop parent1 (affects child1 and child2)")
        parent1 = 0  // This should invalidate child1 and child2's references
        
        print("Step 4: Check all children after parent1 drop")
        child1.checkParentStatus()  // Should be null now
        child2.checkParentStatus()  // Should be null now
        child3.checkParentStatus()  // Should still be valid (different parent)
        
        print("Step 5: Drop parent2 (affects child3)")
        parent2 = 0  // This should invalidate child3's reference
        
        print("Step 6: Final check - all should be null now")
        child1.checkParentStatus()  // Still null
        child2.checkParentStatus()  // Still null
        child3.checkParentStatus()  // Now null too
        
        print("✅ Weak reference system validation complete!")
        return "All tests passed"
    }
}