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
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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
//! # VoiRS CLI
//!
//! Command-line interface for VoiRS speech synthesis framework.
//! Provides easy-to-use commands for synthesis, voice management, and more.

// Allow pedantic lints that are acceptable for audio/DSP processing code
#![allow(clippy::cast_precision_loss)] // Acceptable for audio sample conversions
#![allow(clippy::cast_possible_truncation)] // Controlled truncation in audio processing
#![allow(clippy::cast_sign_loss)] // Intentional in index calculations
#![allow(clippy::missing_errors_doc)] // Many internal functions with self-documenting error types
#![allow(clippy::missing_panics_doc)] // Panics are documented where relevant
#![allow(clippy::unused_self)] // Some trait implementations require &self for consistency
#![allow(clippy::must_use_candidate)] // Not all return values need must_use annotation
#![allow(clippy::doc_markdown)] // Technical terms don't all need backticks
#![allow(clippy::unnecessary_wraps)] // Result wrappers maintained for API consistency
#![allow(clippy::float_cmp)] // Exact float comparisons are intentional in some contexts
#![allow(clippy::match_same_arms)] // Pattern matching clarity sometimes requires duplication
#![allow(clippy::module_name_repetitions)] // Type names often repeat module names
#![allow(clippy::struct_excessive_bools)] // Config structs naturally have many boolean flags
#![allow(clippy::too_many_lines)] // Some functions are inherently complex
#![allow(clippy::needless_pass_by_value)] // Some functions designed for ownership transfer
#![allow(clippy::similar_names)] // Many similar variable names in algorithms
#![allow(clippy::unused_async)] // Public API functions may need async for consistency
#![allow(clippy::needless_range_loop)] // Range loops sometimes clearer than iterators
#![allow(clippy::uninlined_format_args)] // Explicit argument names can improve clarity
#![allow(clippy::manual_clamp)] // Manual clamping sometimes clearer
#![allow(clippy::return_self_not_must_use)] // Not all builder methods need must_use
#![allow(clippy::cast_possible_wrap)] // Controlled wrapping in processing code
#![allow(clippy::cast_lossless)] // Explicit casts preferred for clarity
#![allow(clippy::wildcard_imports)] // Prelude imports are convenient and standard
#![allow(clippy::format_push_string)] // Sometimes more readable than alternative
#![allow(clippy::redundant_closure_for_method_calls)] // Closures sometimes needed for type inference
#![allow(clippy::too_many_arguments)] // Some functions naturally need many parameters
#![allow(clippy::field_reassign_with_default)] // Sometimes clearer than builder pattern
#![allow(clippy::trivially_copy_pass_by_ref)] // API consistency more important
#![allow(clippy::await_holding_lock)] // Controlled lock holding in async contexts

use crate::cli_types::{CliAudioFormat, CliQualityLevel};
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use voirs_sdk::config::{AppConfig, PipelineConfig};
use voirs_sdk::{AudioFormat, QualityLevel, Result, VoirsPipeline};

pub mod audio;
pub mod cli_types;
pub mod cloud;
pub mod commands;
pub mod completion;
pub mod config;
pub mod error;
pub mod help;
pub mod lsp;
pub mod model_types;
pub mod output;
pub mod packaging;
pub mod performance;
pub mod platform;
pub mod plugins;
pub mod progress;
pub mod ssml;
pub mod synthesis;
pub mod telemetry;
pub mod validation;
pub mod workflow;

// Re-export important types are already imported above

/// VoiRS CLI application
#[derive(Parser)]
#[command(name = "voirs")]
#[command(about = "A pure Rust text-to-speech synthesis framework")]
#[command(version = env!("CARGO_PKG_VERSION"))]
pub struct CliApp {
    /// Global options
    #[command(flatten)]
    pub global: GlobalOptions,

    /// Subcommands
    #[command(subcommand)]
    pub command: Commands,
}

/// Global CLI options
#[derive(Parser)]
pub struct GlobalOptions {
    /// Configuration file path
    #[arg(short, long)]
    pub config: Option<PathBuf>,

    /// Verbose output
    #[arg(short, long, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Quiet mode (suppress most output)
    #[arg(short, long)]
    pub quiet: bool,

    /// Output format (overrides config)
    #[arg(long)]
    pub format: Option<CliAudioFormat>,

    /// Voice to use (overrides config)
    #[arg(long)]
    pub voice: Option<String>,

    /// Enable GPU acceleration
    #[arg(long)]
    pub gpu: bool,

    /// Number of threads to use
    #[arg(long)]
    pub threads: Option<usize>,
}

/// Cloud-specific commands
#[derive(Subcommand)]
pub enum CloudCommands {
    /// Synchronize files with cloud storage
    Sync {
        /// Force full synchronization
        #[arg(long)]
        force: bool,

        /// Specific directory to sync
        #[arg(long)]
        directory: Option<PathBuf>,

        /// Dry run (show what would be synced)
        #[arg(long)]
        dry_run: bool,
    },

    /// Add file or directory to cloud sync
    AddToSync {
        /// Local path to sync
        local_path: PathBuf,

        /// Remote path in cloud storage
        remote_path: String,

        /// Sync direction (upload, download, bidirectional)
        #[arg(long, default_value = "bidirectional")]
        direction: String,
    },

    /// Show cloud storage statistics
    StorageStats,

    /// Clean up old cached files
    CleanupCache {
        /// Maximum age in days
        #[arg(long, default_value = "30")]
        max_age_days: u32,

        /// Dry run (show what would be cleaned)
        #[arg(long)]
        dry_run: bool,
    },

    /// Translate text using cloud services
    Translate {
        /// Text to translate
        text: String,

        /// Source language code
        #[arg(long)]
        from: String,

        /// Target language code  
        #[arg(long)]
        to: String,

        /// Translation quality (fast, balanced, high-quality)
        #[arg(long, default_value = "balanced")]
        quality: String,
    },

    /// Analyze content using cloud AI
    AnalyzeContent {
        /// Text content to analyze
        text: String,

        /// Analysis types (comma-separated: sentiment, entities, keywords, etc.)
        #[arg(long, default_value = "sentiment,entities")]
        analysis_types: String,

        /// Language code (optional)
        #[arg(long)]
        language: Option<String>,
    },

    /// Assess audio quality using cloud services
    AssessQuality {
        /// Audio file to assess
        audio_file: PathBuf,

        /// Text that was synthesized
        text: String,

        /// Assessment metrics (comma-separated)
        #[arg(long, default_value = "naturalness,intelligibility,overall")]
        metrics: String,
    },

    /// Check cloud service health
    HealthCheck,

    /// Configure cloud integration
    Configure {
        /// Show current configuration
        #[arg(long)]
        show: bool,

        /// Set cloud storage provider
        #[arg(long)]
        storage_provider: Option<String>,

        /// Set API base URL
        #[arg(long)]
        api_url: Option<String>,

        /// Enable/disable specific services
        #[arg(long)]
        enable_service: Option<String>,

        /// Initialize cloud configuration
        #[arg(long)]
        init: bool,
    },
}

/// Dataset-specific commands
#[derive(Subcommand)]
pub enum DatasetCommands {
    /// Validate dataset structure and quality
    Validate {
        /// Dataset directory path
        path: PathBuf,

        /// Dataset type (auto-detect if not specified)
        #[arg(long)]
        dataset_type: Option<String>,

        /// Perform detailed quality analysis
        #[arg(long)]
        detailed: bool,
    },

    /// Convert between dataset formats
    Convert {
        /// Input dataset path
        input: PathBuf,

        /// Output dataset path
        output: PathBuf,

        /// Source dataset format
        #[arg(long)]
        from: String,

        /// Target dataset format
        #[arg(long)]
        to: String,
    },

    /// Split dataset into train/validation/test sets
    Split {
        /// Dataset directory path
        path: PathBuf,

        /// Training set ratio (0.0-1.0)
        #[arg(long, default_value = "0.8")]
        train_ratio: f32,

        /// Validation set ratio (0.0-1.0)
        #[arg(long, default_value = "0.1")]
        val_ratio: f32,

        /// Test set ratio (auto-calculated if not specified)
        #[arg(long)]
        test_ratio: Option<f32>,

        /// Seed for reproducible splits
        #[arg(long)]
        seed: Option<u64>,
    },

    /// Preprocess dataset for training
    Preprocess {
        /// Input dataset path
        input: PathBuf,

        /// Output directory for preprocessed data
        output: PathBuf,

        /// Target sample rate
        #[arg(long, default_value = "22050")]
        sample_rate: u32,

        /// Normalize audio levels
        #[arg(long)]
        normalize: bool,

        /// Apply audio filters
        #[arg(long)]
        filter: bool,
    },

    /// Generate dataset statistics and analysis
    Analyze {
        /// Dataset directory path
        path: PathBuf,

        /// Output file for analysis report
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Include detailed per-file statistics
        #[arg(long)]
        detailed: bool,
    },
}

/// CLI commands
#[derive(Subcommand)]
pub enum Commands {
    /// Synthesize text to speech
    Synthesize {
        /// Text to synthesize
        text: String,

        /// Output file path (use '-' for stdout, omit for auto-generated filename)
        output: Option<PathBuf>,

        /// Speaking rate (0.5 - 2.0)
        #[arg(long, default_value = "1.0")]
        rate: f32,

        /// Pitch shift in semitones (-12.0 - 12.0)
        #[arg(long, default_value = "0.0")]
        pitch: f32,

        /// Volume gain in dB (-20.0 - 20.0)
        #[arg(long, default_value = "0.0")]
        volume: f32,

        /// Quality level
        #[arg(long, default_value = "high")]
        quality: CliQualityLevel,

        /// Enable audio enhancement
        #[arg(long)]
        enhance: bool,

        /// Play audio after synthesis
        #[arg(short, long)]
        play: bool,

        /// Auto-detect input format (SSML, Markdown, JSON, or plain text)
        #[arg(long)]
        auto_detect: bool,
    },

    /// Synthesize from file
    SynthesizeFile {
        /// Input text file
        input: PathBuf,

        /// Output directory
        #[arg(short, long)]
        output_dir: Option<PathBuf>,

        /// Speaking rate
        #[arg(long, default_value = "1.0")]
        rate: f32,

        /// Quality level
        #[arg(long, default_value = "high")]
        quality: CliQualityLevel,
    },

    /// List available voices
    ListVoices {
        /// Filter by language
        #[arg(long)]
        language: Option<String>,

        /// Show detailed information
        #[arg(long)]
        detailed: bool,
    },

    /// Get voice information
    VoiceInfo {
        /// Voice ID
        voice_id: String,
    },

    /// Download voice
    DownloadVoice {
        /// Voice ID to download
        voice_id: String,

        /// Force download even if voice exists
        #[arg(long)]
        force: bool,
    },

    /// Preview a voice with a sample text
    PreviewVoice {
        /// Voice ID to preview
        voice_id: String,

        /// Custom preview text (default: "This is a preview of this voice.")
        #[arg(long)]
        text: Option<String>,

        /// Save preview to file instead of just playing
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Skip audio playback (only save to file)
        #[arg(long)]
        no_play: bool,
    },

    /// Compare multiple voices side by side
    CompareVoices {
        /// Voice IDs to compare
        voice_ids: Vec<String>,
    },

    /// Test synthesis pipeline
    Test {
        /// Test text
        #[arg(default_value = "Hello, this is a test of VoiRS speech synthesis.")]
        text: String,

        /// Play audio instead of saving
        #[arg(long)]
        play: bool,
    },

    /// Run cross-language consistency tests for FFI bindings
    CrossLangTest {
        /// Output format for test report (json, yaml)
        #[arg(long, default_value = "json")]
        format: String,

        /// Save detailed test report to file
        #[arg(long)]
        save_report: bool,
    },

    /// Test API endpoints for VoiRS server
    TestApi {
        /// Server URL (e.g., http://localhost:8080)
        server_url: String,

        /// API key for authentication
        #[arg(long)]
        api_key: Option<String>,

        /// Number of concurrent requests for load testing
        #[arg(long)]
        concurrent: Option<usize>,

        /// Path to save test report (JSON or Markdown)
        #[arg(long)]
        report: Option<String>,

        /// Enable verbose output
        #[arg(long)]
        verbose: bool,
    },

    /// Show configuration
    Config {
        /// Show configuration and exit
        #[arg(long)]
        show: bool,

        /// Initialize default configuration
        #[arg(long)]
        init: bool,

        /// Configuration file path for init
        #[arg(long)]
        path: Option<PathBuf>,
    },

    /// List available models
    ListModels {
        /// Filter by backend
        #[arg(long)]
        backend: Option<String>,

        /// Show detailed information
        #[arg(long)]
        detailed: bool,
    },

    /// Download a model
    DownloadModel {
        /// Model ID to download
        model_id: String,

        /// Force download even if model exists
        #[arg(long)]
        force: bool,
    },

    /// Benchmark models
    BenchmarkModels {
        /// Model IDs to benchmark
        model_ids: Vec<String>,

        /// Number of iterations
        #[arg(short, long, default_value = "3")]
        iterations: u32,

        /// Include accuracy testing against CMU test set (>95% phoneme accuracy target)
        #[arg(long)]
        accuracy: bool,
    },

    /// Optimize model for current hardware
    OptimizeModel {
        /// Model ID to optimize
        model_id: String,

        /// Output path for optimized model
        #[arg(short, long)]
        output: Option<String>,

        /// Optimization strategy (speed, quality, memory, balanced)
        #[arg(long, default_value = "balanced")]
        strategy: String,
    },

    /// Batch process multiple texts
    Batch {
        /// Input file or directory
        input: PathBuf,

        /// Output directory
        #[arg(short, long)]
        output_dir: Option<PathBuf>,

        /// Number of parallel workers
        #[arg(short, long)]
        workers: Option<usize>,

        /// Speaking rate
        #[arg(long, default_value = "1.0")]
        rate: f32,

        /// Pitch shift in semitones
        #[arg(long, default_value = "0.0")]
        pitch: f32,

        /// Volume gain in dB
        #[arg(long, default_value = "0.0")]
        volume: f32,

        /// Quality level
        #[arg(long, default_value = "high")]
        quality: CliQualityLevel,

        /// Enable resume functionality
        #[arg(long)]
        resume: bool,
    },

    /// Server mode (future feature)
    Server {
        /// Port to bind to
        #[arg(short, long, default_value = "8080")]
        port: u16,

        /// Host to bind to
        #[arg(long, default_value = "127.0.0.1")]
        host: String,
    },

    /// Interactive mode for real-time synthesis
    Interactive {
        /// Initial voice to use
        #[arg(short, long)]
        voice: Option<String>,

        /// Disable audio playback (synthesis only)
        #[arg(long)]
        no_audio: bool,

        /// Enable debug output
        #[arg(long)]
        debug: bool,

        /// Load session from file
        #[arg(long)]
        load_session: Option<PathBuf>,

        /// Auto-save session changes
        #[arg(long)]
        auto_save: bool,
    },

    /// Show detailed help and guides
    Guide {
        /// Command to get help for
        command: Option<String>,

        /// Show getting started guide
        #[arg(long)]
        getting_started: bool,

        /// Show examples for all commands
        #[arg(long)]
        examples: bool,
    },

    /// Generate shell completion scripts
    GenerateCompletion {
        /// Shell to generate completion for
        #[arg(value_enum)]
        shell: clap_complete::Shell,

        /// Output file (default: stdout)
        #[arg(short, long)]
        output: Option<std::path::PathBuf>,

        /// Show installation instructions
        #[arg(long)]
        install_help: bool,

        /// Generate installation script
        #[arg(long)]
        install_script: bool,

        /// Show completion status for all shells
        #[arg(long)]
        status: bool,
    },

    /// Dataset management and validation commands
    Dataset {
        /// Dataset subcommand to execute
        #[command(subcommand)]
        command: DatasetCommands,
    },

    /// Real-time monitoring dashboard
    Dashboard {
        /// Update interval in milliseconds
        #[arg(short, long, default_value = "500")]
        interval: u64,
    },

    /// Cloud integration commands
    Cloud {
        /// Cloud subcommand to execute
        #[command(subcommand)]
        command: CloudCommands,
    },

    /// Telemetry management commands
    Telemetry {
        /// Telemetry subcommand to execute
        #[command(subcommand)]
        command: commands::telemetry::TelemetryCommands,
    },

    /// Start Language Server Protocol (LSP) server for editor integrations
    Lsp {
        /// Enable verbose logging
        #[arg(long)]
        verbose: bool,
    },

    /// Kokoro multilingual TTS commands (requires onnx feature)
    #[cfg(feature = "onnx")]
    Kokoro {
        /// Kokoro subcommand to execute
        #[command(subcommand)]
        command: commands::kokoro::KokoroCommands,
    },

    /// ONNX model tools (inspect, profile, graph export, info)
    #[cfg(feature = "onnx")]
    Onnx {
        /// ONNX tool subcommand to execute
        #[command(subcommand)]
        command: commands::onnx_tools::OnnxCommand,
    },

    /// Accuracy benchmarking commands
    Accuracy {
        /// Accuracy command configuration
        #[command(flatten)]
        command: commands::accuracy::AccuracyCommand,
    },

    /// Performance targets testing and monitoring
    Performance {
        /// Performance command configuration
        #[command(flatten)]
        command: commands::performance::PerformanceCommand,
    },

    /// Emotion control commands
    #[cfg(feature = "emotion")]
    Emotion {
        /// Emotion subcommand to execute
        #[command(subcommand)]
        command: commands::emotion::EmotionCommand,
    },

    /// Voice cloning commands
    #[cfg(feature = "cloning")]
    Clone {
        /// Cloning subcommand to execute
        #[command(subcommand)]
        command: commands::cloning::CloningCommand,
    },

    /// Voice conversion commands
    #[cfg(feature = "conversion")]
    Convert {
        /// Conversion subcommand to execute
        #[command(subcommand)]
        command: commands::conversion::ConversionCommand,
    },

    /// Singing voice synthesis commands
    #[cfg(feature = "singing")]
    Sing {
        /// Singing subcommand to execute
        #[command(subcommand)]
        command: commands::singing::SingingCommand,
    },

    /// 3D spatial audio commands
    #[cfg(feature = "spatial")]
    Spatial {
        /// Spatial subcommand to execute
        #[command(subcommand)]
        command: commands::spatial::SpatialCommand,
    },

    /// Feature detection and capability reporting
    Capabilities {
        /// Capabilities subcommand to execute
        #[command(subcommand)]
        command: commands::capabilities::CapabilitiesCommand,
    },

    /// Checkpoint management commands
    Checkpoint {
        /// Checkpoint subcommand to execute
        #[command(subcommand)]
        command: commands::checkpoint::CheckpointCommands,
    },

    /// Advanced monitoring and debugging commands
    Monitor {
        /// Monitoring subcommand to execute
        #[command(subcommand)]
        command: commands::monitoring::MonitoringCommand,
    },

    /// Train models (vocoder, acoustic, g2p)
    Train {
        /// Training subcommand to execute
        #[command(subcommand)]
        command: commands::train::TrainCommands,
    },

    /// Convert model formats (ONNX, PyTorch → SafeTensors)
    ConvertModel {
        /// Input model path
        input: PathBuf,

        /// Output path (SafeTensors format)
        #[arg(short, long)]
        output: PathBuf,

        /// Source format (auto-detect if not specified)
        #[arg(long)]
        from: Option<String>,

        /// Model type (vocoder, acoustic, g2p)
        #[arg(long)]
        model_type: String,

        /// Verify conversion by running test inference
        #[arg(long)]
        verify: bool,
    },

    /// Run vocoder inference (mel → audio)
    VocoderInfer {
        /// Path to vocoder checkpoint (SafeTensors)
        checkpoint: PathBuf,

        /// Path to mel spectrogram file (optional, generates dummy if omitted)
        #[arg(long)]
        mel: Option<PathBuf>,

        /// Output audio file path
        #[arg(short, long, default_value = "vocoder_output.wav")]
        output: PathBuf,

        /// Number of diffusion sampling steps
        #[arg(long, default_value = "50")]
        steps: usize,

        /// Quality preset (fast, balanced, high)
        #[arg(long)]
        quality: Option<String>,

        /// Batch processing: input directory
        #[arg(long)]
        batch_input: Option<PathBuf>,

        /// Batch processing: output directory
        #[arg(long)]
        batch_output: Option<PathBuf>,

        /// Show performance metrics
        #[arg(long)]
        metrics: bool,
    },

    /// Stream real-time text-to-speech synthesis
    Stream {
        /// Initial text to synthesize
        text: Option<String>,

        /// Target latency in milliseconds
        #[arg(long, default_value = "100")]
        latency: u64,

        /// Chunk size in frames
        #[arg(long, default_value = "512")]
        chunk_size: usize,

        /// Buffer size in chunks
        #[arg(long, default_value = "4")]
        buffer_chunks: usize,

        /// Enable audio output
        #[arg(long)]
        play: bool,
    },

    /// Inspect and analyze model files
    ModelInspect {
        /// Model file path
        model: PathBuf,

        /// Show detailed layer information
        #[arg(long)]
        detailed: bool,

        /// Export architecture to file
        #[arg(long)]
        export: Option<PathBuf>,

        /// Verify model integrity
        #[arg(long)]
        verify: bool,
    },

    /// Export voice profile or preset
    Export {
        /// Export type (voice-profile, emotion-preset, config)
        #[arg(long)]
        export_type: String,

        /// Source identifier (voice ID, preset name, etc.)
        source: String,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Include model weights
        #[arg(long)]
        include_weights: bool,
    },

    /// Import voice profile or preset
    Import {
        /// Import file path
        input: PathBuf,

        /// Installation name/identifier
        #[arg(long)]
        name: Option<String>,

        /// Force overwrite if exists
        #[arg(long)]
        force: bool,

        /// Validate before importing
        #[arg(long, default_value = "true")]
        validate: bool,
    },

    /// View command history and get suggestions
    History {
        /// Number of recent commands to show
        #[arg(short = 'n', long, default_value = "20")]
        limit: usize,

        /// Show usage statistics
        #[arg(long)]
        stats: bool,

        /// Show command suggestions based on history
        #[arg(long)]
        suggest: bool,

        /// Clear all history
        #[arg(long)]
        clear: bool,
    },

    /// Workflow automation commands
    Workflow {
        /// Workflow subcommand to execute
        #[command(subcommand)]
        command: commands::workflow::WorkflowCommands,
    },

    /// Manage command aliases
    Alias {
        /// Alias subcommand
        #[command(subcommand)]
        command: AliasCommand,
    },
}

/// Alias management subcommands
#[derive(Subcommand)]
pub enum AliasCommand {
    /// Add a new alias
    Add {
        /// Alias name
        name: String,

        /// Command to execute (without 'voirs' prefix)
        command: String,

        /// Optional description
        #[arg(short, long)]
        description: Option<String>,
    },

    /// Remove an alias
    Remove {
        /// Alias name to remove
        name: String,
    },

    /// List all aliases
    List,

    /// Show details of a specific alias
    Show {
        /// Alias name to show
        name: String,
    },

    /// Clear all aliases
    Clear,
}

/// CLI application implementation
impl CliApp {
    /// Run the CLI application
    pub async fn run() -> Result<()> {
        let app = Self::parse();

        // Initialize logging
        app.init_logging()?;

        // Load configuration
        let config = app.load_config().await?;

        // Execute command
        app.execute_command(config).await
    }

    /// Initialize logging based on verbosity
    fn init_logging(&self) -> Result<()> {
        let level = if self.global.quiet {
            tracing::Level::ERROR
        } else {
            match self.global.verbose {
                0 => tracing::Level::INFO,
                1 => tracing::Level::DEBUG,
                _ => tracing::Level::TRACE,
            }
        };

        tracing_subscriber::fmt()
            .with_max_level(level)
            .with_target(false)
            .with_writer(std::io::stderr) // Always write logs to stderr, not stdout
            .init();

        Ok(())
    }

    /// Load configuration from file or use defaults
    async fn load_config(&self) -> Result<AppConfig> {
        let mut config = if let Some(config_path) = &self.global.config {
            tracing::info!("Loading configuration from {:?}", config_path);
            self.load_config_from_file(config_path).await?
        } else {
            // Try to load from default locations
            self.load_config_from_default_locations().await?
        };

        // Apply CLI overrides
        self.apply_cli_overrides(&mut config);

        Ok(config)
    }

    /// Load configuration from a specific file
    async fn load_config_from_file(&self, config_path: &std::path::Path) -> Result<AppConfig> {
        if !config_path.exists() {
            tracing::warn!(
                "Configuration file not found: {}, using defaults",
                config_path.display()
            );
            return Ok(AppConfig::default());
        }

        let content =
            std::fs::read_to_string(config_path).map_err(|e| voirs_sdk::VoirsError::IoError {
                path: config_path.to_path_buf(),
                operation: voirs_sdk::error::IoOperation::Read,
                source: e,
            })?;

        // Optimized format detection - use content analysis for better performance
        let config = match config_path.extension().and_then(|ext| ext.to_str()) {
            Some("toml") => {
                // For TOML files, try TOML first but allow fallback for compatibility
                toml::from_str(&content).or_else(|_| {
                    // Fallback to auto-detection for compatibility with tests
                    self.parse_config_auto_detect(&content)
                })?
            }
            Some("json") => {
                // For JSON files, try JSON first but allow fallback for compatibility
                serde_json::from_str(&content).or_else(|_| {
                    // Fallback to auto-detection for compatibility
                    self.parse_config_auto_detect(&content)
                })?
            }
            Some("yaml") | Some("yml") => {
                // For YAML files, try YAML first but allow fallback for compatibility
                serde_yaml::from_str(&content).or_else(|_| {
                    // Fallback to auto-detection for compatibility
                    self.parse_config_auto_detect(&content)
                })?
            }
            _ => {
                // Auto-detect format with optimized content analysis
                self.parse_config_auto_detect(&content)?
            }
        };

        tracing::info!(
            "Successfully loaded configuration from {}",
            config_path.display()
        );
        Ok(config)
    }

    /// Load configuration from default locations
    async fn load_config_from_default_locations(&self) -> Result<AppConfig> {
        let possible_paths = get_default_config_paths();

        for path in possible_paths {
            if path.exists() {
                tracing::info!("Found configuration file at: {}", path.display());
                return self.load_config_from_file(&path).await;
            }
        }

        // No config file found, use defaults
        tracing::info!("No configuration file found, using defaults");
        Ok(AppConfig::default())
    }

    /// Parse configuration with optimized auto-detection
    fn parse_config_auto_detect(&self, content: &str) -> Result<AppConfig> {
        // Optimized format detection using content analysis
        // Check for format indicators without parsing the entire content
        let trimmed = content.trim_start();

        if trimmed.starts_with('{') {
            // Likely JSON format
            serde_json::from_str(content).map_err(|e| {
                voirs_sdk::VoirsError::config_error(format!(
                    "Failed to parse JSON configuration: {}",
                    e
                ))
            })
        } else if trimmed.contains("---") || content.contains(": ") {
            // Likely YAML format (contains YAML indicators)
            serde_yaml::from_str(content).or_else(|yaml_err| {
                // Try TOML as fallback
                toml::from_str(content).map_err(|toml_err| {
                    voirs_sdk::VoirsError::config_error(format!(
                        "Failed to parse configuration. YAML error: {}, TOML error: {}",
                        yaml_err, toml_err
                    ))
                })
            })
        } else {
            // Try TOML first, then JSON, then YAML
            toml::from_str(content)
                .or_else(|_| serde_json::from_str(content))
                .or_else(|_| serde_yaml::from_str(content))
                .map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!(
                        "Unable to parse configuration file. Supported formats: TOML, JSON, YAML. Last error: {}", e
                    ))
                })
        }
    }

    /// Apply CLI overrides to configuration
    fn apply_cli_overrides(&self, config: &mut AppConfig) {
        if self.global.gpu {
            config.pipeline.use_gpu = true;
        }

        if let Some(threads) = self.global.threads {
            config.pipeline.num_threads = Some(threads);
        }

        if let Some(ref voice) = self.global.voice {
            config.cli.default_voice = Some(voice.clone());
        }

        if let Some(ref format) = self.global.format {
            config.cli.default_format = (*format).into();
            // Also update the synthesis config format
            config.pipeline.default_synthesis.output_format = (*format).into();
        }
    }

    /// Execute the specified command
    async fn execute_command(&self, config: AppConfig) -> Result<()> {
        match &self.command {
            Commands::Synthesize {
                text,
                output,
                rate,
                pitch,
                volume,
                quality,
                enhance,
                play,
                auto_detect,
            } => {
                let args = commands::synthesize::SynthesizeArgs {
                    text,
                    output: output.as_deref(),
                    rate: *rate,
                    pitch: *pitch,
                    volume: *volume,
                    quality: (*quality).into(),
                    enhance: *enhance,
                    play: *play,
                    auto_detect: *auto_detect,
                };
                commands::synthesize::run_synthesize(args, &config, &self.global).await
            }

            Commands::SynthesizeFile {
                input,
                output_dir,
                rate,
                quality,
            } => {
                commands::synthesize::run_synthesize_file(
                    input,
                    output_dir.as_deref(),
                    *rate,
                    (*quality).into(),
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::ListVoices { language, detailed } => {
                commands::voices::run_list_voices(language.as_deref(), *detailed, &config).await
            }

            Commands::VoiceInfo { voice_id } => {
                commands::voices::run_voice_info(voice_id, &config).await
            }

            Commands::DownloadVoice { voice_id, force } => {
                commands::voices::run_download_voice(voice_id, *force, &config).await
            }

            Commands::PreviewVoice {
                voice_id,
                text,
                output,
                no_play,
            } => {
                commands::voices::run_preview_voice(
                    voice_id,
                    text.as_deref(),
                    output.as_ref(),
                    *no_play,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::CompareVoices { voice_ids } => {
                commands::voices::run_compare_voices(voice_ids.clone(), &config).await
            }

            Commands::Test { text, play } => {
                commands::test::run_test(text, *play, &config, &self.global).await
            }

            Commands::CrossLangTest {
                format,
                save_report,
            } => {
                commands::cross_lang_test::run_cross_lang_tests(
                    format,
                    *save_report,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::TestApi {
                server_url,
                api_key,
                concurrent,
                report,
                verbose,
            } => commands::test_api::run_api_tests(
                server_url.clone(),
                api_key.clone(),
                *concurrent,
                report.clone(),
                *verbose,
            )
            .await
            .map_err(|e| voirs_sdk::VoirsError::InternalError {
                component: "API Tester".to_string(),
                message: e.to_string(),
            }),

            Commands::Config { show, init, path } => {
                commands::config::run_config(*show, *init, path.as_deref(), &config).await
            }

            Commands::ListModels { backend, detailed } => {
                commands::models::run_list_models(
                    backend.as_deref(),
                    *detailed,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::DownloadModel { model_id, force } => {
                commands::models::run_download_model(model_id, *force, &config, &self.global).await
            }

            Commands::BenchmarkModels {
                model_ids,
                iterations,
                accuracy,
            } => {
                commands::models::run_benchmark_models(
                    model_ids,
                    *iterations,
                    *accuracy,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::OptimizeModel {
                model_id,
                output,
                strategy,
            } => {
                commands::models::run_optimize_model(
                    model_id,
                    output.as_deref(),
                    Some(strategy),
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::Batch {
                input,
                output_dir,
                workers,
                rate,
                pitch,
                volume,
                quality,
                resume,
            } => {
                commands::batch::run_batch_process(
                    commands::batch::BatchProcessArgs {
                        input,
                        output_dir: output_dir.as_deref(),
                        workers: *workers,
                        quality: (*quality).into(),
                        rate: *rate,
                        pitch: *pitch,
                        volume: *volume,
                        resume: *resume,
                    },
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::Server { port, host } => {
                commands::server::run_server(host, *port, &config).await
            }

            Commands::Interactive {
                voice,
                no_audio,
                debug,
                load_session,
                auto_save,
            } => {
                let options = commands::interactive::InteractiveOptions {
                    voice: voice.clone(),
                    no_audio: *no_audio,
                    debug: *debug,
                    load_session: load_session.clone(),
                    auto_save: *auto_save,
                };

                commands::interactive::run_interactive(options)
                    .await
                    .map_err(Into::into)
            }

            Commands::Guide {
                command,
                getting_started,
                examples,
            } => {
                let help_system = help::HelpSystem::new();

                if *getting_started {
                    println!("{}", help::display_getting_started());
                } else if *examples {
                    println!("{}", help_system.display_command_overview());
                } else if let Some(cmd) = command {
                    println!("{}", help_system.display_command_help(cmd));
                } else {
                    println!("{}", help_system.display_command_overview());
                }

                Ok(())
            }

            Commands::GenerateCompletion {
                shell,
                output,
                install_help,
                install_script,
                status,
            } => {
                if *status {
                    println!("{}", completion::display_completion_status());
                } else if *install_script {
                    println!("{}", completion::generate_install_script());
                } else if *install_help {
                    println!("{}", completion::get_installation_instructions(*shell));
                } else if let Some(output_path) = output {
                    completion::generate_completion_to_file(*shell, output_path).map_err(|e| {
                        voirs_sdk::VoirsError::IoError {
                            path: output_path.clone(),
                            operation: voirs_sdk::error::IoOperation::Write,
                            source: e,
                        }
                    })?;
                    println!("Completion script generated: {}", output_path.display());
                } else {
                    completion::generate_completion_to_stdout(*shell).map_err(|e| {
                        voirs_sdk::VoirsError::IoError {
                            path: std::env::current_dir().unwrap_or_default(),
                            operation: voirs_sdk::error::IoOperation::Write,
                            source: e,
                        }
                    })?;
                }

                Ok(())
            }

            Commands::Dataset { command } => {
                commands::dataset::execute_dataset_command(command, &config, &self.global).await
            }

            Commands::Dashboard { interval } => commands::dashboard::run_dashboard(*interval)
                .await
                .map_err(|e| voirs_sdk::VoirsError::InternalError {
                    component: "Dashboard".to_string(),
                    message: e.to_string(),
                }),

            Commands::Cloud { command } => {
                commands::cloud::execute_cloud_command(command, &config, &self.global).await
            }

            Commands::Telemetry { command } => commands::telemetry::execute(command.clone())
                .await
                .map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!("Telemetry command failed: {}", e))
                }),

            Commands::Lsp { verbose } => {
                if *verbose {
                    eprintln!("Starting VoiRS LSP server in verbose mode...");
                }

                let server = crate::lsp::LspServer::new();
                server.start().await.map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!("LSP server failed: {}", e))
                })
            }

            #[cfg(feature = "onnx")]
            Commands::Kokoro { command } => {
                commands::kokoro::execute_kokoro_command(command, &config, &self.global).await
            }

            #[cfg(feature = "onnx")]
            Commands::Onnx { command } => commands::onnx_tools::handle_onnx_command(command)
                .map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!("ONNX tool failed: {}", e))
                }),

            Commands::Accuracy { command } => {
                commands::accuracy::execute_accuracy_command(command.clone())
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Accuracy command failed: {}",
                            e
                        ))
                    })
            }

            Commands::Performance { command } => {
                commands::performance::execute_performance_command(command.clone())
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Performance command failed: {}",
                            e
                        ))
                    })
            }

            #[cfg(feature = "emotion")]
            Commands::Emotion { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::emotion::execute_emotion_command(command.clone(), &output_formatter)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Emotion command failed: {}",
                            e
                        ))
                    })
            }

            #[cfg(feature = "cloning")]
            Commands::Clone { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::cloning::execute_cloning_command(command.clone(), &output_formatter)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Cloning command failed: {}",
                            e
                        ))
                    })
            }

            #[cfg(feature = "conversion")]
            Commands::Convert { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::conversion::execute_conversion_command(command.clone(), &output_formatter)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Conversion command failed: {}",
                            e
                        ))
                    })
            }

            #[cfg(feature = "singing")]
            Commands::Sing { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::singing::execute_singing_command(command.clone(), &output_formatter)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Singing command failed: {}",
                            e
                        ))
                    })
            }

            #[cfg(feature = "spatial")]
            Commands::Spatial { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::spatial::execute_spatial_command(command.clone(), &output_formatter)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Spatial command failed: {}",
                            e
                        ))
                    })
            }

            Commands::Capabilities { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::capabilities::execute_capabilities_command(
                    command.clone(),
                    &output_formatter,
                    &config,
                )
                .await
                .map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!(
                        "Capabilities command failed: {}",
                        e
                    ))
                })
            }

            Commands::Checkpoint { command } => {
                commands::checkpoint::execute_checkpoint_command(command.clone(), &self.global)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Checkpoint command failed: {}",
                            e
                        ))
                    })
            }

            Commands::Monitor { command } => {
                use crate::output::OutputFormatter;
                let output_formatter = OutputFormatter::new(!self.global.quiet, false);
                commands::monitoring::execute_monitoring_command(
                    command.clone(),
                    &output_formatter,
                    &config,
                )
                .await
                .map_err(|e| {
                    voirs_sdk::VoirsError::config_error(format!("Monitoring command failed: {}", e))
                })
            }

            Commands::Train { command } => {
                commands::train::execute_train_command(command.clone(), &self.global)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!("Train command failed: {}", e))
                    })
            }

            Commands::ConvertModel {
                input,
                output,
                from,
                model_type,
                verify,
            } => commands::convert_model::run_convert_model(
                input.clone(),
                output.clone(),
                from.clone(),
                model_type.clone(),
                *verify,
                &self.global,
            )
            .await
            .map_err(|e| {
                voirs_sdk::VoirsError::config_error(format!("Model conversion failed: {}", e))
            }),

            Commands::VocoderInfer {
                checkpoint,
                mel,
                output,
                steps,
                quality,
                batch_input,
                batch_output,
                metrics,
            } => {
                let config = commands::vocoder_inference::VocoderInferenceConfig {
                    checkpoint: checkpoint.as_path(),
                    mel_path: mel.as_deref(),
                    output: output.as_path(),
                    steps: *steps,
                    quality: quality.as_deref(),
                    batch_input: batch_input.as_ref(),
                    batch_output: batch_output.as_ref(),
                    show_metrics: *metrics,
                };
                commands::vocoder_inference::run_vocoder_inference(config, &self.global)
                    .await
                    .map_err(|e| {
                        voirs_sdk::VoirsError::config_error(format!(
                            "Vocoder inference failed: {}",
                            e
                        ))
                    })
            }

            Commands::Stream {
                text,
                latency,
                chunk_size,
                buffer_chunks,
                play,
            } => {
                commands::streaming::run_streaming_synthesis(
                    text.as_deref(),
                    *latency,
                    *chunk_size,
                    *buffer_chunks,
                    *play,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::ModelInspect {
                model,
                detailed,
                export,
                verify,
            } => {
                commands::model_inspect::run_model_inspect(
                    model,
                    *detailed,
                    export.as_ref(),
                    *verify,
                    &self.global,
                )
                .await
            }

            Commands::Export {
                export_type,
                source,
                output,
                include_weights,
            } => {
                commands::export_import::run_export(
                    export_type,
                    source,
                    output,
                    *include_weights,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::Import {
                input,
                name,
                force,
                validate,
            } => {
                commands::export_import::run_import(
                    input,
                    name.as_deref(),
                    *force,
                    *validate,
                    &config,
                    &self.global,
                )
                .await
            }

            Commands::History {
                limit,
                stats,
                suggest,
                clear,
            } => commands::history::run_history(*limit, *stats, *suggest, *clear).await,

            Commands::Workflow { command } => {
                use commands::workflow::WorkflowCommands;
                match command {
                    WorkflowCommands::Execute {
                        workflow_file,
                        variables,
                        max_parallel,
                        resume,
                        state_dir,
                    } => commands::workflow::run_workflow_execute(
                        workflow_file.clone(),
                        variables.clone(),
                        *max_parallel,
                        *resume,
                        state_dir.clone(),
                    )
                    .await
                    .map_err(|e| voirs_sdk::VoirsError::InternalError {
                        component: "Workflow".to_string(),
                        message: e.to_string(),
                    }),
                    WorkflowCommands::Validate {
                        workflow_file,
                        detailed,
                        format,
                    } => commands::workflow::run_workflow_validate(
                        workflow_file.clone(),
                        *detailed,
                        format.clone(),
                    )
                    .await
                    .map_err(|e| voirs_sdk::VoirsError::InternalError {
                        component: "Workflow".to_string(),
                        message: e.to_string(),
                    }),
                    WorkflowCommands::List {
                        registry_dir,
                        detailed,
                    } => commands::workflow::run_workflow_list(registry_dir.clone(), *detailed)
                        .await
                        .map_err(|e| voirs_sdk::VoirsError::InternalError {
                            component: "Workflow".to_string(),
                            message: e.to_string(),
                        }),
                    WorkflowCommands::Status {
                        workflow_name,
                        state_dir,
                        format,
                    } => commands::workflow::run_workflow_status(
                        workflow_name.clone(),
                        state_dir.clone(),
                        format.clone(),
                    )
                    .await
                    .map_err(|e| voirs_sdk::VoirsError::InternalError {
                        component: "Workflow".to_string(),
                        message: e.to_string(),
                    }),
                    WorkflowCommands::Resume {
                        workflow_name,
                        state_dir,
                        max_parallel,
                    } => commands::workflow::run_workflow_resume(
                        workflow_name.clone(),
                        state_dir.clone(),
                        *max_parallel,
                    )
                    .await
                    .map_err(|e| voirs_sdk::VoirsError::InternalError {
                        component: "Workflow".to_string(),
                        message: e.to_string(),
                    }),
                    WorkflowCommands::Stop {
                        workflow_name,
                        state_dir,
                        force,
                    } => commands::workflow::run_workflow_stop(
                        workflow_name.clone(),
                        state_dir.clone(),
                        *force,
                    )
                    .await
                    .map_err(|e| voirs_sdk::VoirsError::InternalError {
                        component: "Workflow".to_string(),
                        message: e.to_string(),
                    }),
                }
            }

            Commands::Alias { command } => {
                use commands::alias::AliasSubcommand;
                let subcommand = match command {
                    AliasCommand::Add {
                        name,
                        command,
                        description,
                    } => AliasSubcommand::Add {
                        name: name.clone(),
                        command: command.clone(),
                        description: description.clone(),
                    },
                    AliasCommand::Remove { name } => AliasSubcommand::Remove { name: name.clone() },
                    AliasCommand::List => AliasSubcommand::List,
                    AliasCommand::Show { name } => AliasSubcommand::Show { name: name.clone() },
                    AliasCommand::Clear => AliasSubcommand::Clear,
                };
                commands::alias::run_alias(subcommand).await
            }
        }
    }
}

/// Utility functions for CLI
pub mod utils {
    use crate::cli_types::CliAudioFormat;
    use std::path::Path;
    use voirs_sdk::AudioFormat;

    /// Determine output format from file extension
    pub fn format_from_extension(path: &Path) -> Option<AudioFormat> {
        path.extension()
            .and_then(|ext| ext.to_str())
            .and_then(|ext| match ext.to_lowercase().as_str() {
                "wav" => Some(AudioFormat::Wav),
                "flac" => Some(AudioFormat::Flac),
                "mp3" => Some(AudioFormat::Mp3),
                "opus" => Some(AudioFormat::Opus),
                "ogg" => Some(AudioFormat::Ogg),
                _ => None,
            })
    }

    /// Generate output filename for text
    pub fn generate_output_filename(text: &str, format: AudioFormat) -> String {
        let safe_text = text
            .chars()
            .take(30)
            .filter(|c| c.is_alphanumeric() || c.is_whitespace())
            .collect::<String>()
            .replace(' ', "_")
            .to_lowercase();

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("SystemTime should be after UNIX_EPOCH")
            .as_secs();

        format!("voirs_{}_{}.{}", safe_text, timestamp, format.extension())
    }
}

/// Get default configuration file paths in order of preference
fn get_default_config_paths() -> Vec<std::path::PathBuf> {
    let mut paths = Vec::new();

    // 1. Current directory
    paths.push(
        std::env::current_dir()
            .unwrap_or_default()
            .join("voirs.toml"),
    );
    paths.push(
        std::env::current_dir()
            .unwrap_or_default()
            .join("voirs.json"),
    );
    paths.push(
        std::env::current_dir()
            .unwrap_or_default()
            .join("voirs.yaml"),
    );

    // 2. User config directory
    if let Some(config_dir) = dirs::config_dir() {
        let voirs_config_dir = config_dir.join("voirs");
        paths.push(voirs_config_dir.join("config.toml"));
        paths.push(voirs_config_dir.join("config.json"));
        paths.push(voirs_config_dir.join("config.yaml"));
        paths.push(voirs_config_dir.join("voirs.toml"));
        paths.push(voirs_config_dir.join("voirs.json"));
        paths.push(voirs_config_dir.join("voirs.yaml"));
    }

    // 3. Home directory
    if let Some(home_dir) = dirs::home_dir() {
        paths.push(home_dir.join(".voirs.toml"));
        paths.push(home_dir.join(".voirs.json"));
        paths.push(home_dir.join(".voirs.yaml"));
        paths.push(home_dir.join(".voirsrc"));
        paths.push(home_dir.join(".config").join("voirs").join("config.toml"));
    }

    paths
}

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

    #[test]
    fn test_format_from_extension() {
        use std::path::Path;

        assert_eq!(
            utils::format_from_extension(Path::new("test.wav")),
            Some(AudioFormat::Wav)
        );
        assert_eq!(
            utils::format_from_extension(Path::new("test.flac")),
            Some(AudioFormat::Flac)
        );
        assert_eq!(
            utils::format_from_extension(Path::new("test.unknown")),
            None
        );
    }

    #[test]
    fn test_generate_output_filename() {
        let filename = utils::generate_output_filename("Hello World", AudioFormat::Wav);
        assert!(filename.starts_with("voirs_hello_world_"));
        assert!(filename.ends_with(".wav"));
    }
}