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
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
//! Performance optimizer for automated tuning and recommendations
//!
//! This module analyzes performance metrics and applies optimizations automatically
//! or provides detailed recommendations for manual optimization.

use super::{
    GpuMetrics, MemoryMetrics, OptimizationCategory, OptimizationRecommendation,
    PerformanceMetrics, SynthesisMetrics, SystemMetrics,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Performance optimizer configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizerConfig {
    /// Enable automatic optimizations
    pub auto_optimize: bool,
    /// Minimum improvement threshold to trigger optimization
    pub min_improvement_threshold: f64,
    /// Maximum optimization attempts per session
    pub max_optimization_attempts: u32,
    /// Optimization target priority
    pub optimization_targets: Vec<OptimizationTarget>,
    /// Resource constraints
    pub resource_constraints: ResourceConstraints,
    /// Optimization aggressiveness (1-10)
    pub aggressiveness: u8,
}

/// Optimization targets with priorities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationTarget {
    /// Target category
    pub category: OptimizationCategory,
    /// Priority weight (0.0-1.0)
    pub weight: f64,
    /// Enable automatic optimization for this target
    pub auto_optimize: bool,
}

/// Resource constraints for optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceConstraints {
    /// Maximum memory usage in MB
    pub max_memory_mb: Option<u64>,
    /// Maximum CPU usage percentage
    pub max_cpu_percent: Option<f64>,
    /// Maximum GPU memory usage in MB
    pub max_gpu_memory_mb: Option<u64>,
    /// Minimum disk space in MB
    pub min_disk_space_mb: Option<u64>,
    /// Target latency in milliseconds
    pub target_latency_ms: Option<f64>,
}

/// Optimization result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationResult {
    /// Applied optimizations
    pub applied: Vec<AppliedOptimization>,
    /// Performance improvement achieved
    pub improvement: PerformanceImprovement,
    /// Time taken to apply optimizations
    pub optimization_time: Duration,
    /// Whether optimization was successful
    pub success: bool,
    /// Error message if optimization failed
    pub error: Option<String>,
}

/// Details of an applied optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppliedOptimization {
    /// Optimization category
    pub category: OptimizationCategory,
    /// Description of what was changed
    pub description: String,
    /// Previous value/setting
    pub previous_value: String,
    /// New value/setting
    pub new_value: String,
    /// Expected improvement
    pub expected_improvement: f64,
    /// Actual improvement measured
    pub actual_improvement: Option<f64>,
}

/// Performance improvement metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceImprovement {
    /// CPU usage improvement (positive = better)
    pub cpu_improvement: f64,
    /// Memory usage improvement (positive = better)
    pub memory_improvement: f64,
    /// Synthesis speed improvement (positive = better)
    pub speed_improvement: f64,
    /// Overall performance score improvement
    pub overall_improvement: f64,
    /// Real-time factor improvement
    pub rtf_improvement: f64,
}

/// Performance optimizer
pub struct PerformanceOptimizer {
    /// Optimizer configuration
    config: OptimizerConfig,
    /// Applied optimizations history
    optimization_history: Vec<OptimizationResult>,
    /// Current optimization settings
    current_settings: HashMap<String, String>,
    /// Performance baseline
    baseline_metrics: Option<PerformanceMetrics>,
}

impl PerformanceOptimizer {
    /// Create a new performance optimizer
    pub fn new(config: OptimizerConfig) -> Self {
        Self {
            config,
            optimization_history: Vec::new(),
            current_settings: HashMap::new(),
            baseline_metrics: None,
        }
    }

    /// Set performance baseline
    pub fn set_baseline(&mut self, metrics: PerformanceMetrics) {
        self.baseline_metrics = Some(metrics);
    }

    /// Analyze metrics and generate optimization recommendations
    pub async fn analyze_and_recommend(
        &self,
        current_metrics: &PerformanceMetrics,
    ) -> Vec<OptimizationRecommendation> {
        let mut recommendations = Vec::new();

        // Analyze each optimization target
        for target in &self.config.optimization_targets {
            match target.category {
                OptimizationCategory::Memory => {
                    self.analyze_memory_optimization(
                        &mut recommendations,
                        &current_metrics.memory,
                        &current_metrics.system,
                        target.weight,
                    )
                    .await;
                }
                OptimizationCategory::Cpu => {
                    self.analyze_cpu_optimization(
                        &mut recommendations,
                        &current_metrics.system,
                        &current_metrics.synthesis,
                        target.weight,
                    )
                    .await;
                }
                OptimizationCategory::Gpu => {
                    if let Some(ref gpu_metrics) = current_metrics.gpu {
                        self.analyze_gpu_optimization(
                            &mut recommendations,
                            gpu_metrics,
                            &current_metrics.synthesis,
                            target.weight,
                        )
                        .await;
                    }
                }
                OptimizationCategory::Parallelization => {
                    self.analyze_parallelization_optimization(
                        &mut recommendations,
                        &current_metrics.synthesis,
                        &current_metrics.system,
                        target.weight,
                    )
                    .await;
                }
                OptimizationCategory::Caching => {
                    self.analyze_caching_optimization(
                        &mut recommendations,
                        &current_metrics.memory,
                        &current_metrics.synthesis,
                        target.weight,
                    )
                    .await;
                }
                OptimizationCategory::ModelOptimization => {
                    self.analyze_model_optimization(
                        &mut recommendations,
                        &current_metrics.synthesis,
                        &current_metrics.system,
                        target.weight,
                    )
                    .await;
                }
                _ => {
                    // Handle other categories
                    self.analyze_general_optimization(
                        &mut recommendations,
                        current_metrics,
                        &target.category,
                        target.weight,
                    )
                    .await;
                }
            }
        }

        // Sort by priority and filter by improvement threshold
        recommendations.sort_by(|a, b| {
            b.priority.cmp(&a.priority).then(
                b.performance_impact
                    .partial_cmp(&a.performance_impact)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
        });

        recommendations
            .into_iter()
            .filter(|r| r.performance_impact >= self.config.min_improvement_threshold)
            .take(10) // Limit to top 10 recommendations
            .collect()
    }

    /// Apply automatic optimizations
    pub async fn apply_optimizations(
        &mut self,
        recommendations: &[OptimizationRecommendation],
    ) -> OptimizationResult {
        let start_time = std::time::Instant::now();
        let mut applied = Vec::new();
        let mut total_improvement = 0.0;

        for recommendation in recommendations {
            // Check if auto-optimization is enabled for this category
            let auto_optimize = self
                .config
                .optimization_targets
                .iter()
                .find(|t| t.category == recommendation.category)
                .map(|t| t.auto_optimize)
                .unwrap_or(false);

            if !auto_optimize || !self.config.auto_optimize {
                continue;
            }

            if let Ok(optimization) = self.apply_single_optimization(recommendation).await {
                total_improvement += optimization.expected_improvement;
                applied.push(optimization);
            }
        }

        let optimization_time = start_time.elapsed();

        OptimizationResult {
            applied,
            improvement: PerformanceImprovement {
                cpu_improvement: total_improvement * 0.3,
                memory_improvement: total_improvement * 0.2,
                speed_improvement: total_improvement * 0.4,
                overall_improvement: total_improvement,
                rtf_improvement: total_improvement * 0.5,
            },
            optimization_time,
            success: total_improvement > 0.0,
            error: None,
        }
    }

    /// Apply a single optimization
    async fn apply_single_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<AppliedOptimization, Box<dyn std::error::Error>> {
        let (setting_key, previous_value, new_value) = match recommendation.category {
            OptimizationCategory::Memory => self.apply_memory_optimization(recommendation).await?,
            OptimizationCategory::Cpu => self.apply_cpu_optimization(recommendation).await?,
            OptimizationCategory::Gpu => self.apply_gpu_optimization(recommendation).await?,
            OptimizationCategory::Parallelization => {
                self.apply_parallelization_optimization(recommendation)
                    .await?
            }
            OptimizationCategory::Caching => {
                self.apply_caching_optimization(recommendation).await?
            }
            OptimizationCategory::ModelOptimization => {
                self.apply_model_optimization(recommendation).await?
            }
            OptimizationCategory::Io => self.apply_io_optimization(recommendation).await?,
            OptimizationCategory::Network => {
                self.apply_network_optimization(recommendation).await?
            }
            OptimizationCategory::Configuration => {
                self.apply_configuration_optimization(recommendation)
                    .await?
            }
            OptimizationCategory::ResourceAllocation => {
                self.apply_resource_allocation_optimization(recommendation)
                    .await?
            }
        };

        // Update current settings
        self.current_settings
            .insert(setting_key.clone(), new_value.clone());

        Ok(AppliedOptimization {
            category: recommendation.category.clone(),
            description: recommendation.recommendation.clone(),
            previous_value,
            new_value,
            expected_improvement: recommendation.performance_impact,
            actual_improvement: None, // Will be measured later
        })
    }

    /// Memory optimization analysis
    async fn analyze_memory_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        memory: &MemoryMetrics,
        system: &SystemMetrics,
        weight: f64,
    ) {
        let memory_usage_percent = (memory.heap_used as f64
            / (system.memory_used + system.memory_available) as f64)
            * 100.0;

        if memory_usage_percent > 75.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Memory,
                priority: (8.0 * weight) as u8,
                description: format!("High memory usage: {:.1}%", memory_usage_percent),
                recommendation:
                    "Enable memory optimization: reduce batch size, enable streaming processing"
                        .to_string(),
                expected_improvement: format!("{:.0}% memory reduction", 30.0 * weight),
                difficulty: 2,
                performance_impact: 0.3 * weight,
            });
        }

        if memory.fragmentation_percent > 20.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Memory,
                priority: (6.0 * weight) as u8,
                description: format!("Memory fragmentation: {:.1}%", memory.fragmentation_percent),
                recommendation: "Enable memory pool allocation".to_string(),
                expected_improvement: format!("{:.0}% fragmentation reduction", 50.0 * weight),
                difficulty: 3,
                performance_impact: 0.15 * weight,
            });
        }

        if memory.cache_hit_rate < 60.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Caching,
                priority: (7.0 * weight) as u8,
                description: format!("Low cache hit rate: {:.1}%", memory.cache_hit_rate),
                recommendation: "Increase cache size and enable aggressive caching".to_string(),
                expected_improvement: format!(
                    "{:.0}% cache performance improvement",
                    40.0 * weight
                ),
                difficulty: 2,
                performance_impact: 0.25 * weight,
            });
        }
    }

    /// CPU optimization analysis
    async fn analyze_cpu_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        system: &SystemMetrics,
        synthesis: &SynthesisMetrics,
        weight: f64,
    ) {
        if system.cpu_usage > 90.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Cpu,
                priority: (9.0 * weight) as u8,
                description: format!("CPU overload: {:.1}%", system.cpu_usage),
                recommendation:
                    "Reduce parallel threads, enable GPU acceleration, or use lower quality"
                        .to_string(),
                expected_improvement: format!("{:.0}% CPU usage reduction", 40.0 * weight),
                difficulty: 2,
                performance_impact: 0.4 * weight,
            });
        } else if system.cpu_usage < 30.0 && synthesis.real_time_factor > 2.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Parallelization,
                priority: (6.0 * weight) as u8,
                description: format!("CPU underutilization: {:.1}%", system.cpu_usage),
                recommendation: "Increase parallel processing threads".to_string(),
                expected_improvement: format!("{:.0}% throughput increase", 30.0 * weight),
                difficulty: 1,
                performance_impact: 0.3 * weight,
            });
        }

        if synthesis.real_time_factor < 1.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::ModelOptimization,
                priority: (8.0 * weight) as u8,
                description: format!(
                    "Poor real-time performance: {:.2}x RTF",
                    synthesis.real_time_factor
                ),
                recommendation: "Use quantized models or enable GPU acceleration".to_string(),
                expected_improvement: "Achieve real-time synthesis".to_string(),
                difficulty: 4,
                performance_impact: 0.5 * weight,
            });
        }
    }

    /// GPU optimization analysis
    async fn analyze_gpu_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        gpu: &GpuMetrics,
        synthesis: &SynthesisMetrics,
        weight: f64,
    ) {
        if gpu.utilization < 40.0 && synthesis.real_time_factor < 2.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Gpu,
                priority: (7.0 * weight) as u8,
                description: format!("Low GPU utilization: {:.1}%", gpu.utilization),
                recommendation: "Increase batch size or use larger models".to_string(),
                expected_improvement: format!("{:.0}% GPU utilization improvement", 50.0 * weight),
                difficulty: 2,
                performance_impact: 0.3 * weight,
            });
        }

        let gpu_memory_usage = (gpu.memory_used as f64 / gpu.memory_total as f64) * 100.0;
        if gpu_memory_usage > 85.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Gpu,
                priority: (8.0 * weight) as u8,
                description: format!("High GPU memory usage: {:.1}%", gpu_memory_usage),
                recommendation: "Reduce batch size or enable model quantization".to_string(),
                expected_improvement: format!("{:.0}% GPU memory reduction", 30.0 * weight),
                difficulty: 3,
                performance_impact: 0.2 * weight,
            });
        }

        if gpu.temperature > 80.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Gpu,
                priority: (9.0 * weight) as u8,
                description: format!("High GPU temperature: {:.1}°C", gpu.temperature),
                recommendation: "Reduce GPU workload or improve cooling".to_string(),
                expected_improvement: "Prevent thermal throttling".to_string(),
                difficulty: 4,
                performance_impact: 0.25 * weight,
            });
        }
    }

    /// Parallelization optimization analysis
    async fn analyze_parallelization_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        synthesis: &SynthesisMetrics,
        system: &SystemMetrics,
        weight: f64,
    ) {
        let available_cores = system.thread_count;
        let estimated_utilization = system.cpu_usage / 100.0;

        if estimated_utilization < 0.6 && synthesis.queue_depth > 5 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Parallelization,
                priority: (7.0 * weight) as u8,
                description: format!(
                    "Suboptimal parallelization: {} cores available",
                    available_cores
                ),
                recommendation: format!(
                    "Increase worker threads to {}",
                    (available_cores as f64 * 0.8) as usize
                ),
                expected_improvement: format!("{:.0}% throughput improvement", 40.0 * weight),
                difficulty: 2,
                performance_impact: 0.35 * weight,
            });
        }

        if synthesis.avg_synthesis_time_ms > 1000.0 && synthesis.queue_depth < 2 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Parallelization,
                priority: (6.0 * weight) as u8,
                description: "Sequential processing detected".to_string(),
                recommendation: "Enable batch processing for improved efficiency".to_string(),
                expected_improvement: format!("{:.0}% processing time reduction", 25.0 * weight),
                difficulty: 2,
                performance_impact: 0.25 * weight,
            });
        }
    }

    /// Caching optimization analysis
    async fn analyze_caching_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        memory: &MemoryMetrics,
        synthesis: &SynthesisMetrics,
        weight: f64,
    ) {
        if memory.cache_hit_rate < 70.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Caching,
                priority: (7.0 * weight) as u8,
                description: format!(
                    "Low cache efficiency: {:.1}% hit rate",
                    memory.cache_hit_rate
                ),
                recommendation: "Increase cache size and implement model preloading".to_string(),
                expected_improvement: format!("{:.0}% cache hit rate improvement", 30.0 * weight),
                difficulty: 3,
                performance_impact: 0.3 * weight,
            });
        }

        if synthesis.avg_synthesis_time_ms > 500.0 && memory.cache_hit_rate > 80.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::Caching,
                priority: (5.0 * weight) as u8,
                description: "Opportunity for aggressive caching".to_string(),
                recommendation: "Enable result caching for repeated synthesis".to_string(),
                expected_improvement: format!("{:.0}% synthesis speed improvement", 50.0 * weight),
                difficulty: 3,
                performance_impact: 0.4 * weight,
            });
        }
    }

    /// Model optimization analysis
    async fn analyze_model_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        synthesis: &SynthesisMetrics,
        system: &SystemMetrics,
        weight: f64,
    ) {
        if synthesis.real_time_factor < 1.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::ModelOptimization,
                priority: (9.0 * weight) as u8,
                description: format!(
                    "Below real-time performance: {:.2}x",
                    synthesis.real_time_factor
                ),
                recommendation: "Use quantized models (INT8/FP16) for faster inference".to_string(),
                expected_improvement: format!("{:.0}x speed improvement", 2.0 * weight),
                difficulty: 4,
                performance_impact: 0.6 * weight,
            });
        }

        if synthesis.memory_per_operation_mb > 1000.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::ModelOptimization,
                priority: (7.0 * weight) as u8,
                description: format!(
                    "High memory per operation: {:.0} MB",
                    synthesis.memory_per_operation_mb
                ),
                recommendation: "Use model pruning or distillation for smaller footprint"
                    .to_string(),
                expected_improvement: format!("{:.0}% memory reduction", 40.0 * weight),
                difficulty: 5,
                performance_impact: 0.3 * weight,
            });
        }

        let memory_usage_percent =
            (synthesis.memory_per_operation_mb * synthesis.queue_depth as f64 * 1024.0 * 1024.0)
                / (system.memory_used + system.memory_available) as f64
                * 100.0;

        if memory_usage_percent > 50.0 {
            recommendations.push(OptimizationRecommendation {
                category: OptimizationCategory::ModelOptimization,
                priority: (8.0 * weight) as u8,
                description: "Models consuming excessive memory".to_string(),
                recommendation: "Use smaller model variants or enable model streaming".to_string(),
                expected_improvement: format!(
                    "{:.0}% memory efficiency improvement",
                    35.0 * weight
                ),
                difficulty: 4,
                performance_impact: 0.35 * weight,
            });
        }
    }

    /// General optimization analysis for other categories
    async fn analyze_general_optimization(
        &self,
        recommendations: &mut Vec<OptimizationRecommendation>,
        metrics: &PerformanceMetrics,
        category: &OptimizationCategory,
        weight: f64,
    ) {
        match category {
            OptimizationCategory::Io => {
                if metrics.system.disk_read_bps > 50_000_000
                    || metrics.system.disk_write_bps > 50_000_000
                {
                    recommendations.push(OptimizationRecommendation {
                        category: OptimizationCategory::Io,
                        priority: (6.0 * weight) as u8,
                        description: "High disk I/O detected".to_string(),
                        recommendation: "Use SSD storage or enable I/O optimization".to_string(),
                        expected_improvement: format!(
                            "{:.0}% I/O performance improvement",
                            40.0 * weight
                        ),
                        difficulty: 3,
                        performance_impact: 0.3 * weight,
                    });
                }
            }
            OptimizationCategory::Network => {
                if metrics.system.network_bps > 100_000_000 {
                    recommendations.push(OptimizationRecommendation {
                        category: OptimizationCategory::Network,
                        priority: (5.0 * weight) as u8,
                        description: "High network usage detected".to_string(),
                        recommendation: "Enable compression or local caching".to_string(),
                        expected_improvement: format!(
                            "{:.0}% network efficiency improvement",
                            25.0 * weight
                        ),
                        difficulty: 3,
                        performance_impact: 0.2 * weight,
                    });
                }
            }
            OptimizationCategory::Configuration => {
                recommendations.push(OptimizationRecommendation {
                    category: OptimizationCategory::Configuration,
                    priority: (4.0 * weight) as u8,
                    description: "Configuration optimization available".to_string(),
                    recommendation: "Review and optimize system configuration".to_string(),
                    expected_improvement: format!("{:.0}% overall improvement", 15.0 * weight),
                    difficulty: 2,
                    performance_impact: 0.15 * weight,
                });
            }
            OptimizationCategory::ResourceAllocation => {
                if metrics.synthesis.queue_depth > 10 {
                    recommendations.push(OptimizationRecommendation {
                        category: OptimizationCategory::ResourceAllocation,
                        priority: (7.0 * weight) as u8,
                        description: format!("High queue depth: {}", metrics.synthesis.queue_depth),
                        recommendation: "Optimize resource allocation and scheduling".to_string(),
                        expected_improvement: format!("{:.0}% latency reduction", 30.0 * weight),
                        difficulty: 3,
                        performance_impact: 0.25 * weight,
                    });
                }
            }
            _ => {} // Already handled in specific methods
        }
    }

    /// Apply memory optimization
    async fn apply_memory_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("High memory usage") {
            let key = "batch_size".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"32".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? / 2).to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("fragmentation") {
            let key = "memory_pool".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"false".to_string())
                .clone();
            let new_value = "true".to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown memory optimization".into())
        }
    }

    /// Apply CPU optimization
    async fn apply_cpu_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("CPU overload") {
            let key = "max_threads".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"8".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()?.saturating_sub(2)).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown CPU optimization".into())
        }
    }

    /// Apply GPU optimization
    async fn apply_gpu_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("Low GPU utilization") {
            let key = "gpu_batch_size".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"16".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? * 2).to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("High GPU memory") {
            let key = "gpu_batch_size".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"16".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? / 2).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown GPU optimization".into())
        }
    }

    /// Apply parallelization optimization
    async fn apply_parallelization_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.recommendation.contains("worker threads") {
            let key = "worker_threads".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"4".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? + 2).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown parallelization optimization".into())
        }
    }

    /// Apply caching optimization
    async fn apply_caching_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("cache") {
            let key = "cache_size_mb".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"256".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? * 2).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown caching optimization".into())
        }
    }

    /// Apply model optimization
    async fn apply_model_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.recommendation.contains("quantized") {
            let key = "model_precision".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"fp32".to_string())
                .clone();
            let new_value = "fp16".to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown model optimization".into())
        }
    }

    /// Apply I/O optimization
    async fn apply_io_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("buffering") {
            let key = "io_buffer_size".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"8192".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? * 2).to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("async") {
            let key = "async_io".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"false".to_string())
                .clone();
            let new_value = "true".to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown I/O optimization".into())
        }
    }

    /// Apply network optimization
    async fn apply_network_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("compression") {
            let key = "network_compression".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"none".to_string())
                .clone();
            let new_value = "gzip".to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("connection pool") {
            let key = "connection_pool_size".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"10".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? * 2).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown network optimization".into())
        }
    }

    /// Apply configuration optimization
    async fn apply_configuration_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("sample rate") {
            let key = "sample_rate".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"22050".to_string())
                .clone();
            let new_value = "16000".to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("quality") {
            let key = "quality_preset".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"high".to_string())
                .clone();
            let new_value = "medium".to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown configuration optimization".into())
        }
    }

    /// Apply resource allocation optimization
    async fn apply_resource_allocation_optimization(
        &mut self,
        recommendation: &OptimizationRecommendation,
    ) -> Result<(String, String, String), Box<dyn std::error::Error>> {
        if recommendation.description.contains("worker threads") {
            let key = "worker_threads".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"4".to_string())
                .clone();
            let cpu_count = num_cpus::get();
            let new_value = cpu_count.to_string();
            Ok((key, previous, new_value))
        } else if recommendation.description.contains("memory limit") {
            let key = "memory_limit_mb".to_string();
            let previous = self
                .current_settings
                .get(&key)
                .unwrap_or(&"1024".to_string())
                .clone();
            let new_value = (previous.parse::<u32>()? * 2).to_string();
            Ok((key, previous, new_value))
        } else {
            Err("Unknown resource allocation optimization".into())
        }
    }

    /// Get optimization history
    pub fn get_optimization_history(&self) -> &[OptimizationResult] {
        &self.optimization_history
    }

    /// Get current settings
    pub fn get_current_settings(&self) -> &HashMap<String, String> {
        &self.current_settings
    }

    /// Update configuration
    pub fn update_config(&mut self, config: OptimizerConfig) {
        self.config = config;
    }
}

impl Default for OptimizerConfig {
    fn default() -> Self {
        Self {
            auto_optimize: false,
            min_improvement_threshold: 0.1,
            max_optimization_attempts: 5,
            optimization_targets: vec![
                OptimizationTarget {
                    category: OptimizationCategory::Memory,
                    weight: 0.8,
                    auto_optimize: true,
                },
                OptimizationTarget {
                    category: OptimizationCategory::Cpu,
                    weight: 0.9,
                    auto_optimize: true,
                },
                OptimizationTarget {
                    category: OptimizationCategory::Gpu,
                    weight: 0.7,
                    auto_optimize: false,
                },
            ],
            resource_constraints: ResourceConstraints::default(),
            aggressiveness: 5,
        }
    }
}

impl Default for ResourceConstraints {
    fn default() -> Self {
        Self {
            max_memory_mb: Some(8192),
            max_cpu_percent: Some(80.0),
            max_gpu_memory_mb: Some(6144),
            min_disk_space_mb: Some(1024),
            target_latency_ms: Some(500.0),
        }
    }
}

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

    #[test]
    fn test_optimizer_config_default() {
        let config = OptimizerConfig::default();
        assert!(!config.auto_optimize);
        assert_eq!(config.aggressiveness, 5);
        assert!(config.optimization_targets.len() > 0);
    }

    #[tokio::test]
    async fn test_performance_optimizer_creation() {
        let config = OptimizerConfig::default();
        let optimizer = PerformanceOptimizer::new(config);
        assert_eq!(optimizer.optimization_history.len(), 0);
        assert_eq!(optimizer.current_settings.len(), 0);
    }

    #[tokio::test]
    async fn test_memory_optimization_analysis() {
        let config = OptimizerConfig::default();
        let optimizer = PerformanceOptimizer::new(config);

        let mut recommendations = Vec::new();
        let memory = MemoryMetrics {
            heap_used: 8_000_000_000, // 8GB
            fragmentation_percent: 25.0,
            cache_hit_rate: 50.0,
            ..Default::default()
        };
        let system = SystemMetrics {
            memory_used: 8_000_000_000,
            memory_available: 2_000_000_000,
            ..Default::default()
        };

        optimizer
            .analyze_memory_optimization(&mut recommendations, &memory, &system, 1.0)
            .await;

        assert!(recommendations.len() > 0);
        assert!(recommendations
            .iter()
            .any(|r| r.category == OptimizationCategory::Memory));
    }

    #[tokio::test]
    async fn test_cpu_optimization_analysis() {
        let config = OptimizerConfig::default();
        let optimizer = PerformanceOptimizer::new(config);

        let mut recommendations = Vec::new();
        let system = SystemMetrics {
            cpu_usage: 95.0, // High CPU usage
            ..Default::default()
        };
        let synthesis = SynthesisMetrics {
            real_time_factor: 0.5, // Poor RTF
            ..Default::default()
        };

        optimizer
            .analyze_cpu_optimization(&mut recommendations, &system, &synthesis, 1.0)
            .await;

        assert!(recommendations.len() > 0);
        assert!(recommendations
            .iter()
            .any(|r| r.category == OptimizationCategory::Cpu
                || r.category == OptimizationCategory::ModelOptimization));
    }

    #[tokio::test]
    async fn test_optimization_recommendation_sorting() {
        let config = OptimizerConfig::default();
        let optimizer = PerformanceOptimizer::new(config);

        let metrics = PerformanceMetrics {
            system: SystemMetrics {
                cpu_usage: 95.0,
                memory_used: 8_000_000_000,
                memory_available: 2_000_000_000,
                ..Default::default()
            },
            memory: MemoryMetrics {
                heap_used: 8_000_000_000,
                cache_hit_rate: 50.0,
                ..Default::default()
            },
            synthesis: SynthesisMetrics {
                real_time_factor: 0.5,
                ..Default::default()
            },
            ..Default::default()
        };

        let recommendations = optimizer.analyze_and_recommend(&metrics).await;

        assert!(!recommendations.is_empty());

        // Check that recommendations are sorted by priority
        for i in 1..recommendations.len() {
            assert!(recommendations[i - 1].priority >= recommendations[i].priority);
        }
    }
}