dmsc 0.1.9

Ri - A high-performance Rust middleware framework with modular architecture
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
//!
//! This file is part of Ri.
//! The Ri project belongs to the Dunimd Team.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! You may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//!     http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

#![allow(non_snake_case)]

//! # Resource Pool Management
//! 
//! This file implements resource pool management for the Ri framework, providing a way to group
//! similar devices together for efficient resource allocation and management. It includes both
//! single resource pools and a resource pool manager for handling multiple pools.
//! 
//! ## Key Components
//! 
//! - **RiResourcePool**: Manages a pool of similar devices
//! - **RiResourcePoolConfig**: Configuration for resource pools
//! - **RiResourcePoolStatistics**: Statistics for monitoring resource pools
//! - **RiResourcePoolManager**: Manages multiple resource pools
//! 
//! ## Design Principles
//! 
//! 1. **Resource Grouping**: Groups similar devices together for efficient management
//! 2. **Capacity Tracking**: Tracks total, available, and allocated capacity
//! 3. **Statistics Collection**: Collects comprehensive statistics for monitoring
//! 4. **Device Filtering**: Filters devices by availability and allocation status
//! 5. **Health Monitoring**: Monitors pool health based on available devices
//! 6. **Utilization Tracking**: Tracks resource utilization rates
//! 7. **Multi-Pool Management**: Supports managing multiple pools through a central manager
//! 8. **Device Type Segregation**: Each pool contains devices of a single type
//! 9. **Arc-Based Sharing**: Uses Arc for safe concurrent access to devices
//! 10. **Serialization Support**: All structures support serialization/deserialization
//! 11. **Builder Pattern**: Configurable through RiResourcePoolConfig
//! 12. **Resource Optimization**: Calculates total compute, memory, storage, and bandwidth
//! 
//! ## Usage
//! 
//! ```rust,ignore
//! use ri::device::{RiResourcePoolManager, RiResourcePoolConfig, RiDeviceType};
//! use ri::core::RiResult;
//! 
//! fn example() -> RiResult<()> {
//!     // Create a resource pool manager
//!     let mut manager = RiResourcePoolManager::new();
//!     
//!     // Create a resource pool configuration
//!     let config = RiResourcePoolConfig {
//!         name: "cpu-pool-1".to_string(),
//!         device_type: RiDeviceType::CPU,
//!         max_concurrent_allocations: 10,
//!         allocation_timeout_secs: 60,
//!         health_check_interval_secs: 30,
//!     };
//!     
//!     // Create a resource pool
//!     let pool = manager.create_pool(config);
//!     
//!     // Get pool statistics
//!     let stats = pool.get_statistics();
//!     println!("Pool has {} devices, utilization: {:.2}%", 
//!              stats.total_devices, stats.utilization_rate * 100.0);
//!     
//!     // Get all pools by device type
//!     let cpu_pools = manager.get_pools_by_type(RiDeviceType::CPU);
//!     println!("Found {} CPU pools", cpu_pools.len());
//!     
//!     // Get overall statistics
//!     let overall_stats = manager.get_overall_statistics();
//!     println!("Total devices across all pools: {}", overall_stats.total_devices);
//!     
//!     Ok(())
//! }
//! ```

use std::sync::{Arc, RwLock};
use std::collections::HashMap as FxHashMap;
use std::time::Duration;
use serde::{Serialize, Deserialize};

use super::core::{RiDevice, RiDeviceType, RiDeviceStatus};


/// Resource pool for managing multiple similar devices
/// 
/// This struct manages a pool of devices of the same type, tracking their availability,
/// allocation status, and capacity. It provides methods for adding/removing devices,
/// allocating/releasing devices, and collecting statistics.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiResourcePool {
    /// Name of the resource pool
    name: String,
    /// Type of devices in the pool
    device_type: RiDeviceType,
    /// Map of device IDs to device instances
    devices: FxHashMap<String, Arc<RiDevice>>,
    /// Total capacity of the pool (number of devices)
    total_capacity: usize,
    /// Available capacity (number of devices not allocated)
    available_capacity: usize,
    /// Allocated capacity (number of devices currently allocated)
    allocated_capacity: usize,
    /// Number of pending requests for devices
    pending_requests: usize,
    /// Total compute units across all devices in the pool
    total_compute_units: usize,
    /// Total memory in GB across all devices in the pool
    total_memory_gb: f64,
    /// Total storage in GB across all devices in the pool
    total_storage_gb: f64,
    /// Total bandwidth in Gbps across all devices in the pool
    total_bandwidth_gbps: f64,
    /// Available compute units (not allocated)
    available_compute_units: usize,
    /// Available memory in GB (not allocated)
    available_memory_gb: f64,
    /// Available storage in GB (not allocated)
    available_storage_gb: f64,
    /// Available bandwidth in Gbps (not allocated)
    available_bandwidth_gbps: f64,
    /// Connection pool state for lifecycle management
    connection_pool: Arc<RwLock<RiConnectionPool>>,
}

/// Configuration for a resource pool
/// 
/// This struct defines the configuration options for creating a resource pool, including
/// name, device type, and various operational parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiResourcePoolConfig {
    /// Name of the resource pool
    pub name: String,
    /// Type of devices that will be in the pool
    pub device_type: RiDeviceType,
    /// Maximum number of concurrent allocations allowed
    pub max_concurrent_allocations: usize,
    /// Timeout for device allocation in seconds
    pub allocation_timeout_secs: u64,
    /// Interval for health checks in seconds
    pub health_check_interval_secs: u64,
}

impl Default for RiResourcePoolConfig {
    fn default() -> Self {
        Self {
            name: "default_pool".to_string(),
            device_type: RiDeviceType::CPU,
            max_concurrent_allocations: 10,
            allocation_timeout_secs: 60,
            health_check_interval_secs: 30,
        }
    }
}

impl RiResourcePool {
    /// Creates a new resource pool with the given configuration
    /// 
    /// # Parameters
    /// 
    /// - `config`: The configuration for the resource pool
    /// 
    /// # Returns
    /// 
    /// A new `RiResourcePool` instance with the specified configuration
    pub fn new(config: RiResourcePoolConfig) -> Self {
        let connection_pool = Arc::new(RwLock::new(RiConnectionPool::new(
            config.max_concurrent_allocations,
            Duration::from_secs(config.allocation_timeout_secs),
            Duration::from_secs(config.health_check_interval_secs),
        )));
        
        Self {
            name: config.name,
            device_type: config.device_type,
            devices: FxHashMap::with_capacity(16),
            total_capacity: 0,
            available_capacity: 0,
            allocated_capacity: 0,
            pending_requests: 0,
            total_compute_units: 0,
            total_memory_gb: 0.0,
            total_storage_gb: 0.0,
            total_bandwidth_gbps: 0.0,
            available_compute_units: 0,
            available_memory_gb: 0.0,
            available_storage_gb: 0.0,
            available_bandwidth_gbps: 0.0,
            connection_pool,
        }
    }
    
    /// Adds a device to the pool
    /// 
    /// This method adds a device to the pool if it matches the pool's device type
    /// and is not already in the pool.
    /// 
    /// # Parameters
    /// 
    /// - `device`: The device to add to the pool
    /// 
    /// # Returns
    /// 
    /// `true` if the device was successfully added, `false` otherwise
    pub fn add_device(&mut self, device: Arc<RiDevice>) -> bool {
        // Check if device type matches pool device type
        if device.device_type() != self.device_type {
            return false;
        }
        
        let device_id = device.id().to_string();
        // Check if device is already in the pool
        if self.devices.contains_key(&device_id) {
            return false;
        }
        
        // Get device capabilities and extract values before inserting the device
        let compute_units = device.capabilities().compute_units.unwrap_or(0);
        let memory_gb = device.capabilities().memory_gb.unwrap_or(0.0);
        let storage_gb = device.capabilities().storage_gb.unwrap_or(0.0);
        let bandwidth_gbps = device.capabilities().bandwidth_gbps.unwrap_or(0.0);
        
        // Add device to the pool
        self.devices.insert(device_id, device);
        
        // Update capacity counters
        self.total_capacity += 1;
        self.available_capacity += 1;
        
        // Update total resource counters
        self.total_compute_units += compute_units;
        self.total_memory_gb += memory_gb;
        self.total_storage_gb += storage_gb;
        self.total_bandwidth_gbps += bandwidth_gbps;
        
        // Update available resource counters (device is available initially)
        self.available_compute_units += compute_units;
        self.available_memory_gb += memory_gb;
        self.available_storage_gb += storage_gb;
        self.available_bandwidth_gbps += bandwidth_gbps;
        
        true
    }
    
    /// Removes a device from the pool
    /// 
    /// This method removes a device from the pool by its ID, updating capacity counters
    /// based on the device's status.
    /// 
    /// # Parameters
    /// 
    /// - `device_id`: The ID of the device to remove
    /// 
    /// # Returns
    /// 
    /// `true` if the device was successfully removed, `false` otherwise
    pub fn remove_device(&mut self, device_id: &str) -> bool {
        if let Some(device) = self.devices.remove(device_id) {
            // Get device capabilities
            let capabilities = device.capabilities();
            
            // Decrement total capacity
            self.total_capacity -= 1;
            
            // Update available or allocated capacity based on device status
            if device.is_available() {
                self.available_capacity -= 1;
                
                // Update available resource counters
                self.available_compute_units -= capabilities.compute_units.unwrap_or(0);
                self.available_memory_gb -= capabilities.memory_gb.unwrap_or(0.0);
                self.available_storage_gb -= capabilities.storage_gb.unwrap_or(0.0);
                self.available_bandwidth_gbps -= capabilities.bandwidth_gbps.unwrap_or(0.0);
            } else if device.is_allocated() {
                self.allocated_capacity -= 1;
                
                // Update allocated resource counters indirectly by updating total
                // Available resources don't change when removing an allocated device
            }
            
            // Update total resource counters
            self.total_compute_units -= capabilities.compute_units.unwrap_or(0);
            self.total_memory_gb -= capabilities.memory_gb.unwrap_or(0.0);
            self.total_storage_gb -= capabilities.storage_gb.unwrap_or(0.0);
            self.total_bandwidth_gbps -= capabilities.bandwidth_gbps.unwrap_or(0.0);
            
            true
        } else {
            false
        }
    }
    
    /// Allocates a device from the pool
    /// 
    /// This method allocates the first available device from the pool, updating capacity counters.
    /// 
    /// # Parameters
    /// 
    /// - `_allocation_id`: The ID of the allocation (currently unused)
    /// 
    /// # Returns
    /// 
    /// An `Option<Arc<RiDevice>>` containing the allocated device if successful, `None` otherwise
    pub fn allocate(&mut self, _allocation_id: &str) -> Option<Arc<RiDevice>> {
        // Check if there's available capacity
        if self.available_capacity == 0 {
            return None;
        }
        
        // Find the first available device
        for device in self.devices.values() {
            // This is a simplified allocation - in a real implementation, 
            // we'd need to lock the device and check its status atomically
            if device.is_available() {
                // Get device capabilities
                let capabilities = device.capabilities();
                
                // Note: In a real implementation, we'd need to modify the device
                // to mark it as allocated. This is simplified for demonstration.
                self.available_capacity -= 1;
                self.allocated_capacity += 1;
                
                // Update available resource counters
                self.available_compute_units -= capabilities.compute_units.unwrap_or(0);
                self.available_memory_gb -= capabilities.memory_gb.unwrap_or(0.0);
                self.available_storage_gb -= capabilities.storage_gb.unwrap_or(0.0);
                self.available_bandwidth_gbps -= capabilities.bandwidth_gbps.unwrap_or(0.0);
                
                // Add connection to pool
                let mut pool = match self.connection_pool.write() {
                    Ok(pool) => pool,
                    Err(e) => {
                        log::error!("Failed to acquire connection pool lock: {}", e);
                        return None;
                    }
                };
                pool.add_connection(device.id().to_string(), device.id().to_string());
                
                return Some(device.clone());
            }
        }
        
        None
    }
    
    /// Releases a device back to the pool
    /// 
    /// This method releases a device back to the pool by its allocation ID, updating capacity counters.
    /// 
    /// # Parameters
    /// 
    /// - `allocation_id`: The ID of the allocation to release
    /// 
    /// # Returns
    /// 
    /// `true` if the device was successfully released, `false` otherwise
    pub fn release(&mut self, allocation_id: &str) -> bool {
        // Find the allocated device by allocation ID
        for device in self.devices.values() {
            if let Some(current_allocation) = device.get_allocation_id() {
                if current_allocation == allocation_id {
                    // Get device capabilities
                    let capabilities = device.capabilities();
                    
                    // Note: In a real implementation, we'd need to modify the device
                    // to mark it as released. This is simplified for demonstration.
                    self.allocated_capacity -= 1;
                    self.available_capacity += 1;
                    
                    // Update available resource counters
                    self.available_compute_units += capabilities.compute_units.unwrap_or(0);
                    self.available_memory_gb += capabilities.memory_gb.unwrap_or(0.0);
                    self.available_storage_gb += capabilities.storage_gb.unwrap_or(0.0);
                    self.available_bandwidth_gbps += capabilities.bandwidth_gbps.unwrap_or(0.0);
                    
                    // Remove connection from pool
                    match self.connection_pool.write() {
                        Ok(mut pool) => {
                            pool.remove_connection(device.id());
                        }
                        Err(e) => {
                            log::error!("Failed to acquire connection pool lock for removal: {}", e);
                            // Continue with release even if we can't update the pool
                        }
                    }
                    
                    return true;
                }
            }
        }
        
        false
    }
    
    /// Gets the current status of the pool
    /// 
    /// This method returns a RiResourcePoolStatus struct containing information about the pool's
    /// capacity, allocation, and utilization.
    /// 
    /// # Returns
    /// 
    /// A `RiResourcePoolStatus` struct with the current pool status
    pub fn get_status(&self) -> super::RiResourcePoolStatus {
        super::RiResourcePoolStatus {
            total_capacity: self.total_capacity,
            available_capacity: self.available_capacity,
            allocated_capacity: self.allocated_capacity,
            pending_requests: self.pending_requests,
            utilization_rate: if self.total_capacity > 0 {
                (self.allocated_capacity as f64 / self.total_capacity as f64) * 100.0
            } else {
                0.0
            },
        }
    }
    
    /// Gets the name of the pool
    /// 
    /// # Returns
    /// 
    /// The pool name as a string slice
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }
    
    /// Gets the device type of the pool
    /// 
    /// # Returns
    /// 
    /// The device type as a `RiDeviceType` enum
    #[inline]
    pub fn device_type(&self) -> RiDeviceType {
        self.device_type
    }
    
    /// Gets all devices in the pool
    /// 
    /// # Returns
    /// 
    /// A vector of `Arc<RiDevice>` containing all devices in the pool
    #[inline]
    pub fn get_devices(&self) -> Vec<Arc<RiDevice>> {
        self.devices.values().cloned().collect()
    }
    
    /// Gets available devices in the pool
    /// 
    /// # Returns
    /// 
    /// A vector of `Arc<RiDevice>` containing only available devices
    pub fn get_available_devices(&self) -> Vec<Arc<RiDevice>> {
        self.devices.values()
            .filter(|device| device.is_available())
            .cloned()
            .collect()
    }
    
    /// Gets allocated devices in the pool
    /// 
    /// # Returns
    /// 
    /// A vector of `Arc<RiDevice>` containing only allocated devices
    pub fn get_allocated_devices(&self) -> Vec<Arc<RiDevice>> {
        self.devices.values()
            .filter(|device| device.is_allocated())
            .cloned()
            .collect()
    }
    
    /// Checks if the pool has available capacity
    /// 
    /// # Returns
    /// 
    /// `true` if the pool has available devices, `false` otherwise
    #[inline]
    pub fn has_available_capacity(&self) -> bool {
        self.available_capacity > 0
    }
    
    /// Gets the utilization rate of the pool (0.0 - 1.0)
    /// 
    /// # Returns
    /// 
    /// The utilization rate as a floating-point number between 0.0 and 1.0
    #[inline]
    pub fn utilization_rate(&self) -> f64 {
        if self.total_capacity > 0 {
            self.allocated_capacity as f64 / self.total_capacity as f64
        } else {
            0.0
        }
    }
    
    /// Checks if the pool is healthy
    /// 
    /// A pool is considered healthy if it has available devices or allocated devices.
    /// 
    /// # Returns
    /// 
    /// `true` if the pool is healthy, `false` otherwise
    pub fn is_healthy(&self) -> bool {
        self.available_capacity > 0 || self.allocated_capacity > 0
    }
    
    /// Gets comprehensive statistics for the pool
    /// 
    /// This method calculates and returns comprehensive statistics for the pool, including
    /// device counts, utilization, total compute units, memory, storage, bandwidth, and average health score.
    /// 
    /// # Returns
    /// 
    /// A `RiResourcePoolStatistics` struct with comprehensive pool statistics
    pub fn get_statistics(&self) -> RiResourcePoolStatistics {
        let devices = self.get_devices();
        let available_devices = self.get_available_devices();
        let allocated_devices = self.get_allocated_devices();

        // Calculate total compute units across all devices
        let total_compute_units: usize = devices.iter()
            .filter_map(|d| d.capabilities().compute_units)
            .sum();

        // Calculate total memory across all devices
        let total_memory_gb: f64 = devices.iter()
            .filter_map(|d| d.capabilities().memory_gb)
            .sum();

        // Calculate total storage across all devices
        let total_storage_gb: f64 = devices.iter()
            .filter_map(|d| d.capabilities().storage_gb)
            .sum();

        // Calculate total bandwidth across all devices
        let total_bandwidth_gbps: f64 = devices.iter()
            .filter_map(|d| d.capabilities().bandwidth_gbps)
            .sum();

        // Calculate average health score across all devices
        let average_health_score: f64 = if !devices.is_empty() {
            devices.iter()
                .map(|d| d.health_score() as f64)
                .sum::<f64>() / devices.len() as f64
        } else {
            0.0
        };

        // Get connection pool statistics
        let connection_pool_stats = match self.connection_pool.read() {
            Ok(pool) => Some(pool.get_statistics()),
            Err(e) => {
                log::error!("Failed to acquire connection pool read lock: {}", e);
                None
            }
        };
        
        // Calculate device status distribution
        let mut status_distribution = FxHashMap::with_capacity(4);
        for device in &devices {
            *status_distribution.entry(device.status()).or_insert(0) += 1;
        }
        
        // Calculate average health metrics
        let mut total_response_time_ms = 0.0;
        let mut total_network_latency_ms = 0.0;
        let mut total_disk_iops = 0.0;
        let mut total_battery_level_percent = 0.0;
        let mut total_cpu_usage_percent = 0.0;
        let mut total_memory_usage_percent = 0.0;
        let mut total_temperature_celsius = 0.0;
        let mut total_error_count = 0u32;
        let mut total_throughput = 0.0;
        let mut total_uptime_seconds = 0.0;
        
        for device in &devices {
            let health_metrics = device.health_metrics();
            total_response_time_ms += health_metrics.response_time_ms;
            total_network_latency_ms += health_metrics.network_latency_ms;
            total_disk_iops += health_metrics.disk_iops as f64;
            total_battery_level_percent += health_metrics.battery_level_percent;
            total_cpu_usage_percent += health_metrics.cpu_usage_percent;
            total_memory_usage_percent += health_metrics.memory_usage_percent;
            total_temperature_celsius += health_metrics.temperature_celsius;
            total_error_count += health_metrics.error_count;
            total_throughput += health_metrics.throughput as f64;
            total_uptime_seconds += health_metrics.uptime_seconds as f64;
        }
        
        let device_count = devices.len() as f64;
        
        RiResourcePoolStatistics {
            total_devices: devices.len(),
            available_devices: available_devices.len(),
            allocated_devices: allocated_devices.len(),
            utilization_rate: self.utilization_rate(),
            total_compute_units,
            total_memory_gb,
            total_storage_gb,
            total_bandwidth_gbps,
            average_health_score,
            device_type: self.device_type,
            connection_pool_stats,
            
            status_distribution,
            average_response_time_ms: if device_count > 0.0 { total_response_time_ms / device_count } else { 0.0 },
            average_network_latency_ms: if device_count > 0.0 { total_network_latency_ms / device_count } else { 0.0 },
            average_disk_iops: if device_count > 0.0 { total_disk_iops / device_count } else { 0.0 },
            average_battery_level_percent: if device_count > 0.0 { total_battery_level_percent / device_count } else { 0.0 },
            average_cpu_usage_percent: if device_count > 0.0 { total_cpu_usage_percent / device_count } else { 0.0 },
            average_memory_usage_percent: if device_count > 0.0 { total_memory_usage_percent / device_count } else { 0.0 },
            average_temperature_celsius: if device_count > 0.0 { total_temperature_celsius / device_count } else { 0.0 },
            total_error_count,
            average_throughput: if device_count > 0.0 { total_throughput / device_count } else { 0.0 },
            average_uptime_seconds: if device_count > 0.0 { total_uptime_seconds / device_count } else { 0.0 },
        }
    }
}

/// Connection pool for managing device connections with lifecycle and health monitoring
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct RiConnectionPool {
    /// Active connections with their metadata
    connections: FxHashMap<String, RiConnectionInfo>,
    /// Maximum number of connections allowed
    max_connections: usize,
    /// Connection timeout duration
    connection_timeout: Duration,
    /// Health check interval
    health_check_interval: Duration,
    /// Last health check timestamp (seconds since Unix epoch)
    last_health_check_secs: u64,
    /// Number of active connections
    pub active_connections: usize,
    /// Number of failed connections
    pub failed_connections: usize,
    /// Total number of errors
    pub total_errors: usize,
}

/// Connection information for tracking individual connections
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiConnectionInfo {
    /// Connection ID
    pub connection_id: String,
    /// Device ID this connection is associated with
    pub device_id: String,
    /// Remote address or endpoint
    pub address: String,
    /// Connection establishment timestamp (seconds since Unix epoch)
    pub established_at_secs: u64,
    /// Last activity timestamp (seconds since Unix epoch)
    pub last_activity_secs: u64,
    /// Connection state
    pub state: RiConnectionState,
    /// Connection health metrics
    pub health_metrics: RiConnectionHealthMetrics,
}

/// Connection state enumeration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RiConnectionState {
    /// Connection is establishing
    Connecting,
    /// Connection is active and healthy
    Active,
    /// Connection is idle (no recent activity)
    Idle,
    /// Connection is unhealthy
    Unhealthy,
    /// Connection is being closed
    Closing,
    /// Connection is closed
    Closed,
}

/// Connection health metrics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RiConnectionHealthMetrics {
    /// Number of successful operations
    pub successful_operations: u64,
    /// Number of failed operations
    pub failed_operations: u64,
    /// Average response time in milliseconds
    pub average_response_time_ms: f64,
    /// Last error timestamp (seconds since Unix epoch)
    pub last_error_secs: Option<u64>,
    /// Connection uptime percentage
    pub uptime_percentage: f64,
}

#[allow(dead_code)]
impl RiConnectionPool {
    /// Creates a new connection pool
    pub fn new(max_connections: usize, connection_timeout: Duration, health_check_interval: Duration) -> Self {
        Self {
            connections: FxHashMap::with_capacity(max_connections),
            max_connections,
            connection_timeout,
            health_check_interval,
            last_health_check_secs: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or(Duration::from_secs(0))
                .as_secs(),
            active_connections: 0,
            failed_connections: 0,
            total_errors: 0,
        }
    }
    
    /// Adds a new connection to the pool
    pub fn add_connection(&mut self, device_id: String, address: String) {
        let connection_info = RiConnectionInfo {
            connection_id: device_id.clone(),
            device_id: device_id.clone(),
            address,
            established_at_secs: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            last_activity_secs: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            state: RiConnectionState::Active,
            health_metrics: RiConnectionHealthMetrics::default(),
        };
        
        self.connections.insert(device_id, connection_info);
        self.active_connections += 1;
    }
    
    /// Removes a connection from the pool
    pub fn remove_connection(&mut self, connection_id: &str) -> bool {
        self.connections.remove(connection_id).is_some()
    }
    
    /// Gets connection information
    pub fn get_connection(&self, connection_id: &str) -> Option<&RiConnectionInfo> {
        self.connections.get(connection_id)
    }
    
    /// Updates connection activity
    pub fn update_activity(&mut self, connection_id: &str) -> bool {
        if let Some(connection) = self.connections.get_mut(connection_id) {
            connection.last_activity_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or(Duration::from_secs(0))
                .as_secs();
            if connection.state == RiConnectionState::Idle {
                connection.state = RiConnectionState::Active;
            }
            true
        } else {
            false
        }
    }
    
    /// Updates connection health metrics
    pub fn update_health_metrics(&mut self, connection_id: &str, success: bool, response_time_ms: f64) -> bool {
        if let Some(connection) = self.connections.get_mut(connection_id) {
            if success {
                connection.health_metrics.successful_operations += 1;
            } else {
                connection.health_metrics.failed_operations += 1;
                connection.health_metrics.last_error_secs = Some(
                    std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or(Duration::from_secs(0))
                        .as_secs()
                );
            }
            
            // Update average response time
            let total_ops = connection.health_metrics.successful_operations + connection.health_metrics.failed_operations;
            connection.health_metrics.average_response_time_ms = 
                (connection.health_metrics.average_response_time_ms * (total_ops - 1) as f64 + response_time_ms) / total_ops as f64;
            
            // Update uptime percentage
            let total_ops = connection.health_metrics.successful_operations + connection.health_metrics.failed_operations;
            connection.health_metrics.uptime_percentage = 
                (connection.health_metrics.successful_operations as f64 / total_ops as f64) * 100.0;
            
            true
        } else {
            false
        }
    }
    
    /// Performs health check on all connections
    pub fn perform_health_check(&mut self) {
        self.last_health_check_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or(Duration::from_secs(0))
            .as_secs();
        
        for connection in self.connections.values_mut() {
            // Check for idle connections
            let current_time = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            let elapsed_secs = current_time.saturating_sub(connection.last_activity_secs);
            
            if connection.state == RiConnectionState::Active && elapsed_secs > self.connection_timeout.as_secs() {
                connection.state = RiConnectionState::Idle;
            }
            
            // Check for unhealthy connections
            if connection.health_metrics.uptime_percentage < 90.0 {
                connection.state = RiConnectionState::Unhealthy;
            } else if let Some(last_error_secs) = connection.health_metrics.last_error_secs {
                let current_secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or(Duration::from_secs(0))
                    .as_secs();
                if current_secs.saturating_sub(last_error_secs) < 60 {
                    connection.state = RiConnectionState::Unhealthy;
                }
            }
            
            // Close connections that have been unhealthy for too long
            if connection.state == RiConnectionState::Unhealthy &&
               connection.health_metrics.failed_operations > 10 {
                connection.state = RiConnectionState::Closing;
            }
        }
        
        // Remove closed connections
        self.connections.retain(|_, conn| conn.state != RiConnectionState::Closed);
    }
    
    /// Gets the number of active connections
    pub fn active_connections(&self) -> usize {
        self.connections.values()
            .filter(|conn| conn.state == RiConnectionState::Active)
            .count()
    }
    
    /// Gets the number of idle connections
    pub fn idle_connections(&self) -> usize {
        self.connections.values()
            .filter(|conn| conn.state == RiConnectionState::Idle)
            .count()
    }
    
    /// Gets the number of unhealthy connections
    pub fn unhealthy_connections(&self) -> usize {
        self.connections.values()
            .filter(|conn| conn.state == RiConnectionState::Unhealthy)
            .count()
    }
    
    /// Gets overall connection pool statistics
    pub fn get_statistics(&self) -> RiConnectionPoolStatistics {
        let total_connections = self.connections.len();
        let active_connections = self.active_connections();
        let idle_connections = self.idle_connections();
        let unhealthy_connections = self.unhealthy_connections();
        
        let total_successful_ops: u64 = self.connections.values()
            .map(|conn| conn.health_metrics.successful_operations)
            .sum();
        let total_failed_ops: u64 = self.connections.values()
            .map(|conn| conn.health_metrics.failed_operations)
            .sum();
        
        let avg_response_time = if !self.connections.is_empty() {
            let total_response_time: f64 = self.connections.values()
                .map(|conn| conn.health_metrics.average_response_time_ms)
                .sum();
            total_response_time / self.connections.len() as f64
        } else {
            0.0
        };
        
        let last_health_check_secs = self.last_health_check_secs;
        
        RiConnectionPoolStatistics {
            total_connections,
            active_connections,
            idle_connections,
            unhealthy_connections,
            available_slots: self.max_connections.saturating_sub(total_connections),
            total_successful_operations: total_successful_ops,
            total_failed_operations: total_failed_ops,
            average_response_time_ms: avg_response_time,
            health_check_interval_secs: self.health_check_interval.as_secs(),
            last_health_check_secs,
        }
    }
}

/// Connection pool statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiConnectionPoolStatistics {
    /// Total number of connections
    pub total_connections: usize,
    /// Number of active connections
    pub active_connections: usize,
    /// Number of idle connections
    pub idle_connections: usize,
    /// Number of unhealthy connections
    pub unhealthy_connections: usize,
    /// Number of available connection slots
    pub available_slots: usize,
    /// Total successful operations across all connections
    pub total_successful_operations: u64,
    /// Total failed operations across all connections
    pub total_failed_operations: u64,
    /// Average response time across all connections
    pub average_response_time_ms: f64,
    /// Health check interval in seconds
    pub health_check_interval_secs: u64,
    /// Last health check timestamp (seconds since Unix epoch)
    pub last_health_check_secs: u64,
}

impl Default for RiConnectionPoolStatistics {
    fn default() -> Self {
        Self {
            total_connections: 0,
            active_connections: 0,
            idle_connections: 0,
            unhealthy_connections: 0,
            available_slots: 0,
            total_successful_operations: 0,
            total_failed_operations: 0,
            average_response_time_ms: 0.0,
            health_check_interval_secs: 0,
            last_health_check_secs: 0,
        }
    }
}

/// Resource pool statistics structure
/// 
/// This struct contains comprehensive statistics for a resource pool, including device counts,
/// utilization, total resources, and detailed health metrics.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiResourcePoolStatistics {
    /// Total number of devices in the pool
    pub total_devices: usize,
    /// Number of available devices in the pool
    pub available_devices: usize,
    /// Number of allocated devices in the pool
    pub allocated_devices: usize,
    /// Utilization rate of the pool (0.0 - 1.0)
    pub utilization_rate: f64,
    /// Total compute units across all devices
    pub total_compute_units: usize,
    /// Total memory in gigabytes across all devices
    pub total_memory_gb: f64,
    /// Total storage in gigabytes across all devices
    pub total_storage_gb: f64,
    /// Total bandwidth in gigabits per second across all devices
    pub total_bandwidth_gbps: f64,
    /// Average health score across all devices
    pub average_health_score: f64,
    /// Type of devices in the pool
    pub device_type: RiDeviceType,
    /// Connection pool statistics
    pub connection_pool_stats: Option<RiConnectionPoolStatistics>,
    
    /// Device status distribution
    pub status_distribution: FxHashMap<RiDeviceStatus, usize>,
    /// Average response time in milliseconds
    pub average_response_time_ms: f64,
    /// Average network latency in milliseconds (for network devices)
    pub average_network_latency_ms: f64,
    /// Average disk IOPS (for storage devices)
    pub average_disk_iops: f64,
    /// Average battery level percentage (for battery-powered devices)
    pub average_battery_level_percent: f64,
    /// Average CPU usage percentage
    pub average_cpu_usage_percent: f64,
    /// Average memory usage percentage
    pub average_memory_usage_percent: f64,
    /// Average temperature in Celsius
    pub average_temperature_celsius: f64,
    /// Total error count across all devices
    pub total_error_count: u32,
    /// Average throughput across all devices
    pub average_throughput: f64,
    /// Average uptime in seconds
    pub average_uptime_seconds: f64,
}

impl Default for RiResourcePoolStatistics {
    fn default() -> Self {
        Self {
            total_devices: 0,
            available_devices: 0,
            allocated_devices: 0,
            utilization_rate: 0.0,
            total_compute_units: 0,
            total_memory_gb: 0.0,
            total_storage_gb: 0.0,
            total_bandwidth_gbps: 0.0,
            average_health_score: 0.0,
            device_type: RiDeviceType::CPU,
            connection_pool_stats: None,
            status_distribution: FxHashMap::with_capacity(4),
            average_response_time_ms: 0.0,
            average_network_latency_ms: 0.0,
            average_disk_iops: 0.0,
            average_battery_level_percent: 0.0,
            average_cpu_usage_percent: 0.0,
            average_memory_usage_percent: 0.0,
            average_temperature_celsius: 0.0,
            total_error_count: 0,
            average_throughput: 0.0,
            average_uptime_seconds: 0.0,
        }
    }
}

/// Resource pool manager for managing multiple resource pools
/// 
/// This struct manages multiple resource pools, providing methods for creating, retrieving,
/// and removing pools, as well as getting overall statistics.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiResourcePoolManager {
    /// Map of pool names to resource pools
    pools: FxHashMap<String, Arc<RiResourcePool>>,
}

impl Default for RiResourcePoolManager {
    fn default() -> Self {
        Self::new()
    }
}

impl RiResourcePoolManager {
    /// Creates a new resource pool manager
    /// 
    /// # Returns
    /// 
    /// A new `RiResourcePoolManager` instance
    pub fn new() -> Self {
        Self {
            pools: FxHashMap::with_capacity(8),
        }
    }
    
    /// Creates a new resource pool
    /// 
    /// This method creates a new resource pool with the given configuration and adds it to the manager.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The configuration for the new resource pool
    /// 
    /// # Returns
    /// 
    /// An `Arc<RiResourcePool>` to the newly created pool
    pub fn create_pool(&mut self, config: RiResourcePoolConfig) -> Arc<RiResourcePool> {
        let pool = Arc::new(RiResourcePool::new(config));
        self.pools.insert(pool.name().to_string(), pool.clone());
        pool
    }
    
    /// Gets a resource pool by name
    /// 
    /// # Parameters
    /// 
    /// - `name`: The name of the resource pool to get
    /// 
    /// # Returns
    /// 
    /// An `Option<Arc<RiResourcePool>>` containing the pool if found, `None` otherwise
    pub fn get_pool(&self, name: &str) -> Option<Arc<RiResourcePool>> {
        self.pools.get(name).cloned()
    }
    
    /// Removes a resource pool by name
    /// 
    /// # Parameters
    /// 
    /// - `name`: The name of the resource pool to remove
    /// 
    /// # Returns
    /// 
    /// An `Option<Arc<RiResourcePool>>` containing the removed pool if found, `None` otherwise
    pub fn remove_pool(&mut self, name: &str) -> Option<Arc<RiResourcePool>> {
        self.pools.remove(name)
    }
    
    /// Gets all resource pools
    /// 
    /// # Returns
    /// 
    /// A vector of `Arc<RiResourcePool>` containing all resource pools
    pub fn get_all_pools(&self) -> Vec<Arc<RiResourcePool>> {
        self.pools.values().cloned().collect()
    }
    
    /// Gets all resource pools of a specific device type
    /// 
    /// # Parameters
    /// 
    /// - `device_type`: The device type to filter pools by
    /// 
    /// # Returns
    /// 
    /// A vector of `Arc<RiResourcePool>` containing all pools of the specified device type
    pub fn get_pools_by_type(&self, device_type: RiDeviceType) -> Vec<Arc<RiResourcePool>> {
        self.pools.values()
            .filter(|pool| pool.device_type() == device_type)
            .cloned()
            .collect()
    }
    
    /// Gets overall statistics for all resource pools
    /// 
    /// This method calculates and returns overall statistics for all resource pools, including
    /// total devices, utilization, and total resources across all pools.
    /// 
    /// # Returns
    /// 
    /// A `RiResourcePoolStatistics` struct with overall statistics for all pools
    pub fn get_overall_statistics(&self) -> RiResourcePoolStatistics {
        let pools = self.get_all_pools();
        
        // Calculate total devices and allocated devices across all pools
        let total_devices: usize = pools.iter().map(|p| p.get_statistics().total_devices).sum();
        let allocated_devices: usize = pools.iter().map(|p| p.get_statistics().allocated_devices).sum();
        
        // Calculate total compute units across all devices in all pools
        let total_compute_units: usize = pools.iter()
            .flat_map(|p| p.get_devices())
            .filter_map(|d| d.capabilities().compute_units)
            .sum();
        
        // Calculate total memory across all devices in all pools
        let total_memory_gb: f64 = pools.iter()
            .flat_map(|p| p.get_devices())
            .filter_map(|d| d.capabilities().memory_gb)
            .sum();
        
        // Calculate total storage across all devices in all pools
        let total_storage_gb: f64 = pools.iter()
            .flat_map(|p| p.get_devices())
            .filter_map(|d| d.capabilities().storage_gb)
            .sum();
        
        // Calculate total bandwidth across all devices in all pools
        let total_bandwidth_gbps: f64 = pools.iter()
            .flat_map(|p| p.get_devices())
            .filter_map(|d| d.capabilities().bandwidth_gbps)
            .sum();
        
        // Calculate overall utilization rate
        let overall_utilization = if total_devices > 0 {
            allocated_devices as f64 / total_devices as f64
        } else {
            0.0
        };
        
        // Calculate average health score across all pools
        let total_health_score: f64 = pools.iter()
            .map(|p| p.get_statistics().average_health_score)
            .sum();
        let average_health_score = if !pools.is_empty() {
            total_health_score / pools.len() as f64
        } else {
            0.0
        };
        
        RiResourcePoolStatistics {
            total_devices,
            available_devices: total_devices - allocated_devices,
            allocated_devices,
            utilization_rate: overall_utilization,
            total_compute_units,
            total_memory_gb,
            total_storage_gb,
            total_bandwidth_gbps,
            average_health_score,
            device_type: RiDeviceType::Custom, // Multiple device types across pools
            connection_pool_stats: None, // No aggregated connection stats at manager level
            
            status_distribution: FxHashMap::with_capacity(4),
            average_response_time_ms: 0.0,
            average_network_latency_ms: 0.0,
            average_disk_iops: 0.0,
            average_battery_level_percent: 0.0,
            average_cpu_usage_percent: 0.0,
            average_memory_usage_percent: 0.0,
            average_temperature_celsius: 0.0,
            total_error_count: 0,
            average_throughput: 0.0,
            average_uptime_seconds: 0.0,
        }
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiResourcePoolConfig {
    #[new]
    fn py_new() -> Self {
        Self::default()
    }
    
    #[staticmethod]
    fn py_new_with_name(name: String, device_type: RiDeviceType) -> Self {
        Self {
            name,
            device_type,
            max_concurrent_allocations: 10,
            allocation_timeout_secs: 60,
            health_check_interval_secs: 30,
        }
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiResourcePoolStatistics {
    #[new]
    fn py_new() -> Self {
        Self::default()
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiResourcePoolManager {
    #[new]
    fn py_new() -> Self {
        Self::new()
    }
}