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
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
//! 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)]

//! # Device Core Structures
//! 
//! This file defines the core data structures for device management in Ri, including device types,
//! capabilities, status, health metrics, and the device representation itself. These structures form
//! the foundation for device discovery, scheduling, and management.
//! 
//! ## Key Components
//! 
//! - **RiDeviceType**: Enum defining supported device types
//! - **RiDeviceCapabilities**: Device capabilities structure
//! - **RiDeviceStatus**: Enum defining device statuses
//! - **RiDeviceHealthMetrics**: Device health metrics structure
//! - **RiDevice**: Main device representation with status, capabilities, and health metrics
//! 
//! ## Design Principles
//! 
//! 1. **Comprehensive Coverage**: Covers all aspects of device management
//! 2. **Flexibility**: Supports custom device types and capabilities
//! 3. **Health Monitoring**: Built-in health metrics for device monitoring
//! 4. **Resource Management**: Capabilities structure for resource allocation
//! 5. **Status Tracking**: Clear status definitions for device lifecycle management
//! 6. **Serialization Support**: All structures support serialization/deserialization
//! 7. **Builder Pattern**: Capabilities support a fluent builder API
//! 8. **Health Scoring**: Built-in health scoring for device selection
//! 
//! ## Usage
//! 
//! ```rust
//! use ri::device::{RiDevice, RiDeviceType, RiDeviceCapabilities};
//! 
//! // Create a new device
//! let mut device = RiDevice::new("server-1".to_string(), RiDeviceType::CPU);
//! 
//! // Configure device capabilities
//! let capabilities = RiDeviceCapabilities::new()
//!     .with_compute_units(16)
//!     .with_memory_gb(32.0)
//!     .with_storage_gb(1024.0)
//!     .with_bandwidth_gbps(10.0);
//! 
//! // Set device capabilities and status
//! device = device.with_capabilities(capabilities);
//! device.set_status(ri::device::RiDeviceStatus::Available);
//! 
//! // Check if device meets requirements
//! let requirements = RiDeviceCapabilities::new().with_compute_units(8);
//! if device.capabilities().meets_requirements(&requirements) {
//!     println!("Device meets requirements");
//! }
//! ```

use serde::{Serialize, Deserialize};
use std::collections::HashMap as FxHashMap;
use uuid::Uuid;

#[cfg(feature = "pyo3")]
use pyo3::prelude::*;

/// Configuration for device control module
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDeviceControlConfig {
    /// Enable CPU discovery
    pub enable_cpu_discovery: bool,
    /// Enable GPU discovery  
    pub enable_gpu_discovery: bool,
    /// Enable memory discovery
    pub enable_memory_discovery: bool,
    /// Enable storage discovery
    pub enable_storage_discovery: bool,
    /// Enable network discovery
    pub enable_network_discovery: bool,
    /// Network discovery timeout in seconds
    pub discovery_timeout_secs: u64,
    /// Maximum number of devices to discover per type
    pub max_devices_per_type: usize,
}

impl Default for RiDeviceControlConfig {
    fn default() -> Self {
        Self {
            enable_cpu_discovery: true,
            enable_gpu_discovery: true,
            enable_memory_discovery: true,
            enable_storage_discovery: true,
            enable_network_discovery: true,
            discovery_timeout_secs: 30,
            max_devices_per_type: 100,
        }
    }
}

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

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

/// Configuration for device module
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDeviceConfig {
    /// Enable CPU discovery
    pub enable_cpu_discovery: bool,
    /// Enable GPU discovery  
    pub enable_gpu_discovery: bool,
    /// Enable memory discovery
    pub enable_memory_discovery: bool,
    /// Enable storage discovery
    pub enable_storage_discovery: bool,
    /// Enable network discovery
    pub enable_network_discovery: bool,
    /// Network discovery timeout in seconds
    pub discovery_timeout_secs: u64,
    /// Maximum number of devices to discover per type
    pub max_devices_per_type: usize,
}

impl Default for RiDeviceConfig {
    fn default() -> Self {
        Self {
            enable_cpu_discovery: true,
            enable_gpu_discovery: true,
            enable_memory_discovery: true,
            enable_storage_discovery: true,
            enable_network_discovery: true,
            discovery_timeout_secs: 30,
            max_devices_per_type: 100,
        }
    }
}

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

/// Network device information for remote device discovery
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiNetworkDeviceInfo {
    /// Unique device identifier
    pub id: String,
    /// Device type (CPU, GPU, Memory, Storage, Network)
    pub device_type: String,
    /// Source system identifier
    pub source: String,
    /// Number of compute units (for CPU/GPU)
    pub compute_units: Option<usize>,
    /// Memory capacity in GB
    pub memory_gb: Option<f64>,
    /// Storage capacity in GB
    pub storage_gb: Option<f64>,
    /// Bandwidth in Gbps
    pub bandwidth_gbps: Option<f64>,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiNetworkDeviceInfo {
    #[new]
    fn py_new(id: String, device_type: String, source: String) -> Self {
        Self {
            id,
            device_type,
            source,
            compute_units: None,
            memory_gb: None,
            storage_gb: None,
            bandwidth_gbps: None,
        }
    }
    
    #[staticmethod]
    fn default_info(id: String, device_type: String, source: String) -> Self {
        Self::py_new(id, device_type, source)
    }
}

/// Device type enumeration
/// 
/// This enum defines the different types of devices supported by Ri. Each device type
/// has specific capabilities and use cases in the system.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub enum RiDeviceType {
    /// Central Processing Unit - General purpose computing
    CPU,
    /// Graphics Processing Unit - Parallel computing and graphics
    GPU,
    /// Memory - RAM and other memory devices
    Memory,
    /// Storage - Hard drives, SSDs, and other storage devices
    Storage,
    /// Network - Network interfaces and devices
    Network,
    /// Sensor - Devices that collect data from the environment
    Sensor,
    /// Actuator - Devices that perform physical actions
    Actuator,
    /// Custom - User-defined device types
    Custom,
}

impl std::fmt::Display for RiDeviceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RiDeviceType::CPU => write!(f, "CPU"),
            RiDeviceType::GPU => write!(f, "GPU"),
            RiDeviceType::Memory => write!(f, "Memory"),
            RiDeviceType::Storage => write!(f, "Storage"),
            RiDeviceType::Network => write!(f, "Network"),
            RiDeviceType::Sensor => write!(f, "Sensor"),
            RiDeviceType::Actuator => write!(f, "Actuator"),
            RiDeviceType::Custom => write!(f, "Custom"),
        }
    }
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiDeviceType {
    #[staticmethod]
    fn new_cpu() -> Self {
        RiDeviceType::CPU
    }
    
    #[staticmethod]
    fn new_gpu() -> Self {
        RiDeviceType::GPU
    }
    
    #[staticmethod]
    fn new_memory() -> Self {
        RiDeviceType::Memory
    }
    
    #[staticmethod]
    fn new_storage() -> Self {
        RiDeviceType::Storage
    }
    
    #[staticmethod]
    fn new_network() -> Self {
        RiDeviceType::Network
    }
    
    #[staticmethod]
    fn new_sensor() -> Self {
        RiDeviceType::Sensor
    }
    
    #[staticmethod]
    fn new_actuator() -> Self {
        RiDeviceType::Actuator
    }
    
    #[staticmethod]
    fn new_custom() -> Self {
        RiDeviceType::Custom
    }
    
    fn __str__(&self) -> String {
        self.to_string()
    }
}

/// Device capabilities structure
/// 
/// This struct defines the capabilities of a device, including compute power, memory, storage,
/// bandwidth, and custom capabilities. It supports a fluent builder API for easy configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiDeviceCapabilities {
    /// Number of compute units (e.g., CPU cores, GPU CUDA cores)
    pub compute_units: Option<usize>,
    /// Memory capacity in gigabytes
    pub memory_gb: Option<f64>,
    /// Storage capacity in gigabytes
    pub storage_gb: Option<f64>,
    /// Bandwidth in gigabits per second
    pub bandwidth_gbps: Option<f64>,
    /// Custom capabilities as key-value pairs
    pub custom_capabilities: FxHashMap<String, String>,
}

impl Default for RiDeviceCapabilities {
    /// Returns the default device capabilities (empty capabilities)
    fn default() -> Self {
        Self::new()
    }
}

impl RiDeviceCapabilities {
    /// Creates a new empty device capabilities structure
    /// 
    /// # Returns
    /// 
    /// A new `RiDeviceCapabilities` instance with no capabilities set
    pub fn new() -> Self {
        Self {
            compute_units: None,
            memory_gb: None,
            storage_gb: None,
            bandwidth_gbps: None,
            custom_capabilities: FxHashMap::default(),
        }
    }
    
    /// Sets the number of compute units
    /// 
    /// # Parameters
    /// 
    /// - `units`: Number of compute units
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceCapabilities` instance
    pub fn with_compute_units(mut self, units: usize) -> Self {
        self.compute_units = Some(units);
        self
    }
    
    /// Sets the memory capacity in gigabytes
    /// 
    /// # Parameters
    /// 
    /// - `memory`: Memory capacity in GB
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceCapabilities` instance
    pub fn with_memory_gb(mut self, memory: f64) -> Self {
        self.memory_gb = Some(memory);
        self
    }
    
    /// Sets the storage capacity in gigabytes
    /// 
    /// # Parameters
    /// 
    /// - `storage`: Storage capacity in GB
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceCapabilities` instance
    pub fn with_storage_gb(mut self, storage: f64) -> Self {
        self.storage_gb = Some(storage);
        self
    }
    
    /// Sets the bandwidth in gigabits per second
    /// 
    /// # Parameters
    /// 
    /// - `bandwidth`: Bandwidth in Gbps
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceCapabilities` instance
    pub fn with_bandwidth_gbps(mut self, bandwidth: f64) -> Self {
        self.bandwidth_gbps = Some(bandwidth);
        self
    }
    
    /// Adds a custom capability
    /// 
    /// # Parameters
    /// 
    /// - `key`: Custom capability key
    /// - `value`: Custom capability value
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceCapabilities` instance
    pub fn with_custom_capability(mut self, key: String, value: String) -> Self {
        self.custom_capabilities.insert(key, value);
        self
    }
    
    /// Checks if this device meets the required capabilities
    /// 
    /// This method compares the device's capabilities with the required capabilities and
    /// returns true if all required capabilities are met or exceeded.
    /// 
    /// # Parameters
    /// 
    /// - `requirements`: The required capabilities to check against
    /// 
    /// # Returns
    /// 
    /// `true` if the device meets all requirements, `false` otherwise
    pub fn meets_requirements(&self, requirements: &RiDeviceCapabilities) -> bool {
        // Check compute units requirement
        if let Some(required_units) = requirements.compute_units {
            if let Some(available_units) = self.compute_units {
                if available_units < required_units {
                    return false;
                }
            } else {
                return false; // No compute units available
            }
        }
        
        // Check memory requirement
        if let Some(required_memory) = requirements.memory_gb {
            if let Some(available_memory) = self.memory_gb {
                if available_memory < required_memory {
                    return false;
                }
            } else {
                return false; // No memory available
            }
        }
        
        // Check storage requirement
        if let Some(required_storage) = requirements.storage_gb {
            if let Some(available_storage) = self.storage_gb {
                if available_storage < required_storage {
                    return false;
                }
            } else {
                return false; // No storage available
            }
        }
        
        // Check bandwidth requirement
        if let Some(required_bandwidth) = requirements.bandwidth_gbps {
            if let Some(available_bandwidth) = self.bandwidth_gbps {
                if available_bandwidth < required_bandwidth {
                    return false;
                }
            } else {
                return false; // No bandwidth available
            }
        }
        
        // Check custom capabilities
        for (key, required_value) in &requirements.custom_capabilities {
            match self.custom_capabilities.get(key) {
                Some(available_value) => {
                    // Simple string comparison for now
                    if available_value != required_value {
                        return false;
                    }
                }
                None => return false, // Required capability not available
            }
        }
        
        true
    }
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiDeviceCapabilities {
    #[new]
    fn py_new() -> Self {
        Self::new()
    }
    
    #[staticmethod]
    fn default_capabilities() -> Self {
        Self::default()
    }
    
    #[pyo3(name = "with_compute_units")]
    fn with_compute_units_impl(&self, units: usize) -> Self {
        let mut new = self.clone();
        new.compute_units = Some(units);
        new
    }
    
    #[pyo3(name = "with_memory_gb")]
    fn with_memory_gb_impl(&self, memory: f64) -> Self {
        let mut new = self.clone();
        new.memory_gb = Some(memory);
        new
    }
    
    #[pyo3(name = "with_storage_gb")]
    fn with_storage_gb_impl(&self, storage: f64) -> Self {
        let mut new = self.clone();
        new.storage_gb = Some(storage);
        new
    }
    
    #[pyo3(name = "with_bandwidth_gbps")]
    fn with_bandwidth_gbps_impl(&self, bandwidth: f64) -> Self {
        let mut new = self.clone();
        new.bandwidth_gbps = Some(bandwidth);
        new
    }
    
    #[pyo3(name = "with_custom_capability")]
    fn with_custom_capability_impl(&self, key: String, value: String) -> Self {
        let mut new = self.clone();
        new.custom_capabilities.insert(key, value);
        new
    }
    
    #[pyo3(name = "get_compute_units")]
    fn get_compute_units_impl(&self) -> Option<usize> { 
        self.compute_units 
    }
    
    #[pyo3(name = "get_memory_gb")]
    fn get_memory_gb_impl(&self) -> Option<f64> { 
        self.memory_gb 
    }
    
    #[pyo3(name = "get_storage_gb")]
    fn get_storage_gb_impl(&self) -> Option<f64> { 
        self.storage_gb 
    }
    
    #[pyo3(name = "get_bandwidth_gbps")]
    fn get_bandwidth_gbps_impl(&self) -> Option<f64> { 
        self.bandwidth_gbps 
    }
    
    #[pyo3(name = "get_custom_capabilities")]
    fn get_custom_capabilities_impl(&self) -> FxHashMap<String, String> { 
        self.custom_capabilities.clone() 
    }
    
    #[pyo3(name = "meets_requirements")]
    fn meets_requirements_impl(&self, requirements: &RiDeviceCapabilities) -> bool {
        self.meets_requirements(requirements)
    }
}

/// Device status enumeration
/// 
/// This enum defines the different statuses a device can have during its lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub enum RiDeviceStatus {
    /// Device status is unknown
    Unknown,
    /// Device is available for use
    Available,
    /// Device is currently in use
    Busy,
    /// Device has encountered an error
    Error,
    /// Device is offline or unreachable
    Offline,
    /// Device is under maintenance
    Maintenance,
    /// Device is degraded but still operational
    Degraded,
    /// Device is allocated to a specific task
    Allocated,
}



/// Device health metrics structure
/// 
/// This struct contains health metrics for monitoring device performance and reliability.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiDeviceHealthMetrics {
    /// CPU usage percentage (0-100)
    pub cpu_usage_percent: f64,
    /// Memory usage percentage (0-100)
    pub memory_usage_percent: f64,
    /// Device temperature in Celsius
    pub temperature_celsius: f64,
    /// Number of errors encountered
    pub error_count: u32,
    /// Throughput in operations per second
    pub throughput: u64, // operations per second
    /// Network latency in milliseconds (for network devices)
    pub network_latency_ms: f64,
    /// Disk I/O operations per second (for storage devices)
    pub disk_iops: u64,
    /// Battery level percentage (for battery-powered devices, 0-100)
    pub battery_level_percent: f64,
    /// Response time in milliseconds
    pub response_time_ms: f64,
    /// Uptime in seconds
    pub uptime_seconds: u64,
}

impl Default for RiDeviceHealthMetrics {
    /// Returns default health metrics (all zero values)
    fn default() -> Self {
        Self {
            cpu_usage_percent: 0.0,
            memory_usage_percent: 0.0,
            temperature_celsius: 0.0,
            error_count: 0,
            throughput: 0,
            network_latency_ms: 0.0,
            disk_iops: 0,
            battery_level_percent: 0.0,
            response_time_ms: 0.0,
            uptime_seconds: 0,
        }
    }
}

/// Smart device representation
/// 
/// This struct represents a smart device in the Ri system, including its status, capabilities,
/// health metrics, and lifecycle information.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDevice {
    /// Unique device ID
    id: String,
    /// Device name
    name: String,
    /// Device type
    device_type: RiDeviceType,
    /// Current device status
    status: RiDeviceStatus,
    /// Device capabilities for resource allocation
    capabilities: RiDeviceCapabilities,
    /// Current health metrics
    health_metrics: RiDeviceHealthMetrics,
    /// Physical location of the device (optional)
    location: Option<String>,
    /// Device group (for grouping devices)
    group: Option<String>,
    /// Device tags (for filtering and selection)
    tags: Vec<String>,
    /// Additional metadata as key-value pairs
    metadata: FxHashMap<String, String>,
    /// Last time the device was seen/updated
    last_seen: chrono::DateTime<chrono::Utc>,
    /// ID of the current allocation using this device (if any)
    current_allocation_id: Option<String>,
}

impl RiDevice {
    /// Creates a new device with the given name and type
    /// 
    /// # Parameters
    /// 
    /// - `name`: The name of the device
    /// - `device_type`: The type of the device
    /// 
    /// # Returns
    /// 
    /// A new `RiDevice` instance with default capabilities and health metrics
    pub fn new(name: String, device_type: RiDeviceType) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            name,
            device_type,
            status: RiDeviceStatus::Unknown,
            capabilities: RiDeviceCapabilities::new(),
            health_metrics: RiDeviceHealthMetrics::default(),
            location: None,
            group: None,
            tags: Vec::new(),
            metadata: FxHashMap::default(),
            last_seen: chrono::Utc::now(),
            current_allocation_id: None,
        }
    }
    
    /// Gets the device ID
    /// 
    /// # Returns
    /// 
    /// The device ID as a string slice
    pub fn id(&self) -> &str {
        &self.id
    }
    
    /// Gets the device name
    /// 
    /// # Returns
    /// 
    /// The device name as a string slice
    pub fn name(&self) -> &str {
        &self.name
    }
    
    /// Gets the device type
    /// 
    /// # Returns
    /// 
    /// The device type as a `RiDeviceType` enum
    pub fn device_type(&self) -> RiDeviceType {
        self.device_type
    }
    
    /// Gets the current device status
    /// 
    /// # Returns
    /// 
    /// The device status as a `RiDeviceStatus` enum
    pub fn status(&self) -> RiDeviceStatus {
        self.status
    }
    
    /// Gets a reference to the device capabilities
    /// 
    /// # Returns
    /// 
    /// A reference to the `RiDeviceCapabilities` structure
    pub fn capabilities(&self) -> &RiDeviceCapabilities {
        &self.capabilities
    }
    
    /// Gets a reference to the device health metrics
    /// 
    /// # Returns
    /// 
    /// A reference to the `RiDeviceHealthMetrics` structure
    pub fn health_metrics(&self) -> &RiDeviceHealthMetrics {
        &self.health_metrics
    }
    
    /// Sets the device status and updates the last seen timestamp
    /// 
    /// # Parameters
    /// 
    /// - `status`: The new status to set
    pub fn set_status(&mut self, status: RiDeviceStatus) {
        self.status = status;
        self.last_seen = chrono::Utc::now();
    }
    
    /// Updates the device health metrics and last seen timestamp
    /// 
    /// # Parameters
    /// 
    /// - `metrics`: The new health metrics to set
    pub fn update_health_metrics(&mut self, metrics: RiDeviceHealthMetrics) {
        self.health_metrics = metrics;
        self.last_seen = chrono::Utc::now();
    }
    
    /// Increments the device error count and updates the last seen timestamp
    pub fn increment_error_count(&mut self) {
        self.health_metrics.error_count += 1;
        self.last_seen = chrono::Utc::now();
    }
    
    /// Updates the device throughput and last seen timestamp
    /// 
    /// # Parameters
    /// 
    /// - `throughput`: The new throughput value in operations per second
    pub fn update_throughput(&mut self, throughput: u64) {
        self.health_metrics.throughput = throughput;
        self.last_seen = chrono::Utc::now();
    }
    
    /// Sets the device capabilities using the builder pattern
    /// 
    /// # Parameters
    /// 
    /// - `capabilities`: The new capabilities to set
    /// 
    /// # Returns
    /// 
    /// The updated `RiDevice` instance
    pub fn with_capabilities(mut self, capabilities: RiDeviceCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }
    
    /// Sets the device location
    /// 
    /// # Parameters
    /// 
    /// - `location`: The physical location of the device
    pub fn set_location(&mut self, location: String) {
        self.location = Some(location);
    }
    
    /// Adds a metadata key-value pair to the device
    /// 
    /// # Parameters
    /// 
    /// - `key`: Metadata key
    /// - `value`: Metadata value
    pub fn add_metadata(&mut self, key: String, value: String) {
        self.metadata.insert(key, value);
    }
    
    /// Updates the last seen timestamp to the current time
    pub fn update_last_seen(&mut self) {
        self.last_seen = chrono::Utc::now();
    }
    
    /// Gets the last seen timestamp
    /// 
    /// # Returns
    /// 
    /// The last seen timestamp as a `chrono::DateTime<chrono::Utc>`
    pub fn last_seen(&self) -> chrono::DateTime<chrono::Utc> {
        self.last_seen
    }
    
    /// Checks if the device is available for allocation
    /// 
    /// A device is available if its status is Available and it has no current allocation.
    /// 
    /// # Returns
    /// 
    /// `true` if the device is available, `false` otherwise
    pub fn is_available(&self) -> bool {
        self.status == RiDeviceStatus::Available && self.current_allocation_id.is_none()
    }
    
    /// Checks if the device is currently allocated
    /// 
    /// # Returns
    /// 
    /// `true` if the device is allocated, `false` otherwise
    pub fn is_allocated(&self) -> bool {
        self.current_allocation_id.is_some()
    }
    
    /// Allocates the device to a specific allocation ID
    /// 
    /// This method marks the device as busy and associates it with the given allocation ID.
    /// 
    /// # Parameters
    /// 
    /// - `allocation_id`: The ID of the allocation using this device
    /// 
    /// # Returns
    /// 
    /// `true` if the device was successfully allocated, `false` if it was already in use
    pub fn allocate(&mut self, allocation_id: &str) -> bool {
        if self.is_available() {
            self.current_allocation_id = Some(allocation_id.to_string());
            self.status = RiDeviceStatus::Busy;
            true
        } else {
            false
        }
    }
    
    /// Releases the device from its current allocation
    /// 
    /// This method clears the allocation ID and sets the device status to Available if it was Busy.
    pub fn release(&mut self) {
        self.current_allocation_id = None;
        if self.status == RiDeviceStatus::Busy {
            self.status = RiDeviceStatus::Available;
        }
    }
    
    /// Gets the device group
    /// 
    /// # Returns
    /// 
    /// The device group as an `Option<&str>`
    pub fn group(&self) -> Option<&str> {
        self.group.as_deref()
    }
    
    /// Sets the device group
    /// 
    /// # Parameters
    /// 
    /// - `group`: The new group for the device
    pub fn set_group(&mut self, group: Option<String>) {
        self.group = group;
    }
    
    /// Gets the device tags
    /// 
    /// # Returns
    /// 
    /// A reference to the device tags vector
    pub fn tags(&self) -> &Vec<String> {
        &self.tags
    }
    
    /// Adds a tag to the device
    /// 
    /// # Parameters
    /// 
    /// - `tag`: The tag to add to the device
    pub fn add_tag(&mut self, tag: String) {
        if !self.tags.contains(&tag) {
            self.tags.push(tag);
        }
    }
    
    /// Removes a tag from the device
    /// 
    /// # Parameters
    /// 
    /// - `tag`: The tag to remove from the device
    /// 
    /// # Returns
    /// 
    /// `true` if the tag was removed, `false` if the tag was not found
    pub fn remove_tag(&mut self, tag: &str) -> bool {
        let initial_len = self.tags.len();
        self.tags.retain(|t| t != tag);
        self.tags.len() < initial_len
    }
    
    /// Checks if the device has a specific tag
    /// 
    /// # Parameters
    /// 
    /// - `tag`: The tag to check for
    /// 
    /// # Returns
    /// 
    /// `true` if the device has the tag, `false` otherwise
    pub fn has_tag(&self, tag: &str) -> bool {
        self.tags.contains(&tag.to_string())
    }
    
    /// Gets the current allocation ID if the device is allocated
    /// 
    /// # Returns
    /// 
    /// An `Option<&str>` containing the allocation ID if the device is allocated, `None` otherwise
    pub fn get_allocation_id(&self) -> Option<&str> {
        self.current_allocation_id.as_deref()
    }
    
    /// Calculates a simple health score based on device status (0-100)
    /// 
    /// This method returns a basic health score based solely on the device status.
    /// 
    /// # Returns
    /// 
    /// A health score between 0 (worst) and 100 (best)
    pub fn health_score(&self) -> u8 {
        match self.status {
            RiDeviceStatus::Available => 100,
            RiDeviceStatus::Busy => 80,
            RiDeviceStatus::Allocated => 80,
            RiDeviceStatus::Maintenance => 60,
            RiDeviceStatus::Degraded => 40,
            RiDeviceStatus::Offline => 20,
            RiDeviceStatus::Error => 10,
            RiDeviceStatus::Unknown => 0,
        }
    }
    
    /// Checks if the device is still responsive (last seen within the timeout)
    /// 
    /// # Parameters
    /// 
    /// - `timeout_secs`: Maximum number of seconds since last seen for the device to be considered responsive
    /// 
    /// # Returns
    /// 
    /// `true` if the device is responsive, `false` otherwise
    pub fn is_responsive(&self, timeout_secs: i64) -> bool {
        let elapsed = chrono::Utc::now() - self.last_seen;
        elapsed.num_seconds() < timeout_secs
    }
    
    /// Calculates a dynamic health score based on multiple factors (0-100)
    /// 
    /// This method calculates a comprehensive health score based on device status, CPU usage,
    /// memory usage, temperature, and error count.
    /// 
    /// # Parameters
    /// 
    /// - `health_metrics`: Current health metrics for the device
    /// 
    /// # Returns
    /// 
    /// A dynamic health score between 0 (worst) and 100 (best)
    pub fn dynamic_health_score(&self, health_metrics: &RiDeviceHealthMetrics) -> u8 {
        let mut score = self.health_score() as f64;
        
        // Adjust score based on CPU usage
        let cpu_penalty = (health_metrics.cpu_usage_percent / 100.0) * 20.0;
        score -= cpu_penalty;
        
        // Adjust score based on memory usage
        let memory_penalty = (health_metrics.memory_usage_percent / 100.0) * 15.0;
        score -= memory_penalty;
        
        // Adjust score based on temperature
        let temp_penalty = if health_metrics.temperature_celsius > 80.0 {
            (health_metrics.temperature_celsius - 80.0) * 2.0
        } else {
            0.0
        };
        score -= temp_penalty;
        
        // Adjust score based on error count
        let error_penalty = (health_metrics.error_count as f64) * 5.0;
        score -= error_penalty;
        
        // Adjust score based on network latency (for network devices)
        if matches!(self.device_type, RiDeviceType::Network) {
            let latency_penalty = if health_metrics.network_latency_ms > 100.0 {
                (health_metrics.network_latency_ms - 100.0) * 0.5
            } else {
                0.0
            };
            score -= latency_penalty;
        }
        
        // Adjust score based on disk IOPS (for storage devices)
        if matches!(self.device_type, RiDeviceType::Storage) {
            let iops_penalty = if health_metrics.disk_iops < 100 {
                (100.0 - health_metrics.disk_iops as f64) * 0.3
            } else {
                0.0
            };
            score -= iops_penalty;
        }
        
        // Adjust score based on battery level (for mobile/portable devices)
        let battery_penalty = if health_metrics.battery_level_percent < 20.0 {
            (20.0 - health_metrics.battery_level_percent) * 2.0
        } else {
            0.0
        };
        score -= battery_penalty;
        
        // Adjust score based on response time
        let response_time_penalty = if health_metrics.response_time_ms > 50.0 {
            (health_metrics.response_time_ms - 50.0) * 1.0
        } else {
            0.0
        };
        score -= response_time_penalty;
        
        // Ensure score is within 0-100 range
        score.clamp(0.0, 100.0) as u8
    }
    
    /// Checks if the device is healthy based on multiple criteria
    /// 
    /// A device is considered healthy if it is responsive, has a good health score,
    /// and is not in an error or offline state.
    /// 
    /// # Parameters
    /// 
    /// - `health_metrics`: Current health metrics for the device
    /// - `timeout_secs`: Maximum number of seconds since last seen for the device to be considered responsive
    /// 
    /// # Returns
    /// 
    /// `true` if the device is healthy, `false` otherwise
    pub fn is_healthy(&self, health_metrics: &RiDeviceHealthMetrics, timeout_secs: i64) -> bool {
        self.is_responsive(timeout_secs) && 
        self.dynamic_health_score(health_metrics) > 50 && 
        self.status != RiDeviceStatus::Error && 
        self.status != RiDeviceStatus::Offline
    }

    /// Gets a reference to the device metadata
    /// 
    /// # Returns
    /// 
    /// A reference to the metadata HashMap
    pub fn metadata(&self) -> &FxHashMap<String, String> {
        &self.metadata
    }
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiDevice {
    #[new]
    fn py_new(name: String, device_type: RiDeviceType) -> Self {
        Self::new(name, device_type)
    }
    
    #[staticmethod]
    fn default_device(name: String, device_type: RiDeviceType) -> Self {
        Self::new(name, device_type)
    }
    
    #[pyo3(name = "id")]
    fn id_impl(&self) -> String {
        self.id().to_string()
    }
    
    #[pyo3(name = "name")]
    fn name_impl(&self) -> String {
        self.name().to_string()
    }
    
    #[pyo3(name = "device_type")]
    fn device_type_impl(&self) -> RiDeviceType {
        self.device_type()
    }
    
    #[pyo3(name = "status")]
    fn status_impl(&self) -> RiDeviceStatus {
        self.status()
    }
    
    #[pyo3(name = "capabilities")]
    fn capabilities_impl(&self) -> RiDeviceCapabilities {
        self.capabilities().clone()
    }
    
    #[pyo3(name = "health_metrics")]
    fn health_metrics_impl(&self) -> RiDeviceHealthMetrics {
        self.health_metrics().clone()
    }
    
    #[pyo3(name = "set_status")]
    fn set_status_impl(&mut self, status: RiDeviceStatus) {
        self.set_status(status)
    }
    
    #[pyo3(name = "update_health_metrics")]
    fn update_health_metrics_impl(&mut self, metrics: RiDeviceHealthMetrics) {
        self.update_health_metrics(metrics)
    }
    
    #[pyo3(name = "increment_error_count")]
    fn increment_error_count_impl(&mut self) {
        self.increment_error_count()
    }
    
    #[pyo3(name = "update_throughput")]
    fn update_throughput_impl(&mut self, throughput: u64) {
        self.update_throughput(throughput)
    }
    
    #[pyo3(name = "with_capabilities")]
    fn with_capabilities_impl(&self, capabilities: RiDeviceCapabilities) -> Self {
        self.clone().with_capabilities(capabilities)
    }
    
    #[pyo3(name = "set_location")]
    fn set_location_impl(&mut self, location: String) {
        self.set_location(location)
    }
    
    #[pyo3(name = "add_metadata")]
    fn add_metadata_impl(&mut self, key: String, value: String) {
        self.add_metadata(key, value)
    }
    
    #[pyo3(name = "update_last_seen")]
    fn update_last_seen_impl(&mut self) {
        self.update_last_seen()
    }
    
    #[pyo3(name = "is_available")]
    fn is_available_impl(&self) -> bool {
        self.is_available()
    }
    
    #[pyo3(name = "is_allocated")]
    fn is_allocated_impl(&self) -> bool {
        self.is_allocated()
    }
    
    #[pyo3(name = "allocate")]
    fn allocate_impl(&mut self, allocation_id: String) -> bool {
        self.allocate(&allocation_id)
    }
    
    #[pyo3(name = "release")]
    fn release_impl(&mut self) {
        self.release()
    }
    
    #[pyo3(name = "group")]
    fn group_impl(&self) -> Option<String> {
        self.group().map(|s| s.to_string())
    }
    
    #[pyo3(name = "set_group")]
    fn set_group_impl(&mut self, group: Option<String>) {
        self.set_group(group)
    }
    
    #[pyo3(name = "tags")]
    fn tags_impl(&self) -> Vec<String> {
        self.tags().clone()
    }
    
    #[pyo3(name = "add_tag")]
    fn add_tag_impl(&mut self, tag: String) {
        self.add_tag(tag)
    }
    
    #[pyo3(name = "remove_tag")]
    fn remove_tag_impl(&mut self, tag: String) -> bool {
        self.remove_tag(&tag)
    }
    
    #[pyo3(name = "has_tag")]
    fn has_tag_impl(&self, tag: String) -> bool {
        self.has_tag(&tag)
    }
    
    #[pyo3(name = "get_allocation_id")]
    fn get_allocation_id_impl(&self) -> Option<String> {
        self.get_allocation_id().map(|s| s.to_string())
    }
    
    #[pyo3(name = "health_score")]
    fn health_score_impl(&self) -> u8 {
        self.health_score()
    }
    
    #[pyo3(name = "is_responsive")]
    fn is_responsive_impl(&self, timeout_secs: i64) -> bool {
        self.is_responsive(timeout_secs)
    }
    
    #[pyo3(name = "dynamic_health_score")]
    fn dynamic_health_score_impl(&self, health_metrics: RiDeviceHealthMetrics) -> u8 {
        self.dynamic_health_score(&health_metrics)
    }
    
    #[pyo3(name = "is_healthy")]
    fn is_healthy_impl(&self, health_metrics: RiDeviceHealthMetrics, timeout_secs: i64) -> bool {
        self.is_healthy(&health_metrics, timeout_secs)
    }
    
    #[pyo3(name = "metadata")]
    fn metadata_impl(&self) -> FxHashMap<String, String> {
        self.metadata().clone()
    }
}