voirs-cli 0.1.0-beta.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
//! Voice management command implementations.

use chrono::Utc;
use indicatif::{ProgressBar, ProgressStyle};
use sha2::{Digest, Sha256};
use std::io::{Read, Write};
use voirs_sdk::{config::AppConfig, error::Result, VoiceConfig, VoirsPipeline};

/// Run list voices command
pub async fn run_list_voices(
    language: Option<&str>,
    detailed: bool,
    config: &AppConfig,
) -> Result<()> {
    let pipeline = VoirsPipeline::builder().build().await?;
    let voices = pipeline.list_voices().await?;

    // Filter by language if specified
    let filtered_voices: Vec<_> = if let Some(lang) = language {
        voices
            .into_iter()
            .filter(|voice| voice.language.as_str().eq_ignore_ascii_case(lang))
            .collect()
    } else {
        voices
    };

    if detailed {
        for voice in &filtered_voices {
            println!("ID: {}", voice.id);
            println!("Name: {}", voice.name);
            println!("Language: {}", voice.language.as_str());
            println!("Quality: {:?}", voice.characteristics.quality);
            println!("---");
        }
    } else {
        for voice in &filtered_voices {
            println!(
                "{} - {} ({})",
                voice.id,
                voice.name,
                voice.language.as_str()
            );
        }
    }

    Ok(())
}

/// Run voice info command
pub async fn run_voice_info(voice_id: &str, config: &AppConfig) -> Result<()> {
    let pipeline = VoirsPipeline::builder().build().await?;
    let voices = pipeline.list_voices().await?;

    // Find the requested voice
    let voice = voices.iter().find(|v| v.id == voice_id).ok_or_else(|| {
        voirs_sdk::VoirsError::audio_error(format!("Voice '{}' not found", voice_id))
    })?;

    // Display voice information
    println!("Voice Information");
    println!("================");
    println!("ID: {}", voice.id);
    println!("Name: {}", voice.name);
    println!("Language: {}", voice.language.as_str());
    println!(
        "Description: {}",
        voice
            .metadata
            .get("description")
            .unwrap_or(&"No description available".to_string())
    );
    println!();

    println!("Characteristics:");
    println!(
        "  Gender: {}",
        voice
            .characteristics
            .gender
            .map(|g| format!("{:?}", g))
            .unwrap_or_else(|| "Not specified".to_string())
    );
    println!(
        "  Age: {}",
        voice
            .characteristics
            .age
            .map(|a| format!("{:?}", a))
            .unwrap_or_else(|| "Not specified".to_string())
    );
    println!("  Style: {:?}", voice.characteristics.style);
    println!(
        "  Emotion Support: {}",
        voice.characteristics.emotion_support
    );
    println!("  Quality: {:?}", voice.characteristics.quality);
    println!();

    println!("Model Configuration:");
    println!("  Acoustic Model: {}", voice.model_config.acoustic_model);
    println!("  Vocoder Model: {}", voice.model_config.vocoder_model);
    if let Some(ref g2p_model) = voice.model_config.g2p_model {
        println!("  G2P Model: {}", g2p_model);
    }
    println!("  Format: {:?}", voice.model_config.format);
    println!();

    println!("Device Requirements:");
    println!(
        "  Minimum Memory: {} MB",
        voice.model_config.device_requirements.min_memory_mb
    );
    println!(
        "  GPU Support: {}",
        voice.model_config.device_requirements.gpu_support
    );
    if !voice
        .model_config
        .device_requirements
        .compute_capabilities
        .is_empty()
    {
        println!(
            "  Compute Capabilities: {:?}",
            voice.model_config.device_requirements.compute_capabilities
        );
    }

    if !voice.metadata.is_empty() {
        println!();
        println!("Additional Metadata:");
        for (key, value) in &voice.metadata {
            println!("  {}: {}", key, value);
        }
    }

    // Check if voice is available locally
    let cache_dir = config.pipeline.effective_cache_dir();
    let voice_dir = cache_dir.join("voices").join(voice_id);
    let is_downloaded = voice_dir.exists();

    println!();
    if is_downloaded {
        println!("Status: Downloaded and available");
        println!("Location: {}", voice_dir.display());

        // Check if all required models are present
        let acoustic_path = voice_dir.join(&voice.model_config.acoustic_model);
        let vocoder_path = voice_dir.join(&voice.model_config.vocoder_model);
        let acoustic_exists = acoustic_path.exists();
        let vocoder_exists = vocoder_path.exists();

        if acoustic_exists && vocoder_exists {
            println!("Model files: Complete");
        } else {
            println!("Model files: Incomplete - re-download may be required");
            if !acoustic_exists {
                println!("  Missing: acoustic model");
            }
            if !vocoder_exists {
                println!("  Missing: vocoder model");
            }
        }
    } else {
        println!("Status: Available for download");
    }

    Ok(())
}

/// Run download voice command
pub async fn run_download_voice(voice_id: &str, force: bool, config: &AppConfig) -> Result<()> {
    println!("Downloading voice: {}", voice_id);

    let pipeline = VoirsPipeline::builder().build().await?;
    let voices = pipeline.list_voices().await?;

    // Find the requested voice
    let voice = voices.iter().find(|v| v.id == voice_id).ok_or_else(|| {
        voirs_sdk::VoirsError::audio_error(format!("Voice '{}' not found", voice_id))
    })?;

    // Check if already downloaded
    let cache_dir = config.pipeline.effective_cache_dir();
    let voice_dir = cache_dir.join("voices").join(voice_id);

    if voice_dir.exists() && !force {
        println!(
            "Voice '{}' is already downloaded. Use --force to re-download.",
            voice_id
        );
        return Ok(());
    }

    // Create voice directory
    std::fs::create_dir_all(&voice_dir).map_err(voirs_sdk::VoirsError::from)?;

    println!("Preparing to download voice models...");

    // List of models to download
    let mut models_to_download = vec![
        ("acoustic", &voice.model_config.acoustic_model),
        ("vocoder", &voice.model_config.vocoder_model),
    ];

    if let Some(ref g2p_model) = voice.model_config.g2p_model {
        models_to_download.push(("g2p", g2p_model));
    }

    println!("Models to download:");
    for (model_type, model_path) in &models_to_download {
        println!("  {}: {}", model_type, model_path);
    }

    // Download models from configured repositories
    let models_count = models_to_download.len();
    for (model_type, model_path) in models_to_download {
        let local_path = voice_dir.join(model_path);

        // Create parent directories if needed
        if let Some(parent) = local_path.parent() {
            std::fs::create_dir_all(parent).map_err(voirs_sdk::VoirsError::from)?;
        }

        println!("  Downloading {} model...", model_type);

        // Try downloading from each repository until one succeeds
        let mut download_success = false;
        for (repo_index, repository) in config
            .pipeline
            .model_loading
            .repositories
            .iter()
            .enumerate()
        {
            let download_url = format!("{}/voices/{}/{}", repository, voice_id, model_path);

            println!(
                "    Attempting download from repository {}: {}",
                repo_index + 1,
                repository
            );

            match download_model_file(&download_url, &local_path, config).await {
                Ok(_) => {
                    println!("    ✓ Downloaded successfully from {}", repository);
                    download_success = true;
                    break;
                }
                Err(e) => {
                    println!("    ✗ Failed to download from {}: {}", repository, e);
                    continue;
                }
            }
        }

        // If all repositories failed, create a placeholder file as fallback
        if !download_success {
            println!("    Creating placeholder file as fallback...");
            std::fs::write(
                &local_path,
                format!("Placeholder for {} model: {}", model_type, model_path),
            )
            .map_err(voirs_sdk::VoirsError::from)?;

            println!("    ⚠ Placeholder created: {}", local_path.display());
        }
    }

    // Save voice configuration
    let voice_config_path = voice_dir.join("voice.json");
    let voice_json = serde_json::to_string_pretty(voice).map_err(|e| {
        voirs_sdk::VoirsError::config_error(format!("Failed to serialize voice config: {}", e))
    })?;

    std::fs::write(&voice_config_path, voice_json).map_err(voirs_sdk::VoirsError::from)?;

    println!();
    println!("Voice '{}' downloaded successfully!", voice_id);
    println!("  Location: {}", voice_dir.display());
    println!("  Models: {} files", models_count);
    println!();
    println!("Download completed successfully.");
    if models_count > 0 {
        println!("Model repositories used for download:");
    } else {
        println!("Note: No models were available for download.");
        println!("Available repositories:");
    }
    for repo in &config.pipeline.model_loading.repositories {
        println!("  - {}", repo);
    }

    if models_count > 0 {
        println!();
        println!("Configuration:");
        println!(
            "  Timeout: {} seconds",
            config.pipeline.model_loading.download_timeout_secs
        );
        println!(
            "  Retries: {}",
            config.pipeline.model_loading.download_retries
        );
        println!(
            "  Verify checksums: {}",
            config.pipeline.model_loading.verify_checksums
        );
    }

    Ok(())
}

/// Download a model file from a URL with progress tracking and verification
async fn download_model_file(
    url: &str,
    local_path: &std::path::Path,
    config: &AppConfig,
) -> Result<()> {
    use std::time::Duration;

    // Create HTTP client with timeout
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(
            config.pipeline.model_loading.download_timeout_secs,
        ))
        .build()
        .map_err(|e| {
            voirs_sdk::VoirsError::config_error(format!("Failed to create HTTP client: {}", e))
        })?;

    // Attempt download with retries
    let mut last_error = None;
    for attempt in 1..=config.pipeline.model_loading.download_retries {
        match attempt_download(&client, url, local_path, attempt).await {
            Ok(_) => {
                // Verify file if checksums are enabled
                if config.pipeline.model_loading.verify_checksums {
                    verify_downloaded_file(local_path, config)?;
                }
                return Ok(());
            }
            Err(e) => {
                last_error = Some(e);
                if attempt < config.pipeline.model_loading.download_retries {
                    println!(
                        "      Retrying... (attempt {} of {})",
                        attempt + 1,
                        config.pipeline.model_loading.download_retries
                    );
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
            }
        }
    }

    Err(last_error.unwrap_or_else(|| {
        voirs_sdk::VoirsError::config_error("Download failed after all retries")
    }))
}

/// Attempt a single download
async fn attempt_download(
    client: &reqwest::Client,
    url: &str,
    local_path: &std::path::Path,
    attempt: u32,
) -> Result<()> {
    let response =
        client.get(url).send().await.map_err(|e| {
            voirs_sdk::VoirsError::config_error(format!("HTTP request failed: {}", e))
        })?;

    if !response.status().is_success() {
        return Err(voirs_sdk::VoirsError::config_error(format!(
            "HTTP error {}: {}",
            response.status(),
            response
                .status()
                .canonical_reason()
                .unwrap_or("Unknown error")
        )));
    }

    // Get content length for progress tracking
    let total_size = response.content_length().unwrap_or(0);

    // Create progress bar
    let pb = if total_size > 0 {
        let pb = ProgressBar::new(total_size);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("      [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                .expect("progress template is valid")
                .progress_chars("#>-"),
        );
        Some(pb)
    } else {
        println!("      Downloading (size unknown)...");
        None
    };

    // Download with progress tracking
    let mut file =
        std::fs::File::create(local_path).map_err(|e| voirs_sdk::VoirsError::IoError {
            path: local_path.to_path_buf(),
            operation: voirs_sdk::error::IoOperation::Write,
            source: e,
        })?;

    let mut downloaded = 0u64;
    let mut stream = response.bytes_stream();

    use futures_util::StreamExt;
    while let Some(chunk) = stream.next().await {
        let chunk = chunk.map_err(|e| {
            voirs_sdk::VoirsError::config_error(format!("Download stream error: {}", e))
        })?;

        file.write_all(&chunk)
            .map_err(|e| voirs_sdk::VoirsError::IoError {
                path: local_path.to_path_buf(),
                operation: voirs_sdk::error::IoOperation::Write,
                source: e,
            })?;

        downloaded += chunk.len() as u64;

        // Update progress bar
        if let Some(ref pb) = pb {
            pb.set_position(downloaded);
        }
    }

    file.flush().map_err(|e| voirs_sdk::VoirsError::IoError {
        path: local_path.to_path_buf(),
        operation: voirs_sdk::error::IoOperation::Write,
        source: e,
    })?;

    // Finish progress bar
    if let Some(pb) = pb {
        pb.finish_and_clear();
        println!(
            "      ✓ Downloaded {:.2} MB",
            downloaded as f64 / 1024.0 / 1024.0
        );
    } else {
        println!(
            "      ✓ Downloaded {:.2} MB",
            downloaded as f64 / 1024.0 / 1024.0
        );
    }

    Ok(())
}

/// Verify downloaded file integrity
fn verify_downloaded_file(local_path: &std::path::Path, config: &AppConfig) -> Result<()> {
    // Basic file existence and size check
    let metadata = std::fs::metadata(local_path).map_err(|e| voirs_sdk::VoirsError::IoError {
        path: local_path.to_path_buf(),
        operation: voirs_sdk::error::IoOperation::Read,
        source: e,
    })?;

    if metadata.len() == 0 {
        return Err(voirs_sdk::VoirsError::config_error(
            "Downloaded file is empty",
        ));
    }

    // Check for minimum file size (models should be at least 1KB)
    if metadata.len() < 1024 {
        return Err(voirs_sdk::VoirsError::config_error(
            "Downloaded file is too small to be a valid model",
        ));
    }

    // Enhanced checksum verification implementation
    if config.pipeline.model_loading.verify_checksums {
        if let Err(e) = verify_file_checksum(local_path) {
            println!("      ⚠ Checksum verification failed: {}", e);
            // For now, warn but don't fail - future enhancement could make this configurable
        } else {
            println!("      ✓ Checksum verification passed");
        }
    }

    println!(
        "      ✓ File verification passed ({} bytes)",
        metadata.len()
    );
    Ok(())
}

/// Verify file checksum using SHA256
fn verify_file_checksum(file_path: &std::path::Path) -> Result<()> {
    // Check for accompanying checksum file (.sha256)
    let checksum_path = file_path.with_extension(format!(
        "{}.sha256",
        file_path.extension().and_then(|s| s.to_str()).unwrap_or("")
    ));

    if !checksum_path.exists() {
        // Also try looking for a .sha256 file with same base name
        let alt_checksum_path = file_path.with_extension("sha256");
        if !alt_checksum_path.exists() {
            return Err(voirs_sdk::VoirsError::config_error(
                "No checksum file found for verification",
            ));
        }
    }

    let expected_checksum = std::fs::read_to_string(&checksum_path)
        .or_else(|_| std::fs::read_to_string(file_path.with_extension("sha256")))
        .map_err(|e| {
            voirs_sdk::VoirsError::config_error(format!("Failed to read checksum file: {}", e))
        })?
        .trim()
        .to_lowercase();

    // Validate checksum format (should be 64 hex characters for SHA256)
    if expected_checksum.len() != 64 || !expected_checksum.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(voirs_sdk::VoirsError::config_error(
            "Invalid checksum format - expected 64 hex characters",
        ));
    }

    // Calculate SHA256 of the downloaded file
    let calculated_checksum = calculate_file_sha256(file_path)?;

    // Compare checksums
    if calculated_checksum != expected_checksum {
        return Err(voirs_sdk::VoirsError::config_error(format!(
            "Checksum mismatch - expected: {}, calculated: {}",
            expected_checksum, calculated_checksum
        )));
    }

    Ok(())
}

/// Calculate SHA256 hash of a file
fn calculate_file_sha256(file_path: &std::path::Path) -> Result<String> {
    let mut file = std::fs::File::open(file_path).map_err(|e| voirs_sdk::VoirsError::IoError {
        path: file_path.to_path_buf(),
        operation: voirs_sdk::error::IoOperation::Read,
        source: e,
    })?;

    let mut hasher = Sha256::new();
    let mut buffer = [0; 8192]; // 8KB buffer for efficient reading

    loop {
        let bytes_read = file
            .read(&mut buffer)
            .map_err(|e| voirs_sdk::VoirsError::IoError {
                path: file_path.to_path_buf(),
                operation: voirs_sdk::error::IoOperation::Read,
                source: e,
            })?;

        if bytes_read == 0 {
            break;
        }

        hasher.update(&buffer[..bytes_read]);
    }

    let hash = hasher.finalize();
    Ok(format!("{:x}", hash))
}

/// Compare multiple voices side by side
pub async fn run_compare_voices(voice_ids: Vec<String>, config: &AppConfig) -> Result<()> {
    let pipeline = VoirsPipeline::builder().build().await?;
    let voices = pipeline.list_voices().await?;

    let mut found_voices = Vec::new();
    let mut missing_voices = Vec::new();

    // Find all requested voices
    for voice_id in &voice_ids {
        if let Some(voice) = voices.iter().find(|v| v.id == *voice_id) {
            found_voices.push(voice);
        } else {
            missing_voices.push(voice_id.clone());
        }
    }

    // Report missing voices
    if !missing_voices.is_empty() {
        println!("⚠ Warning: The following voices were not found:");
        for voice_id in &missing_voices {
            println!("  - {}", voice_id);
        }
        println!();
    }

    if found_voices.is_empty() {
        println!("No voices found for comparison.");
        return Ok(());
    }

    println!("Voice Comparison");
    println!("================");
    println!("Comparing {} voice(s)\n", found_voices.len());

    // Display simple comparison table
    display_simple_voice_comparison(&found_voices, config)?;

    // Display basic recommendations
    println!("\nRecommendations:");
    println!("================");
    display_simple_recommendations(&found_voices);

    Ok(())
}

/// Display a simple comparison of voices
fn display_simple_voice_comparison(voices: &[&VoiceConfig], config: &AppConfig) -> Result<()> {
    let cache_dir = config.pipeline.effective_cache_dir();

    for (i, voice) in voices.iter().enumerate() {
        println!("Voice {} - {}", i + 1, voice.name);
        println!("  ID: {}", voice.id);
        println!("  Language: {}", voice.language.as_str());
        println!("  Quality: {:?}", voice.characteristics.quality);

        if let Some(gender) = voice.characteristics.gender {
            println!("  Gender: {:?}", gender);
        }

        if let Some(age) = voice.characteristics.age {
            println!("  Age: {:?}", age);
        }

        println!("  Style: {:?}", voice.characteristics.style);
        println!(
            "  Emotion Support: {}",
            voice.characteristics.emotion_support
        );

        // Check download status
        let voice_dir = cache_dir.join("voices").join(&voice.id);
        let status = if voice_dir.exists() {
            "✓ Downloaded"
        } else {
            "✗ Not downloaded"
        };
        println!("  Status: {}", status);

        // Get estimated size if downloaded
        if voice_dir.exists() {
            let size = estimate_voice_size(&voice_dir);
            println!("  Size: {}", size);
        }

        println!();
    }

    Ok(())
}

/// Display simple recommendations based on voice comparison
fn display_simple_recommendations(voices: &[&VoiceConfig]) {
    if voices.len() < 2 {
        println!("Need at least 2 voices for recommendations.");
        return;
    }

    // Language analysis
    println!("🌐 Language Analysis:");
    let mut language_counts = std::collections::HashMap::new();
    for voice in voices {
        let lang = voice.language.as_str();
        *language_counts.entry(lang).or_insert(0) += 1;
    }

    for (language, count) in language_counts {
        println!("  - {}: {} voice(s)", language, count);
    }

    // Quality analysis
    println!("\n🎯 Quality Analysis:");
    let mut quality_counts = std::collections::HashMap::new();
    for voice in voices {
        let quality_str = format!("{:?}", voice.characteristics.quality);
        *quality_counts.entry(quality_str).or_insert(0) += 1;
    }

    for (quality, count) in quality_counts {
        println!("  - {}: {} voice(s)", quality, count);
    }

    // Feature analysis
    println!("\n🌟 Feature Analysis:");
    let emotion_support_count = voices
        .iter()
        .filter(|v| v.characteristics.emotion_support)
        .count();
    let gender_specified_count = voices
        .iter()
        .filter(|v| v.characteristics.gender.is_some())
        .count();
    let age_specified_count = voices
        .iter()
        .filter(|v| v.characteristics.age.is_some())
        .count();

    println!("  - Emotion Support: {} voice(s)", emotion_support_count);
    println!("  - Gender Specified: {} voice(s)", gender_specified_count);
    println!("  - Age Specified: {} voice(s)", age_specified_count);

    // General recommendations
    println!("\n💡 General Recommendations:");
    if voices.len() > 1 {
        println!("  - Test multiple voices with sample content to find the best fit");
        println!("  - Use high-quality voices for production content");
        println!("  - Choose voices with emotion support for dynamic content");
        println!("  - Consider language consistency for multi-voice projects");
    }
}

/// Truncate string to specified length with ellipsis
fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

/// Estimate the size of a voice directory
fn estimate_voice_size(voice_dir: &std::path::Path) -> String {
    let mut total_size = 0u64;

    if let Ok(entries) = std::fs::read_dir(voice_dir) {
        for entry in entries.flatten() {
            if let Ok(metadata) = entry.metadata() {
                total_size += metadata.len();
            }
        }
    }

    if total_size == 0 {
        "Unknown".to_string()
    } else if total_size < 1024 * 1024 {
        format!("{:.1} KB", total_size as f64 / 1024.0)
    } else if total_size < 1024 * 1024 * 1024 {
        format!("{:.1} MB", total_size as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1} GB", total_size as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// Run voice preview command
///
/// Generates a short audio sample with the specified voice to let users
/// quickly hear what it sounds like before using it for synthesis.
pub async fn run_preview_voice(
    voice_id: &str,
    text: Option<&str>,
    output: Option<&std::path::PathBuf>,
    no_play: bool,
    config: &AppConfig,
    global: &crate::GlobalOptions,
) -> Result<()> {
    use crate::commands::synthesize::SynthesizeArgs;

    // Default preview text if none provided
    let preview_text = text.unwrap_or("This is a preview of this voice.");

    println!("🎤 Voice Preview");
    println!("Voice ID: {}", voice_id);
    println!("Preview text: \"{}\"", preview_text);
    println!();

    // Verify voice exists
    let pipeline = VoirsPipeline::builder().build().await?;
    let voices = pipeline.list_voices().await?;
    let voice = voices.iter().find(|v| v.id == voice_id).ok_or_else(|| {
        voirs_sdk::VoirsError::audio_error(format!(
            "Voice '{}' not found. Use 'voirs list-voices' to see available voices.",
            voice_id
        ))
    })?;

    // Show voice info
    println!("Voice: {}", voice.name);
    println!("Language: {}", voice.language.as_str());
    if let Some(gender) = voice.characteristics.gender {
        println!("Gender: {:?}", gender);
    }
    println!();

    // Determine output path
    let temp_dir = std::env::temp_dir();
    let output_path = if let Some(out) = output {
        out.clone()
    } else {
        temp_dir.join(format!(
            "voirs_preview_{}_{}.wav",
            voice_id,
            chrono::Utc::now().timestamp()
        ))
    };

    // Use the existing synthesize implementation
    let synthesize_args = SynthesizeArgs {
        text: preview_text,
        output: Some(&output_path),
        rate: 1.0,
        pitch: 0.0,
        volume: 0.0,
        quality: voirs_sdk::QualityLevel::High,
        enhance: false,
        play: !no_play && output.is_none(), // Play if not explicitly disabled and no custom output
        auto_detect: false,                 // Don't auto-detect for previews
    };

    // Temporarily override voice in config
    let mut config_override = config.clone();
    config_override.cli.default_voice = Some(voice_id.to_string());

    println!("🎵 Synthesizing preview...");
    crate::commands::synthesize::run_synthesize(synthesize_args, &config_override, global).await?;

    // If user specified an output file, let them know where it is
    if output.is_some() {
        println!("✅ Preview saved to: {}", output_path.display());
    } else if no_play {
        println!("✅ Preview saved to: {}", output_path.display());
        println!("   (temporary file - will be cleaned up by system)");
    }

    Ok(())
}