voirs-sdk 0.1.0-rc.1

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

use crate::{
    error::{Result, VoirsError},
    plugins::{manager::PluginManager, PluginConfig, PluginMetadata, PluginType, VoirsPlugin},
};
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    fs,
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
    time::SystemTime,
};
use tracing::{debug, error, info, warn};

#[cfg(feature = "plugins")]
use libloading::{Library, Symbol};
#[cfg(feature = "plugins")]
use wasmtime::{Engine, Instance, Module, Store};

/// Calculate SHA256 checksum of a file
fn calculate_checksum(path: &Path) -> Result<String> {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let contents = fs::read(path)?;
    let mut hasher = DefaultHasher::new();
    contents.hash(&mut hasher);
    Ok(format!("{:x}", hasher.finish()))
}

/// Plugin registry for discovering and loading plugins
pub struct PluginRegistry {
    /// Search paths for plugin discovery
    search_paths: Vec<PathBuf>,

    /// Discovered plugins
    plugins: Arc<RwLock<HashMap<String, PluginInfo>>>,

    /// Plugin manifest cache
    manifest_cache: Arc<RwLock<HashMap<PathBuf, PluginManifest>>>,

    /// Plugin loading blacklist
    blacklist: Arc<RwLock<HashSet<String>>>,

    /// Registry configuration
    config: RegistryConfig,

    /// Discovery statistics
    stats: Arc<RwLock<DiscoveryStats>>,
}

/// Information about a discovered plugin
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginInfo {
    /// Plugin name
    pub name: String,

    /// Plugin version
    pub version: String,

    /// Plugin description
    pub description: String,

    /// Path to plugin manifest or directory
    pub path: PathBuf,

    /// Plugin type
    pub plugin_type: PluginType,

    /// Plugin author
    pub author: String,

    /// Plugin dependencies
    pub dependencies: Vec<String>,

    /// Supported platforms
    pub supported_platforms: Vec<String>,

    /// Minimum VoiRS version required
    pub min_voirs_version: String,

    /// Last modification time
    pub last_modified: SystemTime,

    /// Whether plugin is trusted
    pub trusted: bool,

    /// Plugin size in bytes
    pub size: u64,

    /// Plugin checksum for integrity verification
    pub checksum: Option<String>,
}

/// Plugin manifest file structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginManifest {
    /// Plugin metadata
    pub plugin: PluginMetadata,

    /// Build configuration
    pub build: Option<BuildConfig>,

    /// Runtime requirements
    pub requirements: Option<RuntimeRequirements>,

    /// Plugin assets
    pub assets: Vec<AssetInfo>,

    /// License information
    pub license: Option<LicenseInfo>,

    /// Documentation links
    pub documentation: Vec<DocumentationLink>,
}

/// Build configuration for plugins
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildConfig {
    /// Target architecture
    pub target: String,

    /// Build type (debug/release)
    pub build_type: String,

    /// Compiler version used
    pub compiler_version: String,

    /// Build timestamp
    pub build_timestamp: String,

    /// Git commit hash
    pub git_hash: Option<String>,
}

/// Runtime requirements for plugins
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeRequirements {
    /// Minimum memory requirement in MB
    pub min_memory_mb: Option<u64>,

    /// Required CPU features
    pub cpu_features: Vec<String>,

    /// GPU requirements
    pub gpu_requirements: Option<GpuRequirements>,

    /// System libraries required
    pub system_libraries: Vec<String>,

    /// Environment variables required
    pub env_variables: Vec<String>,
}

/// GPU requirements specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuRequirements {
    /// Required GPU vendor (nvidia, amd, intel)
    pub vendor: Option<String>,

    /// Minimum GPU memory in MB
    pub min_memory_mb: u64,

    /// Required compute capability
    pub compute_capability: Option<String>,

    /// Required GPU APIs (cuda, opencl, vulkan)
    pub apis: Vec<String>,
}

/// Asset information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetInfo {
    /// Asset name
    pub name: String,

    /// Asset type
    pub asset_type: AssetType,

    /// Relative path from plugin directory
    pub path: PathBuf,

    /// Asset size in bytes
    pub size: u64,

    /// Asset checksum
    pub checksum: String,
}

/// Asset type classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AssetType {
    /// Compiled binary/library
    Binary,
    /// Configuration file
    Config,
    /// Data file
    Data,
    /// Documentation
    Documentation,
    /// Icon/image
    Image,
    /// Other asset type
    Other(String),
}

/// License information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseInfo {
    /// License identifier (SPDX)
    pub license: String,

    /// License file path
    pub license_file: Option<PathBuf>,

    /// Copyright notice
    pub copyright: Option<String>,
}

/// Documentation link
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentationLink {
    /// Link title
    pub title: String,

    /// Link URL
    pub url: String,

    /// Link type
    pub link_type: DocumentationType,
}

/// Documentation type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DocumentationType {
    /// API documentation
    Api,
    /// User guide
    Guide,
    /// Tutorial
    Tutorial,
    /// Examples
    Examples,
    /// Changelog
    Changelog,
    /// Other documentation
    Other(String),
}

/// Registry configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryConfig {
    /// Enable automatic discovery
    pub auto_discovery: bool,

    /// Discovery interval in seconds
    pub discovery_interval: u64,

    /// Enable plugin verification
    pub verify_plugins: bool,

    /// Enable plugin caching
    pub cache_plugins: bool,

    /// Maximum plugin size in MB
    pub max_plugin_size_mb: u64,

    /// Allowed plugin file extensions
    pub allowed_extensions: Vec<String>,

    /// Trusted plugin sources
    pub trusted_sources: Vec<String>,

    /// Maximum search depth
    pub max_search_depth: usize,
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            auto_discovery: true,
            discovery_interval: 300, // 5 minutes
            verify_plugins: true,
            cache_plugins: true,
            max_plugin_size_mb: 100,
            allowed_extensions: vec![
                ".so".to_string(),
                ".dll".to_string(),
                ".dylib".to_string(),
                ".wasm".to_string(),
            ],
            trusted_sources: vec![],
            max_search_depth: 3,
        }
    }
}

/// Plugin discovery statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiscoveryStats {
    /// Total plugins discovered
    pub total_discovered: usize,

    /// Valid plugins found
    pub valid_plugins: usize,

    /// Invalid plugins found
    pub invalid_plugins: usize,

    /// Plugins in blacklist
    pub blacklisted_plugins: usize,

    /// Last discovery timestamp
    pub last_discovery: Option<SystemTime>,

    /// Discovery duration in milliseconds
    pub discovery_duration_ms: u64,

    /// Directories scanned
    pub directories_scanned: usize,

    /// Files examined
    pub files_examined: usize,
}

impl PluginRegistry {
    /// Create new plugin registry
    pub fn new() -> Self {
        Self::with_config(RegistryConfig::default())
    }

    /// Create plugin registry with custom configuration
    pub fn with_config(config: RegistryConfig) -> Self {
        Self {
            search_paths: Vec::new(),
            plugins: Arc::new(RwLock::new(HashMap::new())),
            manifest_cache: Arc::new(RwLock::new(HashMap::new())),
            blacklist: Arc::new(RwLock::new(HashSet::new())),
            config,
            stats: Arc::new(RwLock::new(DiscoveryStats::default())),
        }
    }

    /// Add a search path for plugins
    pub fn add_search_path<P: AsRef<Path>>(&mut self, path: P) {
        let path_buf = path.as_ref().to_path_buf();
        if !self.search_paths.contains(&path_buf) {
            self.search_paths.push(path_buf);
            info!("Added plugin search path: {:?}", path.as_ref());
        }
    }

    /// Remove a search path
    pub fn remove_search_path<P: AsRef<Path>>(&mut self, path: P) {
        let path_buf = path.as_ref().to_path_buf();
        self.search_paths.retain(|p| p != &path_buf);
        info!("Removed plugin search path: {:?}", path.as_ref());
    }

    /// Get all search paths
    pub fn get_search_paths(&self) -> Vec<PathBuf> {
        self.search_paths.clone()
    }

    /// Discover plugins in search paths
    pub async fn discover_plugins(&mut self) -> Result<usize> {
        let start_time = SystemTime::now();
        let mut stats = DiscoveryStats::default();

        info!(
            "Starting plugin discovery in {} paths",
            self.search_paths.len()
        );

        let mut discovered_plugins = HashMap::new();

        for search_path in &self.search_paths {
            if !search_path.exists() {
                warn!("Search path does not exist: {:?}", search_path);
                continue;
            }

            match self.discover_in_path(search_path, &mut stats).await {
                Ok(path_plugins) => {
                    for (name, plugin_info) in path_plugins {
                        discovered_plugins.insert(name, plugin_info);
                    }
                }
                Err(e) => {
                    error!("Failed to discover plugins in {:?}: {}", search_path, e);
                    stats.invalid_plugins += 1;
                }
            }
        }

        // Update the main plugins collection
        {
            let mut plugins = self.plugins.write().expect("lock should not be poisoned");
            *plugins = discovered_plugins;
        }

        // Update statistics
        stats.total_discovered = stats.valid_plugins + stats.invalid_plugins;
        stats.last_discovery = Some(start_time);
        stats.discovery_duration_ms = start_time.elapsed().unwrap_or_default().as_millis() as u64;

        {
            let mut registry_stats = self.stats.write().expect("lock should not be poisoned");
            *registry_stats = stats.clone();
        }

        info!(
            "Plugin discovery completed: {} valid, {} invalid, {} total in {}ms",
            stats.valid_plugins,
            stats.invalid_plugins,
            stats.total_discovered,
            stats.discovery_duration_ms
        );

        Ok(stats.valid_plugins)
    }

    /// Discover plugins in a specific path
    async fn discover_in_path(
        &self,
        path: &Path,
        stats: &mut DiscoveryStats,
    ) -> Result<HashMap<String, PluginInfo>> {
        let mut plugins = HashMap::new();

        self.scan_directory(path, &mut plugins, stats, 0).await?;

        Ok(plugins)
    }

    /// Recursively scan directory for plugins
    fn scan_directory<'a>(
        &'a self,
        dir: &'a Path,
        plugins: &'a mut HashMap<String, PluginInfo>,
        stats: &'a mut DiscoveryStats,
        depth: usize,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + 'a>> {
        Box::pin(async move {
            if depth > self.config.max_search_depth {
                return Ok(());
            }

            stats.directories_scanned += 1;

            let entries = fs::read_dir(dir).map_err(|e| {
                VoirsError::plugin_error(format!("Failed to read directory {dir:?}: {e}"))
            })?;

            for entry in entries {
                let entry = entry.map_err(|e| {
                    VoirsError::plugin_error(format!("Failed to read directory entry: {e}"))
                })?;

                let path = entry.path();
                stats.files_examined += 1;

                if path.is_dir() {
                    // Check for plugin manifest in subdirectory
                    let manifest_path = path.join("plugin.toml");
                    if manifest_path.exists() {
                        match self.load_plugin_from_manifest(&manifest_path).await {
                            Ok(plugin_info) => {
                                if !self.is_blacklisted(&plugin_info.name) {
                                    plugins.insert(plugin_info.name.clone(), plugin_info);
                                    stats.valid_plugins += 1;
                                } else {
                                    stats.blacklisted_plugins += 1;
                                }
                            }
                            Err(e) => {
                                warn!("Failed to load plugin from {:?}: {}", manifest_path, e);
                                stats.invalid_plugins += 1;
                            }
                        }
                    } else {
                        // Recursively scan subdirectory
                        self.scan_directory(&path, plugins, stats, depth + 1)
                            .await?;
                    }
                } else if self.is_plugin_file(&path) {
                    // Handle direct plugin files (for simple plugins without manifests)
                    match self.create_plugin_info_from_file(&path).await {
                        Ok(plugin_info) => {
                            if !self.is_blacklisted(&plugin_info.name) {
                                plugins.insert(plugin_info.name.clone(), plugin_info);
                                stats.valid_plugins += 1;
                            } else {
                                stats.blacklisted_plugins += 1;
                            }
                        }
                        Err(e) => {
                            debug!("Skipped file {:?}: {}", path, e);
                            stats.invalid_plugins += 1;
                        }
                    }
                }
            }

            Ok(())
        })
    }

    /// Check if file is a potential plugin file
    fn is_plugin_file(&self, path: &Path) -> bool {
        if let Some(extension) = path.extension() {
            if let Some(ext_str) = extension.to_str() {
                let ext_with_dot = format!(".{ext_str}");
                return self.config.allowed_extensions.contains(&ext_with_dot);
            }
        }
        false
    }

    /// Load plugin from manifest file
    async fn load_plugin_from_manifest(&self, manifest_path: &Path) -> Result<PluginInfo> {
        let manifest_content = fs::read_to_string(manifest_path).map_err(|e| {
            VoirsError::plugin_error(format!("Failed to read manifest {manifest_path:?}: {e}"))
        })?;

        let manifest: PluginManifest = toml::from_str(&manifest_content).map_err(|e| {
            VoirsError::plugin_error(format!("Failed to parse manifest {manifest_path:?}: {e}"))
        })?;

        // Cache the manifest
        {
            let mut cache = self
                .manifest_cache
                .write()
                .expect("lock should not be poisoned");
            cache.insert(manifest_path.to_path_buf(), manifest.clone());
        }

        // Get file metadata
        let metadata = fs::metadata(manifest_path).map_err(|e| {
            VoirsError::plugin_error(format!("Failed to get metadata for {manifest_path:?}: {e}"))
        })?;

        let plugin_info = PluginInfo {
            name: manifest.plugin.name.clone(),
            version: manifest.plugin.version.clone(),
            description: manifest.plugin.description.clone(),
            path: manifest_path
                .parent()
                .unwrap_or(manifest_path)
                .to_path_buf(),
            plugin_type: manifest.plugin.plugin_type,
            author: manifest.plugin.author.clone(),
            dependencies: manifest.plugin.dependencies.clone(),
            supported_platforms: manifest
                .plugin
                .supported_platforms
                .clone()
                .unwrap_or_else(|| vec!["any".to_string()]),
            min_voirs_version: manifest
                .plugin
                .min_voirs_version
                .clone()
                .unwrap_or_else(|| "0.1.0".to_string()),
            last_modified: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
            trusted: self.is_trusted_source(manifest_path),
            size: metadata.len(),
            checksum: calculate_checksum(manifest_path).ok(),
        };

        Ok(plugin_info)
    }

    /// Create plugin info from standalone file
    async fn create_plugin_info_from_file(&self, path: &Path) -> Result<PluginInfo> {
        let metadata = fs::metadata(path).map_err(|e| {
            VoirsError::plugin_error(format!("Failed to get metadata for {path:?}: {e}"))
        })?;

        // Check file size
        if metadata.len() > self.config.max_plugin_size_mb * 1024 * 1024 {
            return Err(VoirsError::plugin_error(format!(
                "Plugin file too large: {} MB (max: {} MB)",
                metadata.len() / 1024 / 1024,
                self.config.max_plugin_size_mb
            )));
        }

        let file_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();

        let plugin_info = PluginInfo {
            name: file_name.clone(),
            version: "unknown".to_string(),
            description: format!("Plugin loaded from {}", path.display()),
            path: path.to_path_buf(),
            plugin_type: PluginType::Effect, // Default type
            author: "unknown".to_string(),
            dependencies: vec![],
            supported_platforms: vec!["any".to_string()],
            min_voirs_version: "0.1.0".to_string(),
            last_modified: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
            trusted: self.is_trusted_source(path),
            size: metadata.len(),
            checksum: None,
        };

        Ok(plugin_info)
    }

    /// Check if plugin is in blacklist
    fn is_blacklisted(&self, plugin_name: &str) -> bool {
        let blacklist = self.blacklist.read().expect("lock should not be poisoned");
        blacklist.contains(plugin_name)
    }

    /// Check if plugin source is trusted
    fn is_trusted_source(&self, path: &Path) -> bool {
        for trusted_source in &self.config.trusted_sources {
            if path.starts_with(trusted_source) {
                return true;
            }
        }
        false
    }

    /// Add plugin to blacklist
    pub fn blacklist_plugin(&self, plugin_name: &str) {
        let mut blacklist = self.blacklist.write().expect("lock should not be poisoned");
        blacklist.insert(plugin_name.to_string());
        warn!("Added plugin '{}' to blacklist", plugin_name);
    }

    /// Remove plugin from blacklist
    pub fn unblacklist_plugin(&self, plugin_name: &str) {
        let mut blacklist = self.blacklist.write().expect("lock should not be poisoned");
        blacklist.remove(plugin_name);
        info!("Removed plugin '{}' from blacklist", plugin_name);
    }

    /// Load a plugin by name
    pub async fn load_plugin(&self, name: &str) -> Result<Arc<dyn VoirsPlugin>> {
        let plugin_info = {
            let plugins = self.plugins.read().expect("lock should not be poisoned");
            plugins.get(name).cloned()
        };

        match plugin_info {
            Some(info) => {
                if self.is_blacklisted(name) {
                    return Err(VoirsError::plugin_error(format!(
                        "Plugin '{name}' is blacklisted"
                    )));
                }

                if !info.trusted && self.config.verify_plugins {
                    return Err(VoirsError::plugin_error(format!(
                        "Plugin '{name}' is not from a trusted source"
                    )));
                }

                // Implement plugin loading based on plugin type and file extension
                self.load_plugin_from_info(&info).await
            }
            None => Err(VoirsError::plugin_error(format!(
                "Plugin '{name}' not found in registry"
            ))),
        }
    }

    /// List discovered plugins
    pub fn list_plugins(&self) -> Vec<PluginInfo> {
        let plugins = self.plugins.read().expect("lock should not be poisoned");
        plugins.values().cloned().collect()
    }

    /// Get plugin info by name
    pub fn get_plugin_info(&self, name: &str) -> Option<PluginInfo> {
        let plugins = self.plugins.read().expect("lock should not be poisoned");
        plugins.get(name).cloned()
    }

    /// List plugins by type
    pub fn list_plugins_by_type(&self, plugin_type: PluginType) -> Vec<PluginInfo> {
        let plugins = self.plugins.read().expect("lock should not be poisoned");
        plugins
            .values()
            .filter(|plugin| plugin.plugin_type == plugin_type)
            .cloned()
            .collect()
    }

    /// Get plugin manifest
    pub fn get_plugin_manifest(&self, manifest_path: &Path) -> Option<PluginManifest> {
        let cache = self
            .manifest_cache
            .read()
            .expect("lock should not be poisoned");
        cache.get(manifest_path).cloned()
    }

    /// Get discovery statistics
    pub fn get_discovery_stats(&self) -> DiscoveryStats {
        let stats = self.stats.read().expect("lock should not be poisoned");
        stats.clone()
    }

    /// Get registry configuration
    pub fn get_config(&self) -> RegistryConfig {
        self.config.clone()
    }

    /// Update registry configuration
    pub fn update_config(&mut self, config: RegistryConfig) {
        self.config = config;
        info!("Updated registry configuration");
    }

    /// Clear discovery cache
    pub fn clear_cache(&self) {
        {
            let mut plugins = self.plugins.write().expect("lock should not be poisoned");
            plugins.clear();
        }
        {
            let mut cache = self
                .manifest_cache
                .write()
                .expect("lock should not be poisoned");
            cache.clear();
        }
        info!("Cleared plugin discovery cache");
    }

    /// Load plugin from plugin info
    async fn load_plugin_from_info(&self, info: &PluginInfo) -> Result<Arc<dyn VoirsPlugin>> {
        tracing::info!("Loading plugin: {} v{}", info.name, info.version);

        // Validate plugin integrity
        self.validate_plugin_integrity(info)?;

        // Determine plugin loading strategy based on file extension and type
        let plugin_path = &info.path;
        let file_extension = plugin_path
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("");

        match file_extension {
            "wasm" => self.load_wasm_plugin(info).await,
            "so" | "dll" | "dylib" => self.load_native_plugin(info).await,
            _ => {
                // Check if it's a directory with a manifest
                if plugin_path.is_dir() {
                    self.load_manifest_plugin(info).await
                } else {
                    Err(VoirsError::plugin_error(format!(
                        "Unsupported plugin format: {} (file: {})",
                        file_extension,
                        plugin_path.display()
                    )))
                }
            }
        }
    }

    /// Validate plugin integrity and security
    fn validate_plugin_integrity(&self, info: &PluginInfo) -> Result<()> {
        // Check if plugin path exists
        if !info.path.exists() {
            return Err(VoirsError::plugin_error(format!(
                "Plugin file not found: {}",
                info.path.display()
            )));
        }

        // Validate file size
        if info.size > self.config.max_plugin_size_mb * 1024 * 1024 {
            return Err(VoirsError::plugin_error(format!(
                "Plugin file too large: {} MB (max: {} MB)",
                info.size / 1024 / 1024,
                self.config.max_plugin_size_mb
            )));
        }

        // Verify checksum if available
        if let Some(expected_checksum) = &info.checksum {
            let actual_checksum = calculate_checksum(&info.path)?;
            if &actual_checksum != expected_checksum {
                return Err(VoirsError::plugin_error(format!(
                    "Plugin checksum mismatch for '{}': expected {}, got {}",
                    info.name, expected_checksum, actual_checksum
                )));
            }
        }

        // Additional security checks
        if !info.trusted && self.config.verify_plugins {
            return Err(VoirsError::plugin_error(format!(
                "Plugin '{}' is not from a trusted source and verification is enabled",
                info.name
            )));
        }

        Ok(())
    }

    /// Load WASM plugin
    async fn load_wasm_plugin(&self, info: &PluginInfo) -> Result<Arc<dyn VoirsPlugin>> {
        tracing::debug!("Loading WASM plugin: {}", info.name);

        #[cfg(not(feature = "plugins"))]
        {
            Err(VoirsError::plugin_error(format!(
                "WASM plugin loading requires the 'plugins' feature for '{}'",
                info.name
            )))
        }

        #[cfg(feature = "plugins")]
        {
            // Read WASM file
            let wasm_bytes = fs::read(&info.path).map_err(|e| {
                VoirsError::plugin_error(format!(
                    "Failed to read WASM file '{}': {}",
                    info.path.display(),
                    e
                ))
            })?;

            // Create WASM engine and compile module
            let engine = Engine::default();
            let module = Module::new(&engine, &wasm_bytes).map_err(|e| {
                VoirsError::plugin_error(format!(
                    "Failed to compile WASM module '{}': {}",
                    info.name, e
                ))
            })?;

            // Create plugin wrapper
            let plugin = Arc::new(WasmPluginWrapper::new(
                info.clone(),
                Arc::new(engine),
                Arc::new(module),
            ));

            tracing::info!("Successfully loaded WASM plugin: {}", info.name);
            Ok(plugin as Arc<dyn VoirsPlugin>)
        }
    }

    /// Load native dynamic library plugin
    async fn load_native_plugin(&self, info: &PluginInfo) -> Result<Arc<dyn VoirsPlugin>> {
        tracing::debug!("Loading native plugin: {}", info.name);

        #[cfg(not(feature = "plugins"))]
        {
            Err(VoirsError::plugin_error(format!(
                "Native plugin loading requires the 'plugins' feature for '{}'",
                info.name
            )))
        }

        #[cfg(feature = "plugins")]
        {
            // Load dynamic library
            let library = unsafe {
                Library::new(&info.path).map_err(|e| {
                    VoirsError::plugin_error(format!(
                        "Failed to load native library '{}': {}",
                        info.path.display(),
                        e
                    ))
                })?
            };

            let library = Arc::new(library);

            // Look for the plugin factory function
            let create_plugin: Symbol<unsafe extern "C" fn() -> *mut dyn VoirsPlugin> = unsafe {
                library.get(b"create_voirs_plugin").map_err(|e| {
                    VoirsError::plugin_error(format!(
                        "Plugin factory function 'create_voirs_plugin' not found in '{}': {}",
                        info.name, e
                    ))
                })?
            };

            // Call factory function
            let plugin_ptr = unsafe { create_plugin() };
            if plugin_ptr.is_null() {
                return Err(VoirsError::plugin_error(format!(
                    "Plugin factory returned null for '{}'",
                    info.name
                )));
            }

            let plugin = unsafe { Arc::from_raw(plugin_ptr) };

            // Create wrapper to manage the library lifetime
            let wrapped_plugin = Arc::new(NativePluginWrapper::new(plugin, library, info.clone()));

            tracing::info!("Successfully loaded native plugin: {}", info.name);
            Ok(wrapped_plugin as Arc<dyn VoirsPlugin>)
        }
    }

    /// Load plugin from manifest directory
    async fn load_manifest_plugin(&self, info: &PluginInfo) -> Result<Arc<dyn VoirsPlugin>> {
        tracing::debug!("Loading manifest plugin: {}", info.name);

        let manifest_path = info.path.join("plugin.toml");
        if !manifest_path.exists() {
            return Err(VoirsError::plugin_error(format!(
                "Plugin manifest not found: {}",
                manifest_path.display()
            )));
        }

        // Load and parse manifest
        let manifest = self.get_plugin_manifest(&manifest_path).ok_or_else(|| {
            VoirsError::plugin_error(format!(
                "Failed to load plugin manifest for '{}'",
                info.name
            ))
        })?;

        // For now, create a built-in plugin implementation based on the type
        match info.plugin_type {
            PluginType::Effect => self.create_builtin_effect_plugin(&manifest),
            PluginType::VoiceEffect => self.create_builtin_voice_effect_plugin(&manifest),
            PluginType::TextProcessor => self.create_builtin_text_processor_plugin(&manifest),
            PluginType::ModelEnhancer => self.create_builtin_model_enhancer_plugin(&manifest),
            PluginType::OutputProcessor => self.create_builtin_output_processor_plugin(&manifest),
        }
    }

    /// Create built-in effect plugin implementation
    fn create_builtin_effect_plugin(
        &self,
        manifest: &PluginManifest,
    ) -> Result<Arc<dyn VoirsPlugin>> {
        Ok(Arc::new(BuiltinEffectPlugin {
            metadata: manifest.plugin.clone(),
        }))
    }

    /// Create built-in voice effect plugin implementation
    fn create_builtin_voice_effect_plugin(
        &self,
        manifest: &PluginManifest,
    ) -> Result<Arc<dyn VoirsPlugin>> {
        Ok(Arc::new(BuiltinVoiceEffectPlugin {
            metadata: manifest.plugin.clone(),
        }))
    }

    /// Create built-in text processor plugin implementation
    fn create_builtin_text_processor_plugin(
        &self,
        manifest: &PluginManifest,
    ) -> Result<Arc<dyn VoirsPlugin>> {
        Ok(Arc::new(BuiltinTextProcessorPlugin {
            metadata: manifest.plugin.clone(),
        }))
    }

    /// Create built-in model enhancer plugin implementation
    fn create_builtin_model_enhancer_plugin(
        &self,
        manifest: &PluginManifest,
    ) -> Result<Arc<dyn VoirsPlugin>> {
        Ok(Arc::new(BuiltinModelEnhancerPlugin {
            metadata: manifest.plugin.clone(),
        }))
    }

    /// Create built-in output processor plugin implementation
    fn create_builtin_output_processor_plugin(
        &self,
        manifest: &PluginManifest,
    ) -> Result<Arc<dyn VoirsPlugin>> {
        Ok(Arc::new(BuiltinOutputProcessorPlugin {
            metadata: manifest.plugin.clone(),
        }))
    }

    /// Install plugin to manager
    pub async fn install_plugin(
        &self,
        name: &str,
        manager: &PluginManager,
        config: Option<PluginConfig>,
    ) -> Result<()> {
        let plugin = self.load_plugin(name).await?;
        manager
            .register_plugin(name.to_string(), plugin, config)
            .await
    }
}

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

// Built-in plugin implementations for manifest-based plugins

/// Built-in effect plugin implementation
struct BuiltinEffectPlugin {
    metadata: PluginMetadata,
}

impl VoirsPlugin for BuiltinEffectPlugin {
    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn version(&self) -> &str {
        &self.metadata.version
    }

    fn description(&self) -> &str {
        &self.metadata.description
    }

    fn author(&self) -> &str {
        &self.metadata.author
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Built-in voice effect plugin implementation
struct BuiltinVoiceEffectPlugin {
    metadata: PluginMetadata,
}

impl VoirsPlugin for BuiltinVoiceEffectPlugin {
    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn version(&self) -> &str {
        &self.metadata.version
    }

    fn description(&self) -> &str {
        &self.metadata.description
    }

    fn author(&self) -> &str {
        &self.metadata.author
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Built-in text processor plugin implementation
struct BuiltinTextProcessorPlugin {
    metadata: PluginMetadata,
}

impl VoirsPlugin for BuiltinTextProcessorPlugin {
    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn version(&self) -> &str {
        &self.metadata.version
    }

    fn description(&self) -> &str {
        &self.metadata.description
    }

    fn author(&self) -> &str {
        &self.metadata.author
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Built-in model enhancer plugin implementation
struct BuiltinModelEnhancerPlugin {
    metadata: PluginMetadata,
}

impl VoirsPlugin for BuiltinModelEnhancerPlugin {
    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn version(&self) -> &str {
        &self.metadata.version
    }

    fn description(&self) -> &str {
        &self.metadata.description
    }

    fn author(&self) -> &str {
        &self.metadata.author
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Built-in output processor plugin implementation
struct BuiltinOutputProcessorPlugin {
    metadata: PluginMetadata,
}

impl VoirsPlugin for BuiltinOutputProcessorPlugin {
    fn name(&self) -> &str {
        &self.metadata.name
    }

    fn version(&self) -> &str {
        &self.metadata.version
    }

    fn description(&self) -> &str {
        &self.metadata.description
    }

    fn author(&self) -> &str {
        &self.metadata.author
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// Plugin wrapper implementations for WASM and native plugins

#[cfg(feature = "plugins")]
/// WebAssembly plugin wrapper
pub struct WasmPluginWrapper {
    info: PluginInfo,
    engine: Arc<Engine>,
    module: Arc<Module>,
}

#[cfg(feature = "plugins")]
impl WasmPluginWrapper {
    pub fn new(info: PluginInfo, engine: Arc<Engine>, module: Arc<Module>) -> Self {
        Self {
            info,
            engine,
            module,
        }
    }

    fn create_store(&self) -> Store<()> {
        Store::new(&self.engine, ())
    }

    fn call_wasm_function(&self, function_name: &str) -> Result<i32> {
        let mut store = self.create_store();
        let instance = Instance::new(&mut store, &self.module, &[]).map_err(|e| {
            VoirsError::plugin_error(format!("Failed to instantiate WASM module: {}", e))
        })?;

        let func = instance
            .get_typed_func::<(), i32>(&mut store, function_name)
            .map_err(|e| {
                VoirsError::plugin_error(format!("Function '{}' not found: {}", function_name, e))
            })?;

        let result = func
            .call(&mut store, ())
            .map_err(|e| VoirsError::plugin_error(format!("WASM function call failed: {}", e)))?;

        Ok(result)
    }
}

#[cfg(feature = "plugins")]
impl VoirsPlugin for WasmPluginWrapper {
    fn name(&self) -> &str {
        &self.info.name
    }

    fn version(&self) -> &str {
        &self.info.version
    }

    fn description(&self) -> &str {
        &self.info.description
    }

    fn author(&self) -> &str {
        &self.info.author
    }

    fn metadata(&self) -> PluginMetadata {
        PluginMetadata {
            name: self.info.name.clone(),
            version: self.info.version.clone(),
            description: self.info.description.clone(),
            author: self.info.author.clone(),
            plugin_type: self.info.plugin_type,
            supported_formats: vec!["wav".to_string(), "mp3".to_string(), "flac".to_string()], // Default supported formats
            capabilities: vec!["wasm".to_string(), "execute".to_string()], // WASM-specific capabilities
            dependencies: self.info.dependencies.clone(),
            supported_platforms: Some(self.info.supported_platforms.clone()),
            min_voirs_version: Some(self.info.min_voirs_version.clone()),
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(feature = "plugins")]
/// Native plugin wrapper
pub struct NativePluginWrapper {
    plugin: Arc<dyn VoirsPlugin>,
    #[allow(dead_code)]
    library: Arc<Library>, // Keep library alive
    info: PluginInfo,
}

#[cfg(feature = "plugins")]
impl NativePluginWrapper {
    pub fn new(plugin: Arc<dyn VoirsPlugin>, library: Arc<Library>, info: PluginInfo) -> Self {
        Self {
            plugin,
            library,
            info,
        }
    }
}

#[cfg(feature = "plugins")]
impl VoirsPlugin for NativePluginWrapper {
    fn name(&self) -> &str {
        self.plugin.name()
    }

    fn version(&self) -> &str {
        self.plugin.version()
    }

    fn description(&self) -> &str {
        self.plugin.description()
    }

    fn author(&self) -> &str {
        self.plugin.author()
    }

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

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_registry_creation() {
        let registry = PluginRegistry::new();
        assert_eq!(registry.get_search_paths().len(), 0);
        assert_eq!(registry.list_plugins().len(), 0);
    }

    #[tokio::test]
    async fn test_search_path_management() {
        let mut registry = PluginRegistry::new();
        let temp_dir = TempDir::new().unwrap();

        // Add search path
        registry.add_search_path(temp_dir.path());
        assert_eq!(registry.get_search_paths().len(), 1);

        // Remove search path
        registry.remove_search_path(temp_dir.path());
        assert_eq!(registry.get_search_paths().len(), 0);
    }

    #[tokio::test]
    async fn test_blacklist_management() {
        let registry = PluginRegistry::new();

        // Test blacklisting
        assert!(!registry.is_blacklisted("test_plugin"));
        registry.blacklist_plugin("test_plugin");
        assert!(registry.is_blacklisted("test_plugin"));

        // Test unblacklisting
        registry.unblacklist_plugin("test_plugin");
        assert!(!registry.is_blacklisted("test_plugin"));
    }

    #[tokio::test]
    async fn test_empty_directory_discovery() {
        let mut registry = PluginRegistry::new();
        let temp_dir = TempDir::new().unwrap();

        registry.add_search_path(temp_dir.path());
        let discovered = registry.discover_plugins().await.unwrap();
        assert_eq!(discovered, 0);

        let stats = registry.get_discovery_stats();
        assert_eq!(stats.valid_plugins, 0);
        assert_eq!(stats.directories_scanned, 1);
    }
}