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

//! # Custom Discovery Plugins
//!
//! This module provides a plugin system for custom hardware discovery implementations.
//! Users can create their own discovery plugins to support specialized hardware or
//! proprietary device interfaces.
//!
//! ## Architecture
//!
//! - **RiHardwareDiscoveryPlugin**: Trait for plugin implementations
//! - **PluginRegistry**: Manages registered plugins
//! - **PluginMetadata**: Plugin information and configuration
//!
//! ## Usage
//!
//! ```rust,ignore
//! use ri::device::discovery::plugins::{RiHardwareDiscoveryPlugin, PluginRegistry};
//!
//! // Create a custom plugin
//! struct MyCustomPlugin;
//!
//! #[async_trait::async_trait]
//! impl RiHardwareDiscoveryPlugin for MyCustomPlugin {
//!     fn name(&self) -> &str { "MyCustomPlugin" }
//!     fn version(&self) -> &str { "1.0.0" }
//!     async fn discover(&self) -> Result<Vec<RiDevice>, String> {
//!         // Custom discovery logic
//!         Ok(vec![])
//!     }
//! }
//!
//! // Register the plugin
//! let mut registry = PluginRegistry::new();
//! registry.register(Box::new(MyCustomPlugin));
//! ```

use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Serialize, Deserialize};
use std::path::PathBuf;
use libloading::{Library, Symbol};
use thiserror::Error as ThisError;

use super::super::core::RiDevice;
use super::platform::{PlatformInfo, HardwareCategory};

/// Result type for plugin discovery operations
pub type PluginResult<T> = Result<T, PluginError>;

/// Errors that can occur during plugin operations
#[derive(Debug, Clone, Serialize, Deserialize, ThisError)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub enum PluginError {
    #[error("Plugin load failed: {0}")]
    LoadFailed(String),

    #[error("Plugin initialization failed: {0}")]
    InitFailed(String),

    #[error("Plugin discovery failed: {0}")]
    DiscoveryFailed(String),

    #[error("Plugin not found: {0}")]
    NotFound(String),

    #[error("Plugin already registered: {0}")]
    AlreadyRegistered(String),

    #[error("Unsupported platform for plugin")]
    UnsupportedPlatform(),

    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    #[error("Library load failed: {0}")]
    LibraryLoadFailed(String),

    #[error("Symbol resolution failed: {0}")]
    SymbolResolutionFailed(String),

    #[error("Library unload failed: {0}")]
    LibraryUnloadFailed(String),

    #[error("Plugin version mismatch: {0}")]
    VersionMismatch(String),

    #[error("Unknown error: {0}")]
    Unknown(String),
}

impl From<std::io::Error> for PluginError {
    fn from(e: std::io::Error) -> Self {
        PluginError::LoadFailed(format!("IO error: {}", e))
    }
}

/// Plugin metadata for identification and configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub struct PluginMetadata {
    /// Plugin name
    pub name: String,
    /// Plugin version
    pub version: String,
    /// Plugin author
    pub author: String,
    /// Plugin description
    pub description: String,
    /// Supported hardware categories
    pub supported_categories: Vec<HardwareCategory>,
    /// Minimum platform version requirement
    pub min_platform_version: Option<String>,
    /// Plugin configuration schema (JSON)
    pub config_schema: Option<String>,
    /// Dependencies
    pub dependencies: Vec<String>,
    /// Whether the plugin is enabled by default
    pub enabled_by_default: bool,
}

impl PluginMetadata {
    /// Creates new plugin metadata
    pub fn new(
        name: String,
        version: String,
        author: String,
        description: String,
    ) -> Self {
        Self {
            name,
            version,
            author,
            description,
            supported_categories: Vec::new(),
            min_platform_version: None,
            config_schema: None,
            dependencies: Vec::new(),
            enabled_by_default: true,
        }
    }

    /// Adds a supported hardware category
    pub fn with_category(mut self, category: HardwareCategory) -> Self {
        self.supported_categories.push(category);
        self
    }

    /// Sets the minimum platform version
    pub fn with_min_platform_version(mut self, version: String) -> Self {
        self.min_platform_version = Some(version);
        self
    }

    /// Sets the configuration schema
    pub fn with_config_schema(mut self, schema: &str) -> Self {
        self.config_schema = Some(schema.to_string());
        self
    }

    /// Adds a dependency
    pub fn with_dependency(mut self, dep: String) -> Self {
        self.dependencies.push(dep);
        self
    }

    /// Sets whether the plugin is enabled by default
    pub fn with_enabled_by_default(mut self, enabled: bool) -> Self {
        self.enabled_by_default = enabled;
        self
    }
}

/// Trait for custom hardware discovery plugins
#[async_trait]
pub trait RiHardwareDiscoveryPlugin: Send + Sync {
    /// Returns the plugin metadata
    fn metadata(&self) -> PluginMetadata;

    /// Initializes the plugin with configuration
    async fn initialize(&mut self, config: &str) -> PluginResult<()> {
        let _ = config;
        Ok(())
    }

    /// Discovers hardware devices
    async fn discover(&self, platform: &PlatformInfo) -> PluginResult<Vec<RiDevice>>;

    /// Called when the plugin is being unloaded
    async fn shutdown(&mut self) -> PluginResult<()> {
        Ok(())
    }

    /// Returns the current plugin status
    fn status(&self) -> PluginStatus;
}

/// Current status of a plugin
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
pub enum PluginStatus {
    Loaded(),
    Ready(),
    Discovering(),
    Disabled(),
    Error(String),
    ShuttingDown(),
}

impl std::fmt::Display for PluginStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PluginStatus::Loaded() => write!(f, "Plugin is loaded but not initialized"),
            PluginStatus::Ready() => write!(f, "Plugin is initialized and ready"),
            PluginStatus::Discovering() => write!(f, "Plugin is currently discovering"),
            PluginStatus::Disabled() => write!(f, "Plugin has been disabled"),
            PluginStatus::Error(msg) => write!(f, "Plugin encountered an error: {}", msg),
            PluginStatus::ShuttingDown() => write!(f, "Plugin is being unloaded"),
        }
    }
}

/// Plugin wrapper for runtime management
#[allow(dead_code)]
struct PluginWrapper {
    metadata: PluginMetadata,
    plugin: Arc<RwLock<Box<dyn RiHardwareDiscoveryPlugin>>>,
    status: Arc<RwLock<PluginStatus>>,
    config: Arc<RwLock<Option<String>>>,
    load_time: std::time::SystemTime,
    library: Option<Arc<Library>>,
}

impl PluginWrapper {
    pub fn new(plugin: Box<dyn RiHardwareDiscoveryPlugin>) -> Self {
        let metadata = plugin.metadata();
        let status = plugin.status();

        Self {
            metadata,
            plugin: Arc::new(RwLock::new(plugin)),
            status: Arc::new(RwLock::new(status)),
            config: Arc::new(RwLock::new(None)),
            load_time: std::time::SystemTime::now(),
            library: None,
        }
    }

    #[allow(dead_code)]
    pub fn with_library(plugin: Box<dyn RiHardwareDiscoveryPlugin>, library: Arc<Library>) -> Self {
        let metadata = plugin.metadata();
        let status = plugin.status();

        Self {
            metadata,
            plugin: Arc::new(RwLock::new(plugin)),
            status: Arc::new(RwLock::new(status)),
            config: Arc::new(RwLock::new(None)),
            load_time: std::time::SystemTime::now(),
            library: Some(library),
        }
    }

    pub async fn initialize(&self, config: &str) -> PluginResult<()> {
        let mut plugin = self.plugin.write().await;
        plugin.initialize(config).await?;
        *self.config.write().await = Some(config.to_string());
        *self.status.write().await = PluginStatus::Ready();
        Ok(())
    }

    pub async fn discover(&self, platform: &PlatformInfo) -> PluginResult<Vec<RiDevice>> {
        *self.status.write().await = PluginStatus::Discovering();
        let result = self.plugin.read().await.discover(platform).await;
        *self.status.write().await = PluginStatus::Ready();
        result
    }

    pub async fn shutdown(&self) -> PluginResult<()> {
        *self.status.write().await = PluginStatus::ShuttingDown();
        let mut plugin = self.plugin.write().await;
        plugin.shutdown().await?;
        *self.status.write().await = PluginStatus::Loaded();
        Ok(())
    }

    pub fn metadata(&self) -> &PluginMetadata {
        &self.metadata
    }

    #[allow(dead_code)]
    pub async fn status(&self) -> PluginStatus {
        self.status.read().await.clone()
    }

    #[allow(dead_code)]
    pub fn is_dynamic(&self) -> bool {
        self.library.is_some()
    }
}

/// Plugin registry for managing custom discovery plugins
#[derive(Default)]
pub struct PluginRegistry {
    plugins: Arc<RwLock<HashMap<String, PluginWrapper>>>,
    enabled: Arc<RwLock<HashSet<String>>>,
}

impl PluginRegistry {
    /// Creates a new plugin registry
    pub fn new() -> Self {
        Self {
            plugins: Arc::new(RwLock::new(HashMap::new())),
            enabled: Arc::new(RwLock::new(HashSet::new())),
        }
    }

    /// Registers a new plugin
    pub async fn register(&mut self, plugin: Box<dyn RiHardwareDiscoveryPlugin>) -> PluginResult<String> {
        let metadata = plugin.metadata();
        let name = metadata.name.clone();

        let mut plugins = self.plugins.write().await;
        let mut enabled = self.enabled.write().await;

        if plugins.contains_key(&name) {
            return Err(PluginError::AlreadyRegistered(name));
        }

        let wrapper = PluginWrapper::new(plugin);
        plugins.insert(name.clone(), wrapper);
        if metadata.enabled_by_default {
            enabled.insert(name.clone());
        }

        Ok(name)
    }

    /// Unregisters a plugin
    pub async fn unregister(&mut self, name: &str) -> PluginResult<()> {
        let mut plugins = self.plugins.write().await;
        let mut enabled = self.enabled.write().await;

        if let Some(wrapper) = plugins.remove(name) {
            wrapper.shutdown().await?;
            enabled.remove(name);
            Ok(())
        } else {
            Err(PluginError::NotFound(name.to_string()))
        }
    }

    /// Initializes a plugin with configuration
    pub async fn initialize(&self, name: &str, config: &str) -> PluginResult<()> {
        let plugins = self.plugins.read().await;
        if let Some(wrapper) = plugins.get(name) {
            wrapper.initialize(config).await
        } else {
            Err(PluginError::NotFound(name.to_string()))
        }
    }

    /// Discovers devices using a specific plugin
    pub async fn discover_with_plugin(
        &self,
        name: &str,
        platform: &PlatformInfo,
    ) -> PluginResult<Vec<RiDevice>> {
        let enabled = self.enabled.read().await;
        if !enabled.contains(name) {
            return Err(PluginError::NotFound(name.to_string()));
        }

        let plugins = self.plugins.read().await;
        if let Some(wrapper) = plugins.get(name) {
            wrapper.discover(platform).await
        } else {
            Err(PluginError::NotFound(name.to_string()))
        }
    }

    /// Discovers devices using all enabled plugins
    pub async fn discover_all(&self, platform: &PlatformInfo) -> PluginResult<Vec<RiDevice>> {
        let enabled = self.enabled.read().await;
        let plugins = self.plugins.read().await;

        let mut all_devices = Vec::with_capacity(8);
        for name in enabled.iter() {
            if let Some(wrapper) = plugins.get(name) {
                match wrapper.discover(platform).await {
                    Ok(devices) => all_devices.extend(devices),
                    Err(e) => tracing::warn!("Plugin {} discovery failed: {}", name, e),
                }
            }
        }

        Ok(all_devices)
    }

    /// Enables a plugin
    pub async fn enable(&self, name: &str) -> PluginResult<()> {
        let plugins = self.plugins.read().await;
        if plugins.contains_key(name) {
            self.enabled.write().await.insert(name.to_string());
            Ok(())
        } else {
            Err(PluginError::NotFound(name.to_string()))
        }
    }

    /// Disables a plugin
    pub async fn disable(&self, name: &str) -> PluginResult<()> {
        let plugins = self.plugins.read().await;
        if plugins.contains_key(name) {
            self.enabled.write().await.remove(name);
            Ok(())
        } else {
            Err(PluginError::NotFound(name.to_string()))
        }
    }

    /// Checks if a plugin is enabled
    pub async fn is_enabled(&self, name: &str) -> bool {
        self.enabled.read().await.contains(name)
    }

    /// Returns all registered plugin names
    pub async fn registered_plugins(&self) -> Vec<String> {
        self.plugins.read().await.keys().cloned().collect()
    }

    /// Returns all enabled plugin names
    pub async fn enabled_plugins(&self) -> Vec<String> {
        self.enabled.read().await.iter().cloned().collect()
    }

    /// Returns plugin metadata
    pub async fn plugin_metadata(&self, name: &str) -> Option<PluginMetadata> {
        self.plugins.read().await.get(name).map(|w| w.metadata().clone())
    }

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

    /// Returns the count of enabled plugins
    pub async fn enabled_count(&self) -> usize {
        self.enabled.read().await.len()
    }
}

/// Plugin loader for dynamic plugin loading
#[derive(Default)]
pub struct PluginLoader {
    search_paths: Arc<RwLock<Vec<PathBuf>>>,
}

impl PluginLoader {
    /// Creates a new plugin loader
    pub fn new() -> Self {
        let mut search_paths = Vec::with_capacity(8);
        search_paths.push(PathBuf::from("./plugins"));
        search_paths.push(PathBuf::from("/usr/local/lib/ri/plugins"));
        #[cfg(target_os = "macos")]
        search_paths.push(PathBuf::from("/opt/homebrew/lib/ri/plugins"));

        Self {
            search_paths: Arc::new(RwLock::new(search_paths)),
        }
    }

    /// Creates a new plugin loader with custom search paths
    pub fn with_paths(paths: Vec<PathBuf>) -> Self {
        Self {
            search_paths: Arc::new(RwLock::new(paths)),
        }
    }

    /// Adds a search path for plugins
    pub async fn add_search_path(&self, path: PathBuf) {
        self.search_paths.write().await.push(path);
    }

    /// Gets all search paths
    pub async fn search_paths(&self) -> Vec<PathBuf> {
        self.search_paths.read().await.clone()
    }

    /// Clears all search paths
    pub async fn clear_search_paths(&self) {
        self.search_paths.write().await.clear();
    }

    /// Loads plugins from all search paths
    pub async fn load_all(&self, registry: &mut PluginRegistry) -> PluginResult<Vec<String>> {
        let mut loaded = Vec::with_capacity(4);
        let paths = self.search_paths.read().await;

        for path in paths.iter() {
            match self.load_plugins_from_path(path, registry).await {
                Ok(loaded_plugins) => loaded.extend(loaded_plugins),
                Err(e) => tracing::warn!("Failed to load plugins from {}: {}", path.display(), e),
            }
        }

        Ok(loaded)
    }

    /// Loads plugins from a specific directory path
    async fn load_plugins_from_path(&self, path: &PathBuf, registry: &mut PluginRegistry) -> PluginResult<Vec<String>> {
        let mut loaded = Vec::with_capacity(4);

        if !path.exists() {
            tracing::debug!("Plugin path does not exist: {}", path.display());
            return Ok(loaded);
        }

        if !path.is_dir() {
            tracing::warn!("Plugin path is not a directory: {}", path.display());
            return Ok(loaded);
        }

        let entries = std::fs::read_dir(path)?;

        for entry in entries.flatten() {
            let entry_path = entry.path();

            if !entry_path.is_file() {
                continue;
            }

            let extension = entry_path.extension()
                .and_then(|ext| ext.to_str())
                .map(|ext| ext.to_lowercase());

            let is_plugin = extension.as_ref()
                .map(|ext| ext == "so" || ext == "dll" || ext == "dylib")
                .unwrap_or(false);

            if !is_plugin {
                continue;
            }

            tracing::info!("Found plugin: {}", entry_path.display());

            match self.load(&entry_path).await {
                Ok(plugin) => {
                    let name = registry.register(plugin).await?;
                    tracing::info!("Successfully loaded plugin: {}", name);
                    loaded.push(name);
                }
                Err(e) => {
                    tracing::error!("Failed to load plugin {}: {}", entry_path.display(), e);
                }
            }
        }

        Ok(loaded)
    }

    /// Loads a specific plugin file
    /// 
    /// # Security
    /// 
    /// This method performs the following security checks:
    /// 1. Path validation to prevent directory traversal
    /// 2. File extension validation
    /// 3. File size limits to prevent DoS
    /// 4. Signature verification (if enabled)
    pub async fn load(&self, path: &PathBuf) -> PluginResult<Box<dyn RiHardwareDiscoveryPlugin>> {
        tracing::info!("Loading plugin from: {}", path.display());

        // Security: Validate the path
        self.validate_plugin_path(path)?;

        if !path.exists() {
            return Err(PluginError::LoadFailed(format!("Plugin file not found: {}", path.display())));
        }

        // Security: Check file size to prevent DoS
        let metadata = std::fs::metadata(path)
            .map_err(|e| PluginError::LoadFailed(format!("Failed to read file metadata: {}", e)))?;
        
        const MAX_PLUGIN_SIZE: u64 = 100 * 1024 * 1024; // 100 MB
        if metadata.len() > MAX_PLUGIN_SIZE {
            return Err(PluginError::LoadFailed(format!(
                "Plugin file too large: {} bytes (max {} bytes)", 
                metadata.len(), MAX_PLUGIN_SIZE
            )));
        }

        // Security: Verify file extension
        let extension = path.extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_lowercase())
            .unwrap_or_default();

        let valid_extensions = match std::env::consts::OS {
            "linux" => vec!["so"],
            "macos" => vec!["dylib"],
            "windows" => vec!["dll"],
            _ => vec!["so", "dll", "dylib"],
        };

        if !valid_extensions.contains(&extension.as_str()) {
            return Err(PluginError::LoadFailed(format!(
                "Invalid plugin extension: {} (expected: {:?})",
                extension, valid_extensions
            )));
        }

        // Security: Canonicalize path to prevent directory traversal
        let canonical_path = path.canonicalize()
            .map_err(|e| PluginError::LoadFailed(format!("Failed to canonicalize path: {}", e)))?;

        let library = Arc::new(
            unsafe {
                Library::new(&canonical_path)
                    .map_err(|e| PluginError::LibraryLoadFailed(format!(
                        "Failed to load library {}: {}", canonical_path.display(), e
                    )))?
            }
        );

        let plugin = self.load_plugin_from_library(&library, &canonical_path)?;

        Ok(plugin)
    }

    /// Validates a plugin path for security
    /// 
    /// # Security Checks
    /// 
    /// 1. Path must be absolute or relative to allowed directories
    /// 2. Path must not contain directory traversal sequences
    /// 3. Path must be within allowed plugin directories
    fn validate_plugin_path(&self, path: &PathBuf) -> PluginResult<()> {
        let path_str = path.to_string_lossy();
        
        // Security: Check for directory traversal attempts
        if path_str.contains("..") {
            return Err(PluginError::PermissionDenied(
                "Directory traversal not allowed in plugin path".to_string()
            ));
        }

        // Security: Check for null bytes (path injection)
        if path_str.contains('\0') {
            return Err(PluginError::PermissionDenied(
                "Null bytes not allowed in plugin path".to_string()
            ));
        }

        // Security: On Windows, check for reserved names
        #[cfg(target_os = "windows")]
        {
            let file_name = path.file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("")
                .to_uppercase();
            
            let reserved_names = [
                "CON", "PRN", "AUX", "NUL",
                "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
                "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
            ];

            if reserved_names.contains(&file_name.as_str()) {
                return Err(PluginError::PermissionDenied(
                    format!("Reserved file name not allowed: {}", file_name)
                ));
            }
        }

        Ok(())
    }

    /// Loads a plugin from an already loaded library
    fn load_plugin_from_library(&self, library: &Arc<Library>, path: &PathBuf) -> PluginResult<Box<dyn RiHardwareDiscoveryPlugin>> {
        #[allow(improper_ctypes_definitions)]
    type CreatePluginFn = unsafe extern "C" fn() -> *mut dyn RiHardwareDiscoveryPlugin;

        unsafe {
            let create_symbol: Symbol<CreatePluginFn> = library
                .get(b"create_ri_plugin")
                .map_err(|e| PluginError::SymbolResolutionFailed(format!(
                    "Failed to resolve create_ri_plugin symbol in {}: {}", path.display(), e
                )))?;

            let plugin_ptr = create_symbol();

            if plugin_ptr.is_null() {
                return Err(PluginError::LoadFailed(format!(
                    "create_ri_plugin returned null pointer for {}", path.display()
                )));
            }

            let plugin = Box::from_raw(plugin_ptr);

            tracing::info!(
                "Successfully loaded plugin: {} v{}",
                plugin.metadata().name,
                plugin.metadata().version
            );

            Ok(plugin)
        }
    }

    /// Validates a plugin file without loading it
    pub async fn validate(&self, path: &PathBuf) -> PluginResult<PluginMetadata> {
        if !path.exists() {
            return Err(PluginError::LoadFailed(format!("Plugin file not found: {}", path.display())));
        }

        let library = Arc::new(
            unsafe {
                Library::new(path)
                    .map_err(|e| PluginError::LibraryLoadFailed(format!(
                        "Failed to load library {}: {}", path.display(), e
                    )))?
            }
        );

        #[allow(improper_ctypes_definitions)]
        type GetMetadataFn = unsafe extern "C" fn() -> PluginMetadata;

        unsafe {
            let metadata_symbol: Symbol<GetMetadataFn> = library
                .get(b"get_ri_plugin_metadata")
                .map_err(|e| PluginError::SymbolResolutionFailed(format!(
                    "Failed to resolve get_ri_plugin_metadata symbol in {}: {}", path.display(), e
                )))?;

            let metadata = metadata_symbol();

            tracing::info!(
                "Validated plugin: {} v{} (author: {})",
                metadata.name,
                metadata.version,
                metadata.author
            );

            Ok(metadata)
        }
    }

    /// Gets the plugin API version from a library
    pub async fn get_api_version(&self, path: &PathBuf) -> PluginResult<u32> {
        type GetVersionFn = unsafe extern "C" fn() -> u32;

        let library = Arc::new(
            unsafe {
                Library::new(path)
                    .map_err(|e| PluginError::LibraryLoadFailed(format!(
                        "Failed to load library {}: {}", path.display(), e
                    )))?
            }
        );

        unsafe {
            let version_symbol: Symbol<GetVersionFn> = library
                .get(b"get_ri_plugin_api_version")
                .map_err(|e| PluginError::SymbolResolutionFailed(format!(
                    "Failed to resolve get_ri_plugin_api_version symbol in {}: {}", path.display(), e
                )))?;

            let version = version_symbol();

            tracing::debug!("Plugin API version for {}: {}", path.display(), version);

            Ok(version)
        }
    }

    /// Checks if a plugin file is compatible with the current Ri version
    pub async fn is_compatible(&self, path: &PathBuf) -> bool {
        const CURRENT_API_VERSION: u32 = 1;

        match self.get_api_version(path).await {
            Ok(version) => version == CURRENT_API_VERSION,
            Err(e) => {
                tracing::warn!("Failed to check API version for {}: {}", path.display(), e);
                false
            }
        }
    }
}

impl Drop for PluginLoader {
    fn drop(&mut self) {
        tracing::debug!("PluginLoader dropped");
    }
}

/// Built-in custom provider plugin for user-defined discovery
pub struct CustomProviderPlugin {
    name: String,
    version: String,
    description: String,
    discover_func: Arc<dyn Fn() -> Vec<RiDevice> + Send + Sync>,
    status: PluginStatus,
}

impl CustomProviderPlugin {
    /// Creates a new custom provider plugin
    pub fn new<F>(name: &str, version: &str, description: &str, discover_func: F) -> Self
    where
        F: Fn() -> Vec<RiDevice> + Send + Sync + 'static,
    {
        Self {
            name: name.to_string(),
            version: version.to_string(),
            description: description.to_string(),
            discover_func: Arc::new(discover_func),
            status: PluginStatus::Loaded(),
        }
    }
}

#[async_trait]
impl RiHardwareDiscoveryPlugin for CustomProviderPlugin {
    fn metadata(&self) -> PluginMetadata {
        PluginMetadata::new(
            self.name.clone(),
            self.version.clone(),
            "User".to_string(),
            self.description.clone(),
        )
    }

    async fn discover(&self, _platform: &PlatformInfo) -> PluginResult<Vec<RiDevice>> {
        let devices = (self.discover_func)();
        Ok(devices)
    }

    fn status(&self) -> PluginStatus {
        self.status.clone()
    }
}

/// Utility function to create a custom discovery plugin from a closure
pub fn create_custom_plugin<F>(name: &str, version: &str, description: &str, discover_fn: F) -> Box<dyn RiHardwareDiscoveryPlugin>
where
    F: Fn() -> Vec<RiDevice> + Send + Sync + 'static,
{
    Box::new(CustomProviderPlugin::new(name, version, description, discover_fn))
}

use std::collections::{HashMap, HashSet};