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

//! # Hardware Discovery Providers
//!
//! This module provides hardware discovery providers for different device types.
//! Each provider implements a common interface to detect and enumerate hardware
//! on the current platform.
//!
//! ## Architecture
//!
//! - **RiHardwareProvider**: Trait defining the provider interface
//! - **CPUProvider**: Discovers CPU devices
//! - **MemoryProvider**: Discovers memory devices
//! - **StorageProvider**: Discovers storage devices
//! - **NetworkProvider**: Discovers network devices
//! - **GPUProvider**: Discovers GPU devices
//! - **USBProvider**: Discovers USB devices
//! - **ProviderRegistry**: Manages all available providers
//!
//! ## Usage
//!
//! ```rust,ignore
//! use ri::device::discovery::providers::{ProviderRegistry, CPUProvider};
//!
//! let mut registry = ProviderRegistry::new();
//! registry.register(Box::new(CPUProvider::new()));
//!
//! // Discover all CPU devices
//! let cpus = registry.discover_devices("cpu").await;
//! ```

use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::RwLock;
use super::super::core::{RiDevice, RiDeviceType, RiDeviceCapabilities};

/// Sanitizes command output for safe use in device names and logs.
///
/// # Security
///
/// This function prevents:
/// 1. Log injection attacks (removes control characters)
/// 2. ANSI escape sequences (prevents terminal escape attacks)
/// 3. Excessive whitespace (prevents log flooding)
/// 4. Non-printable characters
fn sanitize_command_output(output: &str) -> String {
    let mut result = String::with_capacity(output.len());
    let mut last_was_space = false;
    
    for c in output.chars() {
        match c {
            // Allow printable ASCII characters
            ' '..='~' => {
                // Collapse multiple spaces into one
                if c == ' ' {
                    if !last_was_space {
                        result.push(c);
                    }
                    last_was_space = true;
                } else {
                    result.push(c);
                    last_was_space = false;
                }
            }
            // Allow Unicode letters and numbers
            c if c.is_alphanumeric() => {
                result.push(c);
                last_was_space = false;
            }
            // Skip control characters, ANSI sequences, etc.
            _ => continue,
        }
    }
    
    // Trim and limit length
    let trimmed = result.trim();
    if trimmed.len() > 256 {
        trimmed[..256].to_string()
    } else {
        trimmed.to_string()
    }
}

/// Safely executes a system command and returns sanitized output.
///
/// # Security
///
/// This function:
/// 1. Uses hardcoded command paths (no user input)
/// 2. Sanitizes output to prevent injection
/// 3. Handles errors gracefully
/// 4. Logs command execution for audit
fn safe_command_output(command: &str, args: &[&str]) -> Option<String> {
    log::debug!("[Ri.Device] Executing command: {} {:?}", command, args);
    
    let output = std::process::Command::new(command)
        .args(args)
        .output()
        .ok()?;
    
    if !output.status.success() {
        log::warn!(
            "[Ri.Device] Command failed: {} (exit code: {:?})",
            command,
            output.status.code()
        );
        return None;
    }
    
    let raw_output = String::from_utf8_lossy(&output.stdout);
    let sanitized = sanitize_command_output(&raw_output);
    
    log::debug!("[Ri.Device] Command output: {}", sanitized);
    
    Some(sanitized)
}
use super::platform::{PlatformInfo, HardwareCategory};

/// Result type for hardware discovery
pub type DiscoveryResult<T> = Result<T, String>;

/// Trait for hardware discovery providers
#[async_trait]
pub trait RiHardwareProvider: Send + Sync {
    /// Returns the provider name
    fn name(&self) -> &str;

    /// Returns the hardware categories this provider handles
    fn categories(&self) -> Vec<HardwareCategory>;

    /// Discovers devices of this type
    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>>;

    /// Returns the priority of this provider (lower = higher priority)
    fn priority(&self) -> u32;

    /// Checks if this provider is available on the current platform
    fn is_available(&self, platform: &PlatformInfo) -> bool;
}

/// CPU Discovery Provider
pub struct CPUProvider {
    priority: u32,
}

impl CPUProvider {
    /// Creates a new CPU provider
    pub fn new() -> Self {
        Self { priority: 10 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for CPUProvider {
    fn name(&self) -> &str {
        "CPUProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::CPU]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        // Get CPU information based on platform
        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_cpus(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_cpus(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_cpus(platform).await?);
            }
            _ => {
                // Generic fallback for other platforms
                devices.extend(discover_generic_cpus(platform).await?);
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, _platform: &PlatformInfo) -> bool {
        true
    }
}

/// Memory Discovery Provider
pub struct MemoryProvider {
    priority: u32,
}

impl MemoryProvider {
    pub fn new() -> Self {
        Self { priority: 20 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for MemoryProvider {
    fn name(&self) -> &str {
        "MemoryProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::Memory]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_memory(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_memory(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_memory(platform).await?);
            }
            _ => {
                devices.extend(discover_generic_memory(platform).await?);
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, _platform: &PlatformInfo) -> bool {
        true
    }
}

/// Storage Discovery Provider
pub struct StorageProvider {
    priority: u32,
}

impl StorageProvider {
    pub fn new() -> Self {
        Self { priority: 30 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for StorageProvider {
    fn name(&self) -> &str {
        "StorageProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::Storage]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_storage(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_storage(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_storage(platform).await?);
            }
            _ => {
                devices.extend(discover_generic_storage(platform).await?);
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, _platform: &PlatformInfo) -> bool {
        true
    }
}

/// Network Discovery Provider
pub struct NetworkProvider {
    priority: u32,
}

impl NetworkProvider {
    pub fn new() -> Self {
        Self { priority: 40 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for NetworkProvider {
    fn name(&self) -> &str {
        "NetworkProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::Network]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_network(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_network(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_network(platform).await?);
            }
            _ => {
                devices.extend(discover_generic_network(platform).await?);
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, _platform: &PlatformInfo) -> bool {
        true
    }
}

/// GPU Discovery Provider
pub struct GPUProvider {
    priority: u32,
}

impl GPUProvider {
    pub fn new() -> Self {
        Self { priority: 25 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for GPUProvider {
    fn name(&self) -> &str {
        "GPUProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::GPU]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_gpus(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_gpus(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_gpus(platform).await?);
            }
            _ => {
                devices.extend(discover_generic_gpus(platform).await?);
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, platform: &PlatformInfo) -> bool {
        // GPUs are not available in WebAssembly
        platform.platform_type != super::platform::PlatformType::WebAssembly
    }
}

/// USB Discovery Provider
pub struct USBProvider {
    priority: u32,
}

impl USBProvider {
    pub fn new() -> Self {
        Self { priority: 50 }
    }
}

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

#[async_trait]
impl RiHardwareProvider for USBProvider {
    fn name(&self) -> &str {
        "USBProvider"
    }

    fn categories(&self) -> Vec<HardwareCategory> {
        vec![HardwareCategory::USB]
    }

    async fn discover(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let mut devices = Vec::with_capacity(1);

        match platform.platform_type {
            super::platform::PlatformType::Linux => {
                devices.extend(discover_linux_usb(platform).await?);
            }
            super::platform::PlatformType::MacOS => {
                devices.extend(discover_macos_usb(platform).await?);
            }
            super::platform::PlatformType::Windows => {
                devices.extend(discover_windows_usb(platform).await?);
            }
            _ => {
                // No USB support on other platforms
            }
        }

        Ok(devices)
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn is_available(&self, platform: &PlatformInfo) -> bool {
        platform.platform_type != super::platform::PlatformType::WebAssembly
    }
}

/// Provider Registry - manages all hardware discovery providers
#[derive(Default)]
pub struct ProviderRegistry {
    providers: Arc<RwLock<Vec<Arc<dyn RiHardwareProvider>>>>,
}

impl ProviderRegistry {
    /// Creates a new provider registry
    pub fn new() -> Self {
        Self {
            providers: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Registers a provider
    pub async fn register(&self, provider: Box<dyn RiHardwareProvider>) {
        let mut providers = self.providers.write().await;
        providers.push(Arc::from(provider));
        // Sort by priority
        providers.sort_by_key(|p| p.priority());
    }

    /// Registers the default set of providers
    pub async fn register_defaults(&self) {
        self.register(Box::new(CPUProvider::new())).await;
        self.register(Box::new(MemoryProvider::new())).await;
        self.register(Box::new(StorageProvider::new())).await;
        self.register(Box::new(NetworkProvider::new())).await;
        self.register(Box::new(GPUProvider::new())).await;
        self.register(Box::new(USBProvider::new())).await;
    }

    /// Discovers devices of a specific type
    pub async fn discover_devices(
        &self,
        category: &HardwareCategory,
        platform: &PlatformInfo,
    ) -> DiscoveryResult<Vec<RiDevice>> {
        let providers = self.providers.read().await;
        let mut all_devices = Vec::with_capacity(8);

        for provider in providers.iter() {
            if provider.categories().contains(category) && provider.is_available(platform) {
                match provider.discover(platform).await {
                    Ok(devices) => all_devices.extend(devices),
                    Err(e) => tracing::warn!("Provider {} failed: {}", provider.name(), e),
                }
            }
        }

        Ok(all_devices)
    }

    /// Discovers all available devices
    pub async fn discover_all(&self, platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
        let providers = self.providers.read().await;
        let mut all_devices = Vec::with_capacity(8);

        for provider in providers.iter() {
            if provider.is_available(platform) {
                match provider.discover(platform).await {
                    Ok(devices) => all_devices.extend(devices),
                    Err(e) => tracing::warn!("Provider {} failed: {}", provider.name(), e),
                }
            }
        }

        Ok(all_devices)
    }

    /// Returns the number of registered providers
    pub async fn provider_count(&self) -> usize {
        self.providers.read().await.len()
    }
}

/// Creates a default device with basic capabilities
fn create_device(
    name: String,
    device_type: RiDeviceType,
    capabilities: RiDeviceCapabilities,
) -> RiDevice {
    RiDevice::new(name, device_type)
        .with_capabilities(capabilities)
}

// Platform-specific discovery implementations

async fn discover_linux_cpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    // Read CPU info from /proc/cpuinfo
    if let Ok(content) = std::fs::read_to_string("/proc/cpuinfo") {
        let mut core_count = 0;
        let mut model_name = String::new();

        for line in content.lines() {
            if line.starts_with("processor") {
                core_count += 1;
            }
            if line.starts_with("model name") || line.starts_with("Model name") {
                if let Some(pos) = line.find(':') {
                    model_name = line[pos + 1..].trim().to_string();
                }
            }
        }

        if core_count > 0 {
            let capabilities = RiDeviceCapabilities::new()
                .with_compute_units(core_count)
                .with_memory_gb(0.0); // Memory will be set by memory provider

            let device = create_device(
                format!("CPU: {}", model_name),
                RiDeviceType::CPU,
                capabilities,
            );
            devices.push(device);
        }
    }

    Ok(devices)
}

async fn discover_macos_cpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    // Security: Use safe_command_output to sanitize command output
    let model_name = safe_command_output("sysctl", &["-n", "machdep.cpu.brand_string"])
        .unwrap_or_else(|| "Unknown CPU".to_string());

    let core_count = std::thread::available_parallelism()
        .map(|p| p.get())
        .unwrap_or(1);

    let capabilities = RiDeviceCapabilities::new()
        .with_compute_units(core_count)
        .with_memory_gb(0.0);

    let device = create_device(
        format!("CPU: {}", model_name),
        RiDeviceType::CPU,
        capabilities,
    );
    devices.push(device);

    Ok(devices)
}

async fn discover_windows_cpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    // Security: Use safe_command_output to sanitize command output
    let model_name = safe_command_output("wmic", &["CPU", "Get", "Name", "/VALUE"])
        .and_then(|output| {
            // Parse the output safely
            if let Some(name_line) = output.lines().find(|l| l.starts_with("Name=")) {
                Some(sanitize_command_output(&name_line[5..]))
            } else {
                None
            }
        })
        .unwrap_or_else(|| "Unknown CPU".to_string());

    let core_count = std::thread::available_parallelism()
        .map(|p| p.get())
        .unwrap_or(1);

    let capabilities = RiDeviceCapabilities::new()
        .with_compute_units(core_count)
        .with_memory_gb(0.0);

    let device = create_device(
        format!("CPU: {}", model_name),
        RiDeviceType::CPU,
        capabilities,
    );
    devices.push(device);

    Ok(devices)
}

async fn discover_generic_cpus(platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let capabilities = RiDeviceCapabilities::new()
        .with_compute_units(platform.cpu_cores)
        .with_memory_gb(0.0);

    let device = create_device(
        format!("Generic CPU ({} cores)", platform.cpu_cores),
        RiDeviceType::CPU,
        capabilities,
    );

    Ok(vec![device])
}

async fn discover_linux_memory(platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let capabilities = RiDeviceCapabilities::new()
        .with_compute_units(0)
        .with_memory_gb(platform.total_memory as f64 / (1024.0 * 1024.0 * 1024.0));

    let device = create_device(
        format!("System Memory ({:.2} GB)", platform.total_memory as f64 / (1024.0 * 1024.0 * 1024.0)),
        RiDeviceType::Memory,
        capabilities,
    );

    Ok(vec![device])
}

async fn discover_macos_memory(platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    discover_linux_memory(platform).await
}

async fn discover_windows_memory(platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    discover_linux_memory(platform).await
}

async fn discover_generic_memory(platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    discover_linux_memory(platform).await
}

async fn discover_linux_storage(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    // Read /proc/mounts to find mounted filesystems
    if let Ok(content) = std::fs::read_to_string("/proc/mounts") {
        let mut seen = std::collections::HashSet::new();

        for line in content.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 {
                let device = parts[0];
                if device.starts_with("/dev/") && !seen.contains(device) {
                    seen.insert(device);

                    let capabilities = RiDeviceCapabilities::new()
                        .with_storage_gb(100.0);

                    let device_info = RiDevice::new(
                        device.to_string(),
                        RiDeviceType::Storage,
                    ).with_capabilities(capabilities);
                    devices.push(device_info);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_macos_storage(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("df")
        .arg("-l")
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            let mut seen = std::collections::HashSet::new();
            for line in String::from_utf8_lossy(&output.stdout).lines().skip(1) {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 9 {
                    let device = parts[0];
                    if !seen.contains(device) && device.starts_with("/dev/") {
                        seen.insert(device);
                        let capabilities = RiDeviceCapabilities::new()
                            .with_storage_gb(100.0);

                        let device_info = RiDevice::new(
                            device.to_string(),
                            RiDeviceType::Storage,
                        ).with_capabilities(capabilities);
                        devices.push(device_info);
                    }
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_windows_storage(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("wmic")
        .args(&["LogicalDisk", "Get", "Name,Size", "/VALUE"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                if line.starts_with("Name=") {
                    let drive = &line[5..];
                    let capabilities = RiDeviceCapabilities::new()
                        .with_storage_gb(100.0);

                    let device_info = RiDevice::new(
                        drive.to_string(),
                        RiDeviceType::Storage,
                    ).with_capabilities(capabilities);
                    devices.push(device_info);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_generic_storage(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let capabilities = RiDeviceCapabilities::new()
        .with_storage_gb(100.0);

    let device = create_device(
        "Generic Storage".to_string(),
        RiDeviceType::Storage,
        capabilities,
    );

    Ok(vec![device])
}

async fn discover_linux_network(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    if let Ok(content) = std::fs::read_to_string("/proc/net/dev") {
        for line in content.lines().skip(2) {
            let parts: Vec<&str> = line.split(':').collect();
            if parts.len() >= 2 {
                let interface = parts[0].trim();
                if !interface.is_empty() && interface != "lo" {
                    let capabilities = RiDeviceCapabilities::new()
                        .with_bandwidth_gbps(1.0);

                    let device = RiDevice::new(
                        format!("Network Interface: {}", interface),
                        RiDeviceType::Network,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_macos_network(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("ifconfig")
        .output();

    if let Ok(output) = output {
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            if line.starts_with_flags(&['a'..='z', 'A'..='Z']) && !line.starts_with("lo") {
                let parts: Vec<&str> = line.split(':').collect();
                if parts.len() >= 1 {
                    let interface = parts[0].trim();
                    if !interface.is_empty() {
                        let capabilities = RiDeviceCapabilities::new()
                            .with_bandwidth_gbps(1.0);

                        let device = RiDevice::new(
                            format!("Network Interface: {}", interface),
                            RiDeviceType::Network,
                        ).with_capabilities(capabilities);
                        devices.push(device);
                    }
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_windows_network(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("wmic")
        .args(&["NicConfig", "Get", "Description,MACAddress", "/VALUE"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                if line.starts_with("Description=") {
                    let name = &line[12..];
                    let capabilities = RiDeviceCapabilities::new()
                        .with_bandwidth_gbps(1.0);

                    let device = RiDevice::new(
                        name.to_string(),
                        RiDeviceType::Network,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_generic_network(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let capabilities = RiDeviceCapabilities::new()
        .with_bandwidth_gbps(1.0);

    let device = create_device(
        "Generic Network Adapter".to_string(),
        RiDeviceType::Network,
        capabilities,
    );

    Ok(vec![device])
}

async fn discover_linux_gpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    // Check for NVIDIA GPUs
    if let Ok(nvidia_output) = std::process::Command::new("nvidia-smi")
        .arg("--query-gpu=name,memory.total,driver_version")
        .arg("--format=csv,noheader")
        .output()
    {
        if nvidia_output.status.success() {
            for line in String::from_utf8_lossy(&nvidia_output.stdout).lines() {
                let parts: Vec<&str> = line.split(',').collect();
                if parts.len() >= 1 {
                    let name = parts[0].trim();
                    let capabilities = RiDeviceCapabilities::new()
                        .with_compute_units(1)
                        .with_memory_gb(8.0);

                    let device = RiDevice::new(
                        format!("NVIDIA GPU: {}", name),
                        RiDeviceType::GPU,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    // Check for AMD GPUs in sysfs
    if let Ok(amd_dirs) = std::fs::read_dir("/sys/class/drm") {
        for entry in amd_dirs.flatten() {
            if let Ok(path) = entry.path().join("device").read_link() {
                if path.to_string_lossy().contains("pci") {
                    let capabilities = RiDeviceCapabilities::new()
                        .with_compute_units(1)
                        .with_memory_gb(4.0);

                    let device = RiDevice::new(
                        format!("GPU: {}", entry.file_name().to_string_lossy()),
                        RiDeviceType::GPU,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_macos_gpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("system_profiler")
        .args(&["SPDisplaysDataType", "-detailLevel", "mini"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            let content = String::from_utf8_lossy(&output.stdout);
            let capabilities = RiDeviceCapabilities::new()
                .with_compute_units(1)
                .with_memory_gb(4.0);

            let device = RiDevice::new(
                format!("GPU: {}", content.lines().next().unwrap_or("Unknown")),
                RiDeviceType::GPU,
            ).with_capabilities(capabilities);
            devices.push(device);
        }
    }

    Ok(devices)
}

async fn discover_windows_gpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("wmic")
        .args(&["Path", "Win32_VideoController", "Get", "Name,AdapterRAM", "/VALUE"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                if line.starts_with("Name=") {
                    let name = &line[5..];
                    let capabilities = RiDeviceCapabilities::new()
                        .with_compute_units(1)
                        .with_memory_gb(4.0);

                    let device = RiDevice::new(
                        name.to_string(),
                        RiDeviceType::GPU,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_generic_gpus(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let capabilities = RiDeviceCapabilities::new()
        .with_compute_units(1)
        .with_memory_gb(4.0);

    let device = create_device(
        "Generic GPU".to_string(),
        RiDeviceType::GPU,
        capabilities,
    );

    Ok(vec![device])
}

async fn discover_linux_usb(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    if let Ok(usb_dirs) = std::fs::read_dir("/sys/bus/usb/devices") {
        for entry in usb_dirs.flatten() {
            if let Ok(id) = entry.file_name().into_string() {
                if !id.is_empty() && !id.starts_with('.') {
                    let capabilities = RiDeviceCapabilities::new();

                    let device = RiDevice::new(
                        format!("USB Device: {}", id),
                        RiDeviceType::Custom,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

async fn discover_macos_usb(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("system_profiler")
        .args(&["SPUSBDataType", "-detailLevel", "mini"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            let content = String::from_utf8_lossy(&output.stdout);
            let capabilities = RiDeviceCapabilities::new();

            let device = RiDevice::new(
                format!("USB: {}", content.lines().next().unwrap_or("Unknown")),
                RiDeviceType::Custom,
            ).with_capabilities(capabilities);
            devices.push(device);
        }
    }

    Ok(devices)
}

async fn discover_windows_usb(_platform: &PlatformInfo) -> DiscoveryResult<Vec<RiDevice>> {
    let mut devices = Vec::with_capacity(1);

    let output = std::process::Command::new("wmic")
        .args(&["USBController", "Get", "Name", "/VALUE"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                if line.starts_with("Name=") {
                    let name = &line[5..];
                    let capabilities = RiDeviceCapabilities::new();

                    let device = RiDevice::new(
                        name.to_string(),
                        RiDeviceType::Custom,
                    ).with_capabilities(capabilities);
                    devices.push(device);
                }
            }
        }
    }

    Ok(devices)
}

trait StartsWith {
    fn starts_with_flags(&self, ranges: &[std::ops::RangeInclusive<char>]) -> bool;
}

impl StartsWith for str {
    fn starts_with_flags(&self, ranges: &[std::ops::RangeInclusive<char>]) -> bool {
        if let Some(first_char) = self.chars().next() {
            ranges.iter().any(|r| r.contains(&first_char))
        } else {
            false
        }
    }
}