voirs-cli 0.1.0-rc.1

Command-line interface 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
//! CLI-specific configuration utilities.

pub mod profiles;

use crate::error::{CliError, Result};
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use voirs_sdk::config::AppConfig;

/// CLI-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliConfig {
    /// Core VoiRS configuration
    #[serde(flatten)]
    pub core: AppConfig,

    /// CLI-specific settings
    pub cli: CliSettings,
}

/// Alias for compatibility with interactive modules
pub type Config = CliConfig;

/// CLI-specific settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliSettings {
    /// Default output format
    pub default_output_format: String,

    /// Default voice
    pub default_voice: Option<String>,

    /// Default quality level
    pub default_quality: String,

    /// Enable colored output
    pub colored_output: bool,

    /// Show progress bars
    pub show_progress: bool,

    /// Auto-play synthesized audio
    pub auto_play: bool,

    /// Preferred output directory
    pub output_directory: Option<PathBuf>,

    /// SSML validation level
    pub ssml_validation: SsmlValidationLevel,

    /// Recent files history size
    pub history_size: usize,

    /// Voice download preferences
    pub download: DownloadSettings,
}

/// SSML validation levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SsmlValidationLevel {
    /// No validation
    None,
    /// Warn on issues
    Warn,
    /// Error on issues
    Strict,
}

/// Download settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadSettings {
    /// Parallel downloads
    pub parallel_downloads: usize,

    /// Retry attempts
    pub retry_attempts: usize,

    /// Auto-verify checksums
    pub verify_checksums: bool,

    /// Preferred download mirrors
    pub preferred_mirrors: Vec<String>,
}

impl Default for CliConfig {
    fn default() -> Self {
        Self {
            core: AppConfig::default(),
            cli: CliSettings::default(),
        }
    }
}

impl Default for CliSettings {
    fn default() -> Self {
        Self {
            default_output_format: "wav".to_string(),
            default_voice: None,
            default_quality: "high".to_string(),
            colored_output: true,
            show_progress: true,
            auto_play: false,
            output_directory: None,
            ssml_validation: SsmlValidationLevel::Warn,
            history_size: 100,
            download: DownloadSettings::default(),
        }
    }
}

impl Default for DownloadSettings {
    fn default() -> Self {
        Self {
            parallel_downloads: 3,
            retry_attempts: 3,
            verify_checksums: true,
            preferred_mirrors: vec![
                "https://huggingface.co".to_string(),
                "https://github.com".to_string(),
            ],
        }
    }
}

/// Configuration manager for the CLI
pub struct ConfigManager {
    config_path: PathBuf,
    config: CliConfig,
}

impl ConfigManager {
    /// Create a new configuration manager
    pub fn new() -> Result<Self> {
        let config_path = Self::find_config_file().unwrap_or_else(Self::default_config_path);

        let config = if config_path.exists() {
            Self::load_from_file(&config_path)?
        } else {
            CliConfig::default()
        };

        Ok(Self {
            config_path,
            config,
        })
    }

    /// Create configuration manager with specific path
    pub fn with_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        let config_path = path.as_ref().to_path_buf();

        let config = if config_path.exists() {
            Self::load_from_file(&config_path)?
        } else {
            CliConfig::default()
        };

        Ok(Self {
            config_path,
            config,
        })
    }

    /// Get the current configuration
    pub fn config(&self) -> &CliConfig {
        &self.config
    }

    /// Get mutable reference to configuration
    pub fn config_mut(&mut self) -> &mut CliConfig {
        &mut self.config
    }

    /// Save configuration to file
    pub fn save(&self) -> Result<()> {
        // Create parent directory if it doesn't exist
        if let Some(parent) = self.config_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                CliError::file_operation("create directory", &parent.display().to_string(), e)
            })?;
        }

        let content = toml::to_string_pretty(&self.config).map_err(CliError::from)?;

        fs::write(&self.config_path, content).map_err(|e| {
            CliError::file_operation("write", &self.config_path.display().to_string(), e)
        })?;

        Ok(())
    }

    /// Update configuration value
    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
        match key {
            "default_output_format" => {
                self.config.cli.default_output_format = value.to_string();
            }
            "default_voice" => {
                self.config.cli.default_voice = if value.is_empty() {
                    None
                } else {
                    Some(value.to_string())
                };
            }
            "default_quality" => {
                if ["low", "medium", "high", "ultra"].contains(&value) {
                    self.config.cli.default_quality = value.to_string();
                } else {
                    return Err(CliError::invalid_parameter(
                        key,
                        "must be one of: low, medium, high, ultra",
                    ));
                }
            }
            "colored_output" => {
                self.config.cli.colored_output = value
                    .parse()
                    .map_err(|_| CliError::invalid_parameter(key, "must be true or false"))?;
            }
            "show_progress" => {
                self.config.cli.show_progress = value
                    .parse()
                    .map_err(|_| CliError::invalid_parameter(key, "must be true or false"))?;
            }
            "auto_play" => {
                self.config.cli.auto_play = value
                    .parse()
                    .map_err(|_| CliError::invalid_parameter(key, "must be true or false"))?;
            }
            "output_directory" => {
                self.config.cli.output_directory = if value.is_empty() {
                    None
                } else {
                    Some(PathBuf::from(value))
                };
            }
            _ => {
                return Err(CliError::invalid_parameter(
                    key,
                    "unknown configuration key",
                ));
            }
        }

        Ok(())
    }

    /// Get configuration value as string
    pub fn get_value(&self, key: &str) -> Option<String> {
        match key {
            "default_output_format" => Some(self.config.cli.default_output_format.clone()),
            "default_voice" => self.config.cli.default_voice.clone(),
            "default_quality" => Some(self.config.cli.default_quality.clone()),
            "colored_output" => Some(self.config.cli.colored_output.to_string()),
            "show_progress" => Some(self.config.cli.show_progress.to_string()),
            "auto_play" => Some(self.config.cli.auto_play.to_string()),
            "output_directory" => self
                .config
                .cli
                .output_directory
                .as_ref()
                .map(|p| p.display().to_string()),
            _ => None,
        }
    }

    /// Apply environment variable overrides
    pub fn apply_env_overrides(&mut self) {
        if let Ok(format) = env::var("VOIRS_OUTPUT_FORMAT") {
            self.config.cli.default_output_format = format;
        }

        if let Ok(voice) = env::var("VOIRS_DEFAULT_VOICE") {
            self.config.cli.default_voice = Some(voice);
        }

        if let Ok(quality) = env::var("VOIRS_QUALITY") {
            if ["low", "medium", "high", "ultra"].contains(&quality.as_str()) {
                self.config.cli.default_quality = quality;
            }
        }

        if let Ok(colored) = env::var("VOIRS_COLORED_OUTPUT") {
            if let Ok(value) = colored.parse() {
                self.config.cli.colored_output = value;
            }
        }

        if let Ok(progress) = env::var("VOIRS_SHOW_PROGRESS") {
            if let Ok(value) = progress.parse() {
                self.config.cli.show_progress = value;
            }
        }

        if let Ok(output_dir) = env::var("VOIRS_OUTPUT_DIR") {
            self.config.cli.output_directory = Some(PathBuf::from(output_dir));
        }
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<Vec<String>> {
        let mut warnings = Vec::new();

        // Check if default voice exists
        if let Some(ref voice) = self.config.cli.default_voice {
            // Validate voice existence by checking if it can be resolved
            match self.validate_voice_exists(voice) {
                Ok(true) => {
                    // Voice exists, no warning needed
                }
                Ok(false) => {
                    warnings.push(format!(
                        "Default voice '{}' does not exist. Use 'voirs voices list' to see available voices.",
                        voice
                    ));
                }
                Err(_) => {
                    // Could not validate (e.g., voice system not initialized)
                    // This is not critical, just note it as a warning
                    warnings.push(format!(
                        "Could not verify existence of default voice '{}'. Voice system may not be initialized.",
                        voice
                    ));
                }
            }
        }

        // Check output directory
        if let Some(ref output_dir) = self.config.cli.output_directory {
            if !output_dir.exists() {
                warnings.push(format!(
                    "Output directory '{}' does not exist",
                    output_dir.display()
                ));
            } else if !output_dir.is_dir() {
                return Err(CliError::config(format!(
                    "Output directory '{}' is not a directory",
                    output_dir.display()
                )));
            }
        }

        // Validate download settings
        if self.config.cli.download.parallel_downloads == 0 {
            return Err(CliError::config(
                "parallel_downloads must be greater than 0",
            ));
        }

        if self.config.cli.download.parallel_downloads > 10 {
            warnings.push("parallel_downloads > 10 may cause server rate limiting".to_string());
        }

        Ok(warnings)
    }

    /// Validate if a voice exists in the system
    fn validate_voice_exists(&self, voice_id: &str) -> Result<bool> {
        // Try to check if voice exists by looking in standard voice directories
        // This is a lightweight check that doesn't require initializing the full pipeline

        // Get potential voice directories
        let voice_dirs = self.get_voice_directories();

        for voice_dir in voice_dirs {
            let voice_config_path = voice_dir.join(voice_id).join("voice.json");
            if voice_config_path.exists() {
                // Found the voice config file
                return Ok(true);
            }
        }

        // Voice not found in standard directories
        Ok(false)
    }

    /// Get list of directories where voices might be stored
    fn get_voice_directories(&self) -> Vec<PathBuf> {
        let mut dirs = Vec::new();

        // 1. Check default data directory (~/.voirs/voices)
        if let Some(home) = dirs::home_dir() {
            dirs.push(home.join(".voirs").join("voices"));
        }

        // 3. Check XDG data directory on Linux
        #[cfg(target_os = "linux")]
        {
            if let Ok(xdg_data_home) = std::env::var("XDG_DATA_HOME") {
                dirs.push(PathBuf::from(xdg_data_home).join("voirs").join("voices"));
            } else if let Some(home) = dirs::home_dir() {
                dirs.push(
                    home.join(".local")
                        .join("share")
                        .join("voirs")
                        .join("voices"),
                );
            }
        }

        // 4. Check Library directory on macOS
        #[cfg(target_os = "macos")]
        {
            if let Some(home) = dirs::home_dir() {
                dirs.push(
                    home.join("Library")
                        .join("Application Support")
                        .join("voirs")
                        .join("voices"),
                );
            }
        }

        // 5. Check AppData on Windows
        #[cfg(target_os = "windows")]
        {
            if let Ok(appdata) = std::env::var("APPDATA") {
                dirs.push(PathBuf::from(appdata).join("voirs").join("voices"));
            }
        }

        // 6. Check current directory (for development/testing)
        dirs.push(PathBuf::from("./voices"));

        dirs
    }

    /// Get configuration path
    pub fn config_path(&self) -> &Path {
        &self.config_path
    }

    /// Load configuration from file
    fn load_from_file<P: AsRef<Path>>(path: P) -> Result<CliConfig> {
        let content = fs::read_to_string(path.as_ref()).map_err(|e| {
            CliError::file_operation("read", &path.as_ref().display().to_string(), e)
        })?;

        // Try TOML first, then JSON for backward compatibility
        if let Ok(config) = toml::from_str::<CliConfig>(&content) {
            Ok(config)
        } else {
            serde_json::from_str::<CliConfig>(&content)
                .map_err(|e| CliError::config(format!("Invalid configuration format: {}", e)))
        }
    }

    /// Find configuration file in standard locations
    fn find_config_file() -> Option<PathBuf> {
        let possible_paths = [
            env::current_dir().ok().map(|d| d.join("voirs.toml")),
            env::current_dir().ok().map(|d| d.join("voirs.json")),
            Self::config_dir().map(|d| d.join("voirs.toml")),
            Self::config_dir().map(|d| d.join("voirs.json")),
            env::var("VOIRS_CONFIG").ok().map(PathBuf::from),
        ];

        possible_paths
            .into_iter()
            .flatten()
            .find(|path| path.exists())
    }

    /// Get default configuration path
    fn default_config_path() -> PathBuf {
        Self::config_dir()
            .unwrap_or_else(|| env::current_dir().expect("current dir should be accessible"))
            .join("voirs.toml")
    }

    /// Get configuration directory
    fn config_dir() -> Option<PathBuf> {
        if let Some(config_dir) = env::var_os("XDG_CONFIG_HOME") {
            Some(PathBuf::from(config_dir).join("voirs"))
        } else if let Some(home_dir) = env::var_os("HOME") {
            Some(PathBuf::from(home_dir).join(".config").join("voirs"))
        } else {
            env::var_os("APPDATA").map(|app_data| PathBuf::from(app_data).join("voirs"))
        }
    }
}

/// Configuration utilities
pub mod utils {
    use super::*;

    /// Create a default configuration file
    pub fn create_default_config<P: AsRef<Path>>(path: P) -> Result<()> {
        let config = CliConfig::default();
        let content = toml::to_string_pretty(&config).map_err(CliError::from)?;

        if let Some(parent) = path.as_ref().parent() {
            fs::create_dir_all(parent).map_err(|e| {
                CliError::file_operation("create directory", &parent.display().to_string(), e)
            })?;
        }

        fs::write(path.as_ref(), content).map_err(|e| {
            CliError::file_operation("write", &path.as_ref().display().to_string(), e)
        })?;

        Ok(())
    }

    /// Migrate old configuration format to new format
    pub fn migrate_config<P: AsRef<Path>>(old_path: P, new_path: P) -> Result<()> {
        let old_content = fs::read_to_string(old_path.as_ref()).map_err(|e| {
            CliError::file_operation("read", &old_path.as_ref().display().to_string(), e)
        })?;

        // Try to parse as old format (assuming it was JSON)
        let old_config: serde_json::Value = serde_json::from_str(&old_content)
            .map_err(|e| CliError::config(format!("Cannot parse old config: {}", e)))?;

        // Create new config with migrated values
        let mut new_config = CliConfig::default();

        // Migrate known fields (this is a simplified example)
        if let Some(output_format) = old_config.get("output_format") {
            if let Some(format_str) = output_format.as_str() {
                new_config.cli.default_output_format = format_str.to_string();
            }
        }

        // Save migrated config
        let content = toml::to_string_pretty(&new_config).map_err(CliError::from)?;

        fs::write(new_path.as_ref(), content).map_err(|e| {
            CliError::file_operation("write", &new_path.as_ref().display().to_string(), e)
        })?;

        Ok(())
    }

    /// Export configuration for sharing
    pub fn export_config<P: AsRef<Path>>(
        config: &CliConfig,
        path: P,
        format: ConfigFormat,
    ) -> Result<()> {
        let content = match format {
            ConfigFormat::Toml => toml::to_string_pretty(config)?,
            ConfigFormat::Json => serde_json::to_string_pretty(config)?,
            ConfigFormat::Yaml => serde_yaml::to_string(config)
                .map_err(|e| CliError::config(format!("YAML serialization error: {}", e)))?,
        };

        fs::write(path.as_ref(), content).map_err(|e| {
            CliError::file_operation("write", &path.as_ref().display().to_string(), e)
        })?;

        Ok(())
    }
}

/// Enhanced configuration loader with performance optimizations
pub struct EnhancedConfigLoader {
    cache: Option<(PathBuf, std::time::SystemTime, CliConfig)>,
}

impl EnhancedConfigLoader {
    /// Create a new enhanced configuration loader
    pub fn new() -> Self {
        Self { cache: None }
    }

    /// Load configuration with caching and smart format detection
    pub fn load_config<P: AsRef<Path>>(&mut self, path: P) -> Result<CliConfig> {
        let path = path.as_ref();
        let start_time = Instant::now();

        // Check cache validity
        if let Some((cached_path, cached_time, ref cached_config)) = &self.cache {
            if cached_path == path {
                if let Ok(metadata) = fs::metadata(path) {
                    if let Ok(modified) = metadata.modified() {
                        if modified <= *cached_time {
                            // Cache hit - return cached config
                            return Ok(cached_config.clone());
                        }
                    }
                }
            }
        }

        // Cache miss - load from file
        let content = fs::read_to_string(path)
            .map_err(|e| CliError::file_operation("read", &path.display().to_string(), e))?;

        let config = self.parse_config_content(&content, path)?;

        // Update cache
        if let Ok(metadata) = fs::metadata(path) {
            if let Ok(modified) = metadata.modified() {
                self.cache = Some((path.to_path_buf(), modified, config.clone()));
            }
        }

        let load_time = start_time.elapsed();
        if load_time > Duration::from_millis(100) {
            eprintln!("Warning: Configuration loading took {:?}", load_time);
        }

        Ok(config)
    }

    /// Parse configuration content with smart format detection
    fn parse_config_content<P: AsRef<Path>>(&self, content: &str, path: P) -> Result<CliConfig> {
        let extension = path.as_ref().extension().and_then(|ext| ext.to_str());

        // Try format detection based on file extension first
        match extension {
            Some("toml") => {
                match toml::from_str::<CliConfig>(content) {
                    Ok(config) => return Ok(config),
                    Err(e) => {
                        // If TOML parsing fails, try fallback formats
                        eprintln!("TOML parsing failed: {}, trying fallback formats", e);
                    }
                }
            }
            Some("json") => match serde_json::from_str::<CliConfig>(content) {
                Ok(config) => return Ok(config),
                Err(e) => {
                    eprintln!("JSON parsing failed: {}, trying fallback formats", e);
                }
            },
            Some("yaml") | Some("yml") => match serde_yaml::from_str::<CliConfig>(content) {
                Ok(config) => return Ok(config),
                Err(e) => {
                    eprintln!("YAML parsing failed: {}, trying fallback formats", e);
                }
            },
            _ => {
                // No extension or unknown extension - try content-based detection
            }
        }

        // Content-based format detection with smart heuristics
        let trimmed = content.trim();

        // Try TOML first (most common format)
        if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
            if let Ok(config) = toml::from_str::<CliConfig>(content) {
                return Ok(config);
            }
        }

        // Try JSON if content looks like JSON
        if trimmed.starts_with('{') && trimmed.ends_with('}') {
            if let Ok(config) = serde_json::from_str::<CliConfig>(content) {
                return Ok(config);
            }
        }

        // Try YAML as last resort
        if let Ok(config) = serde_yaml::from_str::<CliConfig>(content) {
            return Ok(config);
        }

        Err(CliError::config(format!(
            "Unable to parse configuration file '{}' - tried TOML, JSON, and YAML formats",
            path.as_ref().display()
        )))
    }

    /// Clear the configuration cache
    pub fn clear_cache(&mut self) {
        self.cache = None;
    }

    /// Check if configuration is cached
    pub fn is_cached<P: AsRef<Path>>(&self, path: P) -> bool {
        if let Some((cached_path, _, _)) = &self.cache {
            cached_path == path.as_ref()
        } else {
            false
        }
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> Option<(PathBuf, std::time::SystemTime)> {
        self.cache
            .as_ref()
            .map(|(path, time, _)| (path.clone(), *time))
    }
}

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

/// Configuration validation utilities
pub mod validation {
    use super::*;
    use std::time::{Duration, Instant};

    /// Validate configuration with detailed reporting
    pub fn validate_config_detailed(config: &CliConfig) -> Result<ValidationReport> {
        let mut report = ValidationReport::new();
        let start_time = Instant::now();

        // Validate CLI settings
        validate_cli_settings(&config.cli, &mut report)?;

        // Validate core configuration
        validate_core_config(&config.core, &mut report)?;

        // Performance check
        let validation_time = start_time.elapsed();
        if validation_time > Duration::from_millis(50) {
            report.add_warning(format!(
                "Configuration validation took {:?} - consider optimizing",
                validation_time
            ));
        }

        Ok(report)
    }

    /// Validate CLI-specific settings
    fn validate_cli_settings(settings: &CliSettings, report: &mut ValidationReport) -> Result<()> {
        // Validate output format
        let valid_formats = ["wav", "mp3", "flac", "ogg", "m4a"];
        if !valid_formats.contains(&settings.default_output_format.as_str()) {
            report.add_error(format!(
                "Invalid default output format '{}'. Valid formats: {}",
                settings.default_output_format,
                valid_formats.join(", ")
            ));
        }

        // Validate quality level
        let valid_qualities = ["low", "medium", "high", "ultra"];
        if !valid_qualities.contains(&settings.default_quality.as_str()) {
            report.add_error(format!(
                "Invalid default quality '{}'. Valid qualities: {}",
                settings.default_quality,
                valid_qualities.join(", ")
            ));
        }

        // Validate output directory
        if let Some(ref output_dir) = settings.output_directory {
            if !output_dir.exists() {
                report.add_warning(format!(
                    "Output directory '{}' does not exist",
                    output_dir.display()
                ));
            } else if !output_dir.is_dir() {
                report.add_error(format!(
                    "Output directory '{}' is not a directory",
                    output_dir.display()
                ));
            }
        }

        // Validate download settings
        if settings.download.parallel_downloads == 0 {
            report.add_error("parallel_downloads must be greater than 0".to_string());
        } else if settings.download.parallel_downloads > 20 {
            report.add_warning(format!(
                "parallel_downloads ({}) is very high and may cause issues",
                settings.download.parallel_downloads
            ));
        }

        if settings.download.retry_attempts > 10 {
            report.add_warning(format!(
                "retry_attempts ({}) is very high and may cause long delays",
                settings.download.retry_attempts
            ));
        }

        Ok(())
    }

    /// Validate core configuration
    fn validate_core_config(config: &AppConfig, report: &mut ValidationReport) -> Result<()> {
        // Validate device configuration
        match config.pipeline.device.as_str() {
            "cpu" => {
                report.add_info("Using CPU device - synthesis will be slower than GPU".to_string());
            }
            "gpu" | "cuda" => {
                report.add_info("GPU acceleration enabled - ensure CUDA is available".to_string());
                #[cfg(not(feature = "cuda"))]
                report.add_warning(
                    "GPU device specified but CUDA feature not enabled in build".to_string(),
                );
            }
            "metal" => {
                report.add_info("Metal acceleration enabled - macOS only".to_string());
                #[cfg(not(target_os = "macos"))]
                report.add_error("Metal device is only available on macOS".to_string());
                #[cfg(not(feature = "metal"))]
                report.add_warning(
                    "Metal device specified but metal feature not enabled in build".to_string(),
                );
            }
            other => {
                report.add_error(format!(
                    "Invalid device '{}' - must be 'cpu', 'gpu', 'cuda', or 'metal'",
                    other
                ));
            }
        }

        // Validate threads configuration
        if let Some(threads) = config.pipeline.num_threads {
            if threads == 0 {
                report.add_error("num_threads must be greater than 0".to_string());
            } else if threads > num_cpus::get() * 2 {
                report.add_warning(format!(
                    "num_threads ({}) exceeds 2x CPU count ({}) - may cause overhead",
                    threads,
                    num_cpus::get()
                ));
            }
        }

        // Validate sample rate from default synthesis config
        let sample_rate = config.pipeline.default_synthesis.sample_rate;
        match sample_rate {
            8000 | 16000 | 22050 | 24000 | 32000 | 44100 | 48000 => {
                // Standard sample rates are ok
            }
            rate if rate < 8000 => {
                report.add_error(format!("sample_rate {} is too low - minimum 8000 Hz", rate));
            }
            rate if rate > 48000 => {
                report.add_warning(format!(
                    "sample_rate {} is very high - may increase processing time",
                    rate
                ));
            }
            rate => {
                report.add_warning(format!(
                    "non-standard sample_rate {} - common rates: 16000, 22050, 44100, 48000",
                    rate
                ));
            }
        }

        // Check cache directory if specified
        if let Some(cache_dir) = &config.pipeline.cache_dir {
            if !cache_dir.exists() {
                report.add_warning(format!(
                    "cache directory does not exist: {}",
                    cache_dir.display()
                ));
            } else if !cache_dir.is_dir() {
                report.add_error(format!(
                    "cache path exists but is not a directory: {}",
                    cache_dir.display()
                ));
            }
        }

        // Validate cache size
        let max_cache_size_mb = config.pipeline.max_cache_size_mb;
        if max_cache_size_mb == 0 {
            report.add_warning("cache disabled (max_cache_size_mb = 0)".to_string());
        } else if max_cache_size_mb > 10240 {
            report.add_warning(format!(
                "very large cache size ({} MB) may consume excessive memory",
                max_cache_size_mb
            ));
        }

        // Validate GPU usage consistency
        if config.pipeline.use_gpu && config.pipeline.device == "cpu" {
            report.add_warning(
                "use_gpu is true but device is set to 'cpu' - inconsistent configuration"
                    .to_string(),
            );
        }

        Ok(())
    }

    /// Configuration validation report
    #[derive(Debug, Clone)]
    pub struct ValidationReport {
        pub errors: Vec<String>,
        pub warnings: Vec<String>,
        pub info: Vec<String>,
    }

    impl ValidationReport {
        pub fn new() -> Self {
            Self {
                errors: Vec::new(),
                warnings: Vec::new(),
                info: Vec::new(),
            }
        }

        pub fn add_error(&mut self, error: String) {
            self.errors.push(error);
        }

        pub fn add_warning(&mut self, warning: String) {
            self.warnings.push(warning);
        }

        pub fn add_info(&mut self, info: String) {
            self.info.push(info);
        }

        pub fn is_valid(&self) -> bool {
            self.errors.is_empty()
        }

        pub fn has_warnings(&self) -> bool {
            !self.warnings.is_empty()
        }

        pub fn summary(&self) -> String {
            format!(
                "Validation complete: {} errors, {} warnings, {} info messages",
                self.errors.len(),
                self.warnings.len(),
                self.info.len()
            )
        }
    }

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

/// Configuration export formats
pub enum ConfigFormat {
    Toml,
    Json,
    Yaml,
}