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
//! 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.

//! # Device Control Module
//! 
//! This module provides comprehensive smart device control functionality for Ri, including device
//! discovery, control, and resource scheduling. It enables efficient management of devices and
//! their resources across distributed environments.
//! 
//! ## Key Components
//! 
//! - **RiDeviceControlModule**: Main device control module implementing service module traits
//! - **RiDevice**: Device representation with type, status, and capabilities
//! - **RiDeviceType**: Enum defining supported device types
//! - **RiDeviceStatus**: Enum defining device statuses
//! - **RiDeviceCapabilities**: Device capabilities structure
//! - **RiDeviceController**: Device controller for managing devices
//! - **RiDeviceScheduler**: Device scheduler for resource allocation
//! - **RiResourcePool**: Resource pool for managing device resources
//! - **RiResourcePoolManager**: Manager for multiple resource pools
//! - **RiResourcePoolStatistics**: Statistics for resource pool monitoring
//! - **RiDeviceControlConfig**: Configuration for device control behavior
//! - **RiDiscoveryResult**: Result structure for device discovery
//! - **RiResourceRequest**: Request structure for resource allocation
//! - **RiResourceAllocation**: Result structure for resource allocation
//! - **RiResourcePoolStatus**: Status structure for resource pools
//! 
//! ## Design Principles
//! 
//! 1. **Device Abstraction**: Unified interface for different device types
//! 2. **Auto Discovery**: Automatic device discovery in the network/environment
//! 3. **Resource Scheduling**: Intelligent resource allocation and scheduling
//! 4. **Configurable**: Highly configurable device control behavior
//! 5. **Async Support**: Full async/await compatibility
//! 6. **Resource Pooling**: Efficient management of device resources through pooling
//! 7. **Service Module Integration**: Implements service module traits for seamless integration
//! 8. **Thread-safe**: Uses Arc and RwLock for safe concurrent access
//! 9. **Non-critical**: Device control failures should not break the entire application
//! 10. **Monitoring**: Comprehensive statistics for device and resource monitoring
//! 11. **Scalable**: Designed to handle large numbers of devices and concurrent tasks
//! 
//! ## Usage
//! 
//! ```rust
//! use ri::prelude::*;
//! use ri::device::{RiDeviceControlConfig, RiResourceRequest, RiDeviceType, RiDeviceCapabilities};
//! 
//! async fn example() -> RiResult<()> {
//!     // Create device control configuration
//!     let device_config = RiDeviceControlConfig {
//!         discovery_enabled: true,
//!         discovery_interval_secs: 30,
//!         auto_scheduling_enabled: true,
//!         max_concurrent_tasks: 100,
//!         resource_allocation_timeout_secs: 60,
//!     };
//!     
//!     // Create device control module
//!     let device_module = RiDeviceControlModule::new()
//!         .with_config(device_config);
//!     
//!     // Discover devices
//!     let discovery_result = device_module.discover_devices().await?;
//!     println!("Discovered {} devices, total devices: {}", 
//!              discovery_result.discovered_devices.len(), 
//!              discovery_result.total_devices);
//!     
//!     // Get device status
//!     let devices = device_module.get_device_status().await?;
//!     println!("Current devices: {:?}", devices);
//!     
//!     // Create resource request
//!     let resource_request = RiResourceRequest {
//!         request_id: "request-123".to_string(),
//!         device_type: RiDeviceType::Compute,
//!         required_capabilities: RiDeviceCapabilities {
//!             cpu_cores: Some(4),
//!             memory_gb: Some(8.0),
//!             storage_gb: Some(100.0),
//!             gpu_enabled: Some(true),
//!             network_speed_mbps: Some(1000.0),
//!             extra: Default::default(),
//!         },
//!         priority: 5,
//!         timeout_secs: 30,
//!     };
//!     
//!     // Allocate resource
//!     if let Some(allocation) = device_module.allocate_resource(resource_request).await? {
//!         println!("Allocated device: {} (ID: {})", 
//!                  allocation.device_name, 
//!                  allocation.device_id);
//!         
//!         // Release resource after use
//!         device_module.release_resource(&allocation.allocation_id).await?;
//!     }
//!     
//!     Ok(())
//! }
//! ```

mod core;
mod controller;
pub mod scheduler;
pub mod pool;
pub mod discovery_scheduler;
pub mod discovery;

use std::sync::Arc;

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

use crate::observability::{RiMetricsRegistry, RiMetric, RiMetricConfig, RiMetricType};

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


pub use core::{RiDevice, RiDeviceType, RiDeviceStatus, RiDeviceCapabilities, RiDeviceControlConfig, RiDeviceConfig, RiNetworkDeviceInfo, RiDeviceHealthMetrics};
pub use controller::RiDeviceController;
pub use pool::{RiResourcePool, RiResourcePoolManager, RiConnectionPoolStatistics, RiResourcePoolConfig};
pub use scheduler::RiDeviceScheduler;
pub use discovery_scheduler::{RiDeviceDiscoveryEngine, RiResourceScheduler};

// Re-export discovery module types
pub use discovery::{
    RiDeviceDiscovery,
    DiscoveryConfig,
    DiscoveryStats,
    DiscoveryStrategy,
    HardwareCategory,
    PlatformInfo,
    PlatformType,
    Architecture,
    PlatformCompatibility,
    ProviderRegistry,
    RiHardwareProvider,
    PluginRegistry,
    RiHardwareDiscoveryPlugin,
    PluginMetadata,
    PluginStatus,
    PluginError,
    AsyncDiscovery,
};

use crate::core::{RiResult, RiServiceContext};


/// Main device control module for Ri.
/// 
/// This module provides comprehensive smart device control functionality, including device discovery,
/// control, and resource scheduling. It manages devices and their resources across distributed environments.
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDeviceControlModule {
    /// Device controller for managing devices
    controller: Arc<RwLock<RiDeviceController>>,
    /// Device scheduler for resource allocation
    scheduler: Arc<RwLock<RiDeviceScheduler>>,
    /// Discovery engine for device discovery
    discovery_engine: Arc<RwLock<RiResourceScheduler>>,
    /// Map of resource pool names to resource pool instances
    resource_pools: FxHashMap<String, Arc<RiResourcePool>>,
    /// Device control configuration
    config: RiDeviceControlConfig,
}

/// Scheduling configuration for device control module
///
/// This configuration contains scheduling and resource management settings
/// for device control operations.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDeviceSchedulingConfig {
    /// Whether device discovery is enabled
    pub discovery_enabled: bool,
    /// Interval between device discovery scans in seconds
    pub discovery_interval_secs: u64,
    /// Whether automatic resource scheduling is enabled
    pub auto_scheduling_enabled: bool,
    /// Maximum number of concurrent tasks
    pub max_concurrent_tasks: usize,
    /// Timeout for resource allocation in seconds
    pub resource_allocation_timeout_secs: u64,
}

impl Default for RiDeviceSchedulingConfig {
    fn default() -> Self {
        Self {
            discovery_enabled: true,
            discovery_interval_secs: 30,
            auto_scheduling_enabled: true,
            max_concurrent_tasks: 100,
            resource_allocation_timeout_secs: 60,
        }
    }
}

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

/// Result structure for device discovery operations.
/// 
/// This struct contains information about the results of a device discovery scan, including
/// discovered, updated, and removed devices.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiDiscoveryResult {
    /// Newly discovered devices
    pub discovered_devices: Vec<RiDevice>,
    /// Devices with updated information
    pub updated_devices: Vec<RiDevice>,
    /// IDs of removed devices
    pub removed_devices: Vec<String>, // device IDs
    /// Total number of devices after discovery
    pub total_devices: usize,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiDiscoveryResult {
    #[new]
    fn py_new() -> Self {
        Self {
            discovered_devices: Vec::new(),
            updated_devices: Vec::new(),
            removed_devices: Vec::new(),
            total_devices: 0,
        }
    }
    
    #[staticmethod]
    fn default_result() -> Self {
        Self::default()
    }
    
    fn discovered_devices_impl(&self) -> Vec<RiDevice> {
        self.discovered_devices.clone()
    }
    
    fn updated_devices_impl(&self) -> Vec<RiDevice> {
        self.updated_devices.clone()
    }
    
    fn removed_devices_impl(&self) -> Vec<String> {
        self.removed_devices.clone()
    }
    
    fn total_devices_impl(&self) -> usize {
        self.total_devices
    }
    
    fn __str__(&self) -> String {
        format!("RiDiscoveryResult(discovered: {}, updated: {}, removed: {}, total: {})", 
                self.discovered_devices.len(), self.updated_devices.len(), 
                self.removed_devices.len(), self.total_devices)
    }
}

impl Default for RiDiscoveryResult {
    fn default() -> Self {
        Self {
            discovered_devices: Vec::new(),
            updated_devices: Vec::new(),
            removed_devices: Vec::new(),
            total_devices: 0,
        }
    }
}

/// Request structure for resource allocation.
/// 
/// This struct defines the requirements for resource allocation, including device type, capabilities,
/// priority, timeout, and advanced scheduling preferences such as SLA, resource weights,
/// and affinity rules. New fields are optional to preserve backward compatibility.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiResourceRequest {
    /// Unique request ID
    pub request_id: String,
    /// Required device type
    pub device_type: RiDeviceType,
    /// Required device capabilities
    pub required_capabilities: RiDeviceCapabilities,
    /// Request priority (1-10, higher is more important)
    pub priority: u8, // 1-10, higher is more important
    /// Request timeout in seconds
    pub timeout_secs: u64,
    /// Optional SLA class for this request (e.g. Critical / High / Medium / Low)
    pub sla_class: Option<RiRequestSlaClass>,
    /// Optional multi-dimensional resource weights to influence scheduling decisions
    pub resource_weights: Option<RiResourceWeights>,
    /// Optional affinity rules describing preferred/required device labels
    pub affinity: Option<RiAffinityRules>,
    /// Optional anti-affinity rules describing labels or devices to avoid
    pub anti_affinity: Option<RiAffinityRules>,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiResourceRequest {
    #[new]
    #[pyo3(signature = (request_id, device_type, required_capabilities, priority=5, timeout_secs=60))]
    fn py_new(request_id: String, device_type: RiDeviceType, required_capabilities: RiDeviceCapabilities, priority: u8, timeout_secs: u64) -> Self {
        Self {
            request_id,
            device_type,
            required_capabilities,
            priority,
            timeout_secs,
            sla_class: None,
            resource_weights: None,
            affinity: None,
            anti_affinity: None,
        }
    }
    
    #[pyo3(name = "request_id")]
    fn request_id_impl(&self) -> String {
        self.request_id.clone()
    }
    
    #[pyo3(name = "device_type")]
    fn device_type_impl(&self) -> RiDeviceType {
        self.device_type
    }
    
    #[pyo3(name = "required_capabilities")]
    fn required_capabilities_impl(&self) -> RiDeviceCapabilities {
        self.required_capabilities.clone()
    }
    
    #[pyo3(name = "priority")]
    fn priority_impl(&self) -> u8 {
        self.priority
    }
    
    #[pyo3(name = "timeout_secs")]
    fn timeout_secs_impl(&self) -> u64 {
        self.timeout_secs
    }
    
    #[pyo3(name = "sla_class")]
    fn sla_class_impl(&self) -> Option<RiRequestSlaClass> {
        self.sla_class
    }
    
    #[pyo3(name = "resource_weights")]
    fn resource_weights_impl(&self) -> Option<RiResourceWeights> {
        self.resource_weights.clone()
    }
    
    #[pyo3(name = "affinity")]
    fn affinity_impl(&self) -> Option<RiAffinityRules> {
        self.affinity.clone()
    }
    
    #[pyo3(name = "anti_affinity")]
    fn anti_affinity_impl(&self) -> Option<RiAffinityRules> {
        self.anti_affinity.clone()
    }
    
    #[pyo3(name = "set_priority")]
    fn set_priority_impl(&mut self, priority: u8) {
        self.priority = priority;
    }
    
    #[pyo3(name = "set_timeout_secs")]
    fn set_timeout_secs_impl(&mut self, timeout_secs: u64) {
        self.timeout_secs = timeout_secs;
    }
    
    #[pyo3(name = "set_sla_class")]
    fn set_sla_class_impl(&mut self, sla_class: Option<RiRequestSlaClass>) {
        self.sla_class = sla_class;
    }
    
    #[pyo3(name = "set_resource_weights")]
    fn set_resource_weights_impl(&mut self, resource_weights: Option<RiResourceWeights>) {
        self.resource_weights = resource_weights;
    }
    
    #[pyo3(name = "set_affinity")]
    fn set_affinity_impl(&mut self, affinity: Option<RiAffinityRules>) {
        self.affinity = affinity;
    }
    
    #[pyo3(name = "set_anti_affinity")]
    fn set_anti_affinity_impl(&mut self, anti_affinity: Option<RiAffinityRules>) {
        self.anti_affinity = anti_affinity;
    }
    
    fn __str__(&self) -> String {
        format!("RiResourceRequest(id: {}, type: {:?}, priority: {}, timeout: {}s)", 
                self.request_id, self.device_type, self.priority, self.timeout_secs)
    }
}

/// SLA class for a resource request.
/// 
/// This enum describes the service level expectations for a request. Schedulers can
/// use this information to trade off between latency, availability, and resource usage.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub enum RiRequestSlaClass {
    /// Mission critical requests that should be served with the highest priority
    Critical,
    /// High priority requests
    High,
    /// Normal priority requests
    Medium,
    /// Low priority / best-effort requests
    Low,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiRequestSlaClass {
    fn __str__(&self) -> String {
        match self {
            RiRequestSlaClass::Critical => "Critical".to_string(),
            RiRequestSlaClass::High => "High".to_string(),
            RiRequestSlaClass::Medium => "Medium".to_string(),
            RiRequestSlaClass::Low => "Low".to_string(),
        }
    }
}

/// Multi-dimensional resource weights for scheduling.
/// 
/// This struct allows callers to express how important different resource dimensions are
/// (compute, memory, storage, bandwidth) for a specific request. Schedulers can use these
/// weights when computing fitness scores.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiResourceWeights {
    /// Weight for compute resources (e.g. CPU cores, GPU units)
    pub compute_weight: f64,
    /// Weight for memory capacity
    pub memory_weight: f64,
    /// Weight for storage capacity
    pub storage_weight: f64,
    /// Weight for network bandwidth
    pub bandwidth_weight: f64,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiResourceWeights {
    #[new]
    #[pyo3(signature = (compute_weight=1.0, memory_weight=1.0, storage_weight=1.0, bandwidth_weight=1.0))]
    fn py_new(compute_weight: f64, memory_weight: f64, storage_weight: f64, bandwidth_weight: f64) -> Self {
        Self {
            compute_weight,
            memory_weight,
            storage_weight,
            bandwidth_weight,
        }
    }
    
    #[staticmethod]
    fn default_weights() -> Self {
        Self::default()
    }
    
    #[pyo3(name = "compute_weight")]
    fn compute_weight_impl(&self) -> f64 { self.compute_weight }
    #[pyo3(name = "memory_weight")]
    fn memory_weight_impl(&self) -> f64 { self.memory_weight }
    #[pyo3(name = "storage_weight")]
    fn storage_weight_impl(&self) -> f64 { self.storage_weight }
    #[pyo3(name = "bandwidth_weight")]
    fn bandwidth_weight_impl(&self) -> f64 { self.bandwidth_weight }
    
    #[pyo3(name = "set_compute_weight")]
    fn set_compute_weight_impl(&mut self, weight: f64) { self.compute_weight = weight; }
    #[pyo3(name = "set_memory_weight")]
    fn set_memory_weight_impl(&mut self, weight: f64) { self.memory_weight = weight; }
    #[pyo3(name = "set_storage_weight")]
    fn set_storage_weight_impl(&mut self, weight: f64) { self.storage_weight = weight; }
    #[pyo3(name = "set_bandwidth_weight")]
    fn set_bandwidth_weight_impl(&mut self, weight: f64) { self.bandwidth_weight = weight; }
    
    fn __str__(&self) -> String {
        format!("RiResourceWeights(compute: {}, memory: {}, storage: {}, bandwidth: {})", 
                self.compute_weight, self.memory_weight, self.storage_weight, self.bandwidth_weight)
    }
}

impl Default for RiResourceWeights {
    fn default() -> Self {
        Self {
            compute_weight: 1.0,
            memory_weight: 1.0,
            storage_weight: 1.0,
            bandwidth_weight: 1.0,
        }
    }
}

/// Affinity and anti-affinity rules for device selection.
/// 
/// Rules are expressed as label key/value pairs. Implementations can interpret labels
/// using device metadata such as location, zone, rack, tenant, etc.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiAffinityRules {
    /// Labels that must be present with matching values
    pub required_labels: FxHashMap<String, String>,
    /// Labels that are preferred (but not strictly required)
    pub preferred_labels: FxHashMap<String, String>,
    /// Labels that must not be present with matching values
    pub forbidden_labels: FxHashMap<String, String>,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiAffinityRules {
    #[new]
    fn py_new() -> Self {
        Self {
            required_labels: FxHashMap::default(),
            preferred_labels: FxHashMap::default(),
            forbidden_labels: FxHashMap::default(),
        }
    }
    
    #[staticmethod]
    fn default_rules() -> Self {
        Self::default()
    }
    
    #[pyo3(name = "required_labels")]
    fn required_labels_impl(&self) -> FxHashMap<String, String> {
        self.required_labels.clone()
    }
    
    #[pyo3(name = "preferred_labels")]
    fn preferred_labels_impl(&self) -> FxHashMap<String, String> {
        self.preferred_labels.clone()
    }
    
    #[pyo3(name = "forbidden_labels")]
    fn forbidden_labels_impl(&self) -> FxHashMap<String, String> {
        self.forbidden_labels.clone()
    }
    
    fn __str__(&self) -> String {
        format!("RiAffinityRules(required: {}, preferred: {}, forbidden: {})", 
                self.required_labels.len(), self.preferred_labels.len(), self.forbidden_labels.len())
    }
}

impl Default for RiAffinityRules {
    fn default() -> Self {
        Self {
            required_labels: FxHashMap::default(),
            preferred_labels: FxHashMap::default(),
            forbidden_labels: FxHashMap::default(),
        }
    }
}

/// Result structure for resource allocation.
/// 
/// This struct contains information about a successful resource allocation, including the allocated
/// device, allocation time, and expiration time.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct RiResourceAllocation {
    /// Unique allocation ID
    pub allocation_id: String,
    /// ID of the allocated device
    pub device_id: String,
    /// Name of the allocated device
    pub device_name: String,
    /// Time when the resource was allocated
    pub allocated_at: chrono::DateTime<chrono::Utc>,
    /// Time when the allocation expires
    pub expires_at: chrono::DateTime<chrono::Utc>,
    /// Original resource request
    pub request: RiResourceRequest,
}

#[cfg(feature = "pyo3")]
#[pymethods]
impl RiResourceAllocation {
    #[new]
    fn py_new(allocation_id: String, device_id: String, device_name: String, request: RiResourceRequest) -> Self {
        let now = chrono::Utc::now();
        let expires_at = now + chrono::TimeDelta::seconds(request.timeout_secs as i64);
        
        Self {
            allocation_id,
            device_id,
            device_name,
            allocated_at: now,
            expires_at,
            request,
        }
    }
    
    #[pyo3(name = "allocation_id")]
    fn allocation_id_impl(&self) -> String {
        self.allocation_id.clone()
    }
    
    #[pyo3(name = "device_id")]
    fn device_id_impl(&self) -> String {
        self.device_id.clone()
    }
    
    #[pyo3(name = "device_name")]
    fn device_name_impl(&self) -> String {
        self.device_name.clone()
    }
    
    #[pyo3(name = "allocated_at")]
    fn allocated_at_impl(&self) -> String {
        self.allocated_at.to_rfc3339()
    }
    
    #[pyo3(name = "expires_at")]
    fn expires_at_impl(&self) -> String {
        self.expires_at.to_rfc3339()
    }
    
    #[pyo3(name = "request")]
    fn request_impl(&self) -> RiResourceRequest {
        self.request.clone()
    }
    
    #[pyo3(name = "is_expired")]
    fn is_expired_impl(&self) -> bool {
        chrono::Utc::now() > self.expires_at
    }
    
    #[pyo3(name = "remaining_time")]
    fn remaining_time_impl(&self) -> i64 {
        (self.expires_at - chrono::Utc::now()).num_seconds()
    }
    
    fn __str__(&self) -> String {
        format!("RiResourceAllocation(id: {}, device: {} ({}), expires: {})", 
                self.allocation_id, self.device_name, self.device_id, self.expires_at)
    }
}

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

impl RiDeviceControlModule {
    /// Creates a new device control module with default configuration.
    /// 
    /// # Returns
    /// 
    /// A new `RiDeviceControlModule` instance with default configuration
    pub fn new() -> Self {
        let controller = Arc::new(RwLock::new(RiDeviceController::new()));
        let resource_pool_manager = Arc::new(RwLock::new(RiResourcePoolManager::new()));
        let scheduler = Arc::new(RwLock::new(RiDeviceScheduler::new(resource_pool_manager)));
        let discovery_engine = Arc::new(RwLock::new(RiResourceScheduler::new()));
        
        Self {
            controller,
            scheduler,
            discovery_engine,
            resource_pools: FxHashMap::default(),
            config: crate::device::core::RiDeviceControlConfig::default(),
        }
    }
    
    /// Configures the device control module with custom settings.
    /// 
    /// # Parameters
    /// 
    /// - `config`: The custom configuration to apply
    /// 
    /// # Returns
    /// 
    /// The updated `RiDeviceControlModule` instance
    pub fn with_config(mut self, config: crate::device::core::RiDeviceControlConfig) -> Self {
        self.config = config;
        self
    }
    
    /// Discovers devices in the network/environment.
    /// 
    /// This method performs a device discovery scan if discovery is enabled, returning information
    /// about discovered, updated, and removed devices.
    /// 
    /// # Returns
    /// 
    /// A `RiResult<RiDiscoveryResult>` containing the discovery results
    pub async fn discover_devices(&self) -> RiResult<RiDiscoveryResult> {
        if !self.config.enable_cpu_discovery && !self.config.enable_gpu_discovery && 
           !self.config.enable_memory_discovery && !self.config.enable_storage_discovery && 
           !self.config.enable_network_discovery {
            return Ok(RiDiscoveryResult {
                discovered_devices: vec![],
                updated_devices: vec![],
                removed_devices: vec![],
                total_devices: 0,
            });
        }
        
        let mut controller = self.controller.write().await;
        controller.discover_devices().await
    }
    
    /// Allocates a device resource based on the given request.
    /// 
    /// This method finds a suitable device based on the requested device type and capabilities,
    /// allocates it using the device scheduler, and returns an allocation result if successful.
    /// 
    /// # Parameters
    /// 
    /// - `request`: The resource allocation request
    /// 
    /// # Returns
    /// 
    /// A `RiResult<Option<RiResourceAllocation>>` containing the allocation result if successful,
    /// or None if allocation failed or auto-scheduling is disabled
    pub async fn allocate_resource(&self, request: RiResourceRequest) -> RiResult<Option<RiResourceAllocation>> {
        // Check if any device type scheduling is enabled
        let scheduling_enabled = match request.device_type {
            RiDeviceType::CPU => self.config.enable_cpu_discovery,
            RiDeviceType::GPU => self.config.enable_gpu_discovery,
            RiDeviceType::Memory => self.config.enable_memory_discovery,
            RiDeviceType::Storage => self.config.enable_storage_discovery,
            RiDeviceType::Network => self.config.enable_network_discovery,
            _ => true, // Default to enabled for unknown types
        };
        
        if !scheduling_enabled {
            return Ok(None);
        }

        let allocation_request = crate::device::scheduler::RiAllocationRequest {
            device_type: request.device_type,
            capabilities: request.required_capabilities,
            priority: request.priority as u32,
            timeout_secs: request.timeout_secs,
            sla_class: request.sla_class,
            resource_weights: request.resource_weights,
            affinity: request.affinity,
            anti_affinity: request.anti_affinity,
        };

        let scheduler = self.scheduler.write().await;
        let device = scheduler.select_device(&allocation_request).await;

        if let Some(device) = device {
            let allocation = RiResourceAllocation {
                allocation_id: uuid::Uuid::new_v4().to_string(),
                device_id: device.id().to_string(),
                device_name: device.name().to_string(),
                allocated_at: chrono::Utc::now(),
                expires_at: chrono::Utc::now() + chrono::Duration::seconds(allocation_request.timeout_secs as i64),
                request: RiResourceRequest {
                    request_id: request.request_id,
                    device_type: allocation_request.device_type,
                    required_capabilities: allocation_request.capabilities,
                    priority: request.priority,
                    timeout_secs: allocation_request.timeout_secs,
                    sla_class: allocation_request.sla_class,
                    resource_weights: allocation_request.resource_weights,
                    affinity: allocation_request.affinity,
                    anti_affinity: allocation_request.anti_affinity,
                },
            };

            // Mark device as busy via controller
            let mut controller = self.controller.write().await;
            controller.allocate_device(&allocation.device_id, &allocation.allocation_id).await?;

            Ok(Some(allocation))
        } else {
            Ok(None)
        }
    }
    
    /// Releases a previously allocated device resource.
    /// 
    /// This method releases a device resource that was allocated with `allocate_resource`.
    /// 
    /// # Parameters
    /// 
    /// - `allocation_id`: The ID of the allocation to release
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    pub async fn release_resource(&self, allocation_id: &str) -> RiResult<()> {
        let mut controller = self.controller.write().await;
        controller.release_device_by_allocation(allocation_id).await
    }
    
    /// Gets the current status of all devices.
    /// 
    /// This method returns a list of all devices currently managed by the device controller.
    /// 
    /// # Returns
    /// 
    /// A `RiResult<Vec<RiDevice>>` containing all managed devices
    pub async fn get_device_status(&self) -> RiResult<Vec<RiDevice>> {
        let controller = self.controller.read().await;
        Ok(controller.get_all_devices())
    }
    
    /// Gets the status of all resource pools.
    /// 
    /// This method returns a map of resource pool names to their current status.
    /// 
    /// # Returns
    /// 
    /// A `FxHashMap<String, RiResourcePoolStatus>` containing the status of all resource pools
    pub fn get_resource_pool_status(&self) -> FxHashMap<String, RiResourcePoolStatus> {
        let mut status = FxHashMap::default();
        for (pool_name, pool) in &self.resource_pools {
            status.insert(pool_name.clone(), pool.get_status());
        }
        status
    }
    
    /// Creates device management metrics and registers them with the metrics registry.
    /// 
    /// This method creates and registers the following metrics:
    /// - dms_device_total: Total number of devices by type and status
    /// - dms_device_allocation_attempts_total: Total number of allocation attempts
    /// - dms_device_allocation_success_total: Total number of successful allocations
    /// - dms_device_allocation_failure_total: Total number of failed allocations
    /// - dms_device_discovery_attempts_total: Total number of device discovery attempts
    /// - dms_device_discovery_success_total: Total number of successful device discoveries
    /// - dms_device_resource_utilization: Resource utilization by device type
    /// 
    /// # Parameters
    /// 
    /// - `registry`: The metrics registry to register the metrics with
    /// 
    /// # Returns
    /// 
    /// A `RiResult<()>` indicating success or failure
    #[allow(dead_code)]
    fn create_device_metrics(&self, registry: Arc<RiMetricsRegistry>) -> RiResult<()> {
        // Device total metric (Gauge)
        let device_total_config = RiMetricConfig {
            metric_type: RiMetricType::Gauge,
            name: "dms_device_total".to_string(),
            help: "Total number of devices by type and status".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(300),
            age_buckets: 5,
        };
        let device_total_metric = Arc::new(RiMetric::new(device_total_config));
        registry.register(device_total_metric)?;
        
        // Allocation attempts metric (Counter)
        let allocation_attempts_config = RiMetricConfig {
            metric_type: RiMetricType::Counter,
            name: "dms_device_allocation_attempts_total".to_string(),
            help: "Total number of device allocation attempts".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(0),
            age_buckets: 0,
        };
        let allocation_attempts_metric = Arc::new(RiMetric::new(allocation_attempts_config));
        registry.register(allocation_attempts_metric)?;
        
        // Allocation success metric (Counter)
        let allocation_success_config = RiMetricConfig {
            metric_type: RiMetricType::Counter,
            name: "dms_device_allocation_success_total".to_string(),
            help: "Total number of successful device allocations".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(0),
            age_buckets: 0,
        };
        let allocation_success_metric = Arc::new(RiMetric::new(allocation_success_config));
        registry.register(allocation_success_metric)?;
        
        // Allocation failure metric (Counter)
        let allocation_failure_config = RiMetricConfig {
            metric_type: RiMetricType::Counter,
            name: "dms_device_allocation_failure_total".to_string(),
            help: "Total number of failed device allocations".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(0),
            age_buckets: 0,
        };
        let allocation_failure_metric = Arc::new(RiMetric::new(allocation_failure_config));
        registry.register(allocation_failure_metric)?;
        
        // Discovery attempts metric (Counter)
        let discovery_attempts_config = RiMetricConfig {
            metric_type: RiMetricType::Counter,
            name: "dms_device_discovery_attempts_total".to_string(),
            help: "Total number of device discovery attempts".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(0),
            age_buckets: 0,
        };
        let discovery_attempts_metric = Arc::new(RiMetric::new(discovery_attempts_config));
        registry.register(discovery_attempts_metric)?;
        
        // Discovery success metric (Counter)
        let discovery_success_config = RiMetricConfig {
            metric_type: RiMetricType::Counter,
            name: "dms_device_discovery_success_total".to_string(),
            help: "Total number of successful device discoveries".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(0),
            age_buckets: 0,
        };
        let discovery_success_metric = Arc::new(RiMetric::new(discovery_success_config));
        registry.register(discovery_success_metric)?;
        
        // Resource utilization metric (Gauge)
        let resource_utilization_config = RiMetricConfig {
            metric_type: RiMetricType::Gauge,
            name: "dms_device_resource_utilization".to_string(),
            help: "Resource utilization by device type".to_string(),
            buckets: vec![],
            quantiles: vec![],
            max_age: std::time::Duration::from_secs(300),
            age_buckets: 5,
        };
        let resource_utilization_metric = Arc::new(RiMetric::new(resource_utilization_config));
        registry.register(resource_utilization_metric)?;
        
        Ok(())
    }
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiDeviceControlModule {
    fn get_config(&self) -> String {
        format!("{:?}", self.config)
    }
}

/// Status structure for resource pools.
/// 
/// This struct contains information about the current status of a resource pool, including capacity,
/// allocation, and utilization.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass(get_all, set_all))]
pub struct RiResourcePoolStatus {
    /// Total capacity of the resource pool
    pub total_capacity: usize,
    /// Available capacity in the resource pool
    pub available_capacity: usize,
    /// Allocated capacity in the resource pool
    pub allocated_capacity: usize,
    /// Number of pending resource requests
    pub pending_requests: usize,
    /// Resource utilization rate (0.0 to 1.0)
    pub utilization_rate: f64,
}

#[cfg(feature = "pyo3")]
#[pyo3::prelude::pymethods]
impl RiResourcePoolStatus {
    #[new]
    #[pyo3(signature = (total_capacity=0, available_capacity=0, allocated_capacity=0, pending_requests=0, utilization_rate=0.0))]
    fn py_new(total_capacity: usize, available_capacity: usize, allocated_capacity: usize, pending_requests: usize, utilization_rate: f64) -> Self {
        Self {
            total_capacity,
            available_capacity,
            allocated_capacity,
            pending_requests,
            utilization_rate,
        }
    }
    
    #[staticmethod]
    fn default_status() -> Self {
        Self::default()
    }
    
    #[pyo3(name = "total_capacity")]
    fn total_capacity_impl(&self) -> usize {
        self.total_capacity
    }
    
    #[pyo3(name = "available_capacity")]
    fn available_capacity_impl(&self) -> usize {
        self.available_capacity
    }
    
    #[pyo3(name = "allocated_capacity")]
    fn allocated_capacity_impl(&self) -> usize {
        self.allocated_capacity
    }
    
    #[pyo3(name = "pending_requests")]
    fn pending_requests_impl(&self) -> usize {
        self.pending_requests
    }
    
    #[pyo3(name = "utilization_rate")]
    fn utilization_rate_impl(&self) -> f64 {
        self.utilization_rate
    }
    
    fn __str__(&self) -> String {
        format!("RiResourcePoolStatus(total: {}, available: {}, allocated: {}, utilization: {:.2}%)",
                self.total_capacity, self.available_capacity, self.allocated_capacity, self.utilization_rate)
    }
}

impl Default for RiResourcePoolStatus {
    fn default() -> Self {
        Self {
            total_capacity: 0,
            available_capacity: 0,
            allocated_capacity: 0,
            pending_requests: 0,
            utilization_rate: 0.0,
        }
    }
}

#[async_trait::async_trait]
impl crate::core::RiModule for RiDeviceControlModule {
    /// Returns the name of the device control module.
    /// 
    /// # Returns
    /// 
    /// The module name as a string
    fn name(&self) -> &str {
        "Ri.DeviceControl"
    }
    
    /// Indicates whether the device control module is critical.
    /// 
    /// The device control module is non-critical, meaning that if it fails to initialize or operate,
    /// it should not break the entire application. This allows the core functionality to continue
    /// even if device control features are unavailable.
    /// 
    /// # Returns
    /// 
    /// `false` since device control is non-critical
    fn is_critical(&self) -> bool {
        false // Non-critical, should not break the app if device control fails
    }
    
    /// Initializes the device control module asynchronously.
    /// 
    /// This method performs the following steps:
    /// 1. Loads configuration from the service context
    /// 2. Initializes real device discovery based on system hardware
    /// 3. Sets up resource scheduling and management
    async fn init(&mut self, ctx: &mut RiServiceContext) -> RiResult<()> {
        let binding = ctx.config();
        let cfg = binding.config();
        let device_config = parse_device_config(cfg.get("device"));
        
        let mut controller = self.controller.write().await;
        controller.discover_system_devices(&device_config).await?;
        drop(controller);
        
        let discovery_engine = RiResourceScheduler::new();
        
        let mut discovery_guard = self.discovery_engine.write().await;
        *discovery_guard = discovery_engine;
        
        if let Some(metrics_registry) = ctx.metrics_registry() {
            let mut controller = self.controller.write().await;
            controller.initialize_metrics(&metrics_registry)?;
            drop(controller);
        }
        
        let logger = ctx.logger();
        logger.info("Ri.DeviceControl", "Device control module initialized with real hardware discovery")?;
        Ok(())
    }
}

impl crate::core::ServiceModule for RiDeviceControlModule {
    fn name(&self) -> &str {
        "Ri.DeviceControl"
    }

    fn is_critical(&self) -> bool {
        false
    }

    fn priority(&self) -> i32 {
        25
    }

    fn dependencies(&self) -> Vec<&str> {
        vec![]
    }

    fn init(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }

    fn start(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }

    fn shutdown(&mut self, _ctx: &mut crate::core::RiServiceContext) -> crate::core::RiResult<()> {
        Ok(())
    }
}

fn parse_device_config(config_str: Option<&String>) -> crate::device::core::RiDeviceControlConfig {
    match config_str {
        Some(config) => {
            let trimmed = config.trim();
            if trimmed.starts_with('{') {
                if let Ok(result) = serde_json::from_str::<crate::device::core::RiDeviceControlConfig>(trimmed) {
                    return result;
                }
            }
            if trimmed.starts_with("---") || trimmed.contains("discovery_enabled:") {
                if let Ok(result) = serde_yaml::from_str::<crate::device::core::RiDeviceControlConfig>(trimmed) {
                    return result;
                }
            }
            if trimmed.contains('[') || trimmed.contains("discovery_enabled") {
                if let Ok(result) = toml::from_str::<crate::device::core::RiDeviceControlConfig>(trimmed) {
                    return result;
                }
            }
            serde_json::from_str::<crate::device::core::RiDeviceControlConfig>(trimmed)
                .unwrap_or_default()
        }
        None => crate::device::core::RiDeviceControlConfig::default(),
    }
}