trustformers 0.1.1

TrustformeRS - Rust port of Hugging Face Transformers
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
//! Quality analyzer and streaming algorithms for conversational AI pipeline.
//!
//! This module provides comprehensive quality assessment for streaming conversational responses,
//! including real-time quality metrics, trend analysis, performance evaluation, and optimization
//! recommendations for natural and coherent streaming delivery.

use super::types::*;
use crate::pipeline::conversational::types::TrendDirection;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

// ================================================================================================
// QUALITY MEASUREMENT AND ANALYSIS TYPES
// ================================================================================================

/// Quality indicators for streaming
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingQuality {
    /// Smoothness score (0.0 to 1.0)
    pub smoothness: f32,
    /// Naturalness score (0.0 to 1.0)
    pub naturalness: f32,
    /// Responsiveness score (0.0 to 1.0)
    pub responsiveness: f32,
    /// Coherence score (0.0 to 1.0)
    pub coherence: f32,
    /// Overall quality score (0.0 to 1.0)
    pub overall_quality: f32,
    /// Chunk consistency score (0.0 to 1.0)
    pub chunk_consistency: f32,
    /// Flow smoothness score (0.0 to 1.0)
    pub flow_smoothness: f32,
    /// Timing accuracy score (0.0 to 1.0)
    pub timing_accuracy: f32,
    /// Buffer efficiency score (0.0 to 1.0)
    pub buffer_efficiency: f32,
}

impl Default for StreamingQuality {
    fn default() -> Self {
        Self {
            smoothness: 0.8,
            naturalness: 0.8,
            responsiveness: 0.8,
            coherence: 0.8,
            overall_quality: 0.8,
            chunk_consistency: 0.8,
            flow_smoothness: 0.8,
            timing_accuracy: 0.8,
            buffer_efficiency: 0.8,
        }
    }
}

/// Individual quality measurement
#[derive(Debug, Clone)]
pub struct QualityMeasurement {
    /// Timestamp of measurement
    pub timestamp: Instant,
    /// Smoothness score (0.0 to 1.0)
    pub smoothness: f32,
    /// Naturalness score (0.0 to 1.0)
    pub naturalness: f32,
    /// Responsiveness score (0.0 to 1.0)
    pub responsiveness: f32,
    /// Coherence score (0.0 to 1.0)
    pub coherence: f32,
    /// Latency (ms)
    pub latency_ms: f64,
    /// Chunk size consistency
    pub chunk_consistency: f32,
    /// Overall quality score (0.0 to 1.0)
    pub score: f32,
    /// Confidence in the measurement (0.0 to 1.0)
    pub confidence: f32,
    /// Quality trend direction
    pub trend: TrendDirection,
}

/// Quality thresholds for different aspects
#[derive(Debug, Clone)]
pub struct QualityThresholds {
    /// Minimum smoothness threshold
    pub min_smoothness: f32,
    /// Minimum naturalness threshold
    pub min_naturalness: f32,
    /// Minimum responsiveness threshold
    pub min_responsiveness: f32,
    /// Minimum coherence threshold
    pub min_coherence: f32,
    /// Maximum acceptable latency (ms)
    pub max_latency_ms: f64,
    /// Minimum overall quality threshold
    pub min_overall_quality: f32,
    /// Minimum acceptable quality level
    pub minimum_acceptable: f32,
    /// Target quality level
    pub target_quality: f32,
    /// Excellent quality threshold
    pub excellent_threshold: f32,
    /// Quality degradation threshold
    pub degradation_threshold: f32,
}

impl Default for QualityThresholds {
    fn default() -> Self {
        Self {
            min_smoothness: 0.7,
            min_naturalness: 0.6,
            min_responsiveness: 0.8,
            min_coherence: 0.7,
            max_latency_ms: 200.0,
            min_overall_quality: 0.7,
            minimum_acceptable: 0.6,
            target_quality: 0.8,
            excellent_threshold: 0.9,
            degradation_threshold: 0.5,
        }
    }
}

/// Quality trends analysis
#[derive(Debug, Clone)]
pub struct QualityTrends {
    /// Overall quality trend
    pub overall_trend: TrendDirection,
    /// Smoothness trend
    pub smoothness_trend: TrendDirection,
    /// Naturalness trend
    pub naturalness_trend: TrendDirection,
    /// Responsiveness trend
    pub responsiveness_trend: TrendDirection,
    /// Coherence trend
    pub coherence_trend: TrendDirection,
}

impl Default for QualityTrends {
    fn default() -> Self {
        Self {
            overall_trend: TrendDirection::Stable,
            smoothness_trend: TrendDirection::Stable,
            naturalness_trend: TrendDirection::Stable,
            responsiveness_trend: TrendDirection::Stable,
            coherence_trend: TrendDirection::Stable,
        }
    }
}

/// Advanced quality metrics for comprehensive analysis
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AdvancedQualityMetrics {
    /// Perceptual quality scores
    pub perceptual_quality: PerceptualQuality,
    /// Statistical analysis
    pub statistical_analysis: StatisticalAnalysis,
    /// Performance benchmarks
    pub performance_benchmarks: PerformanceBenchmarks,
    /// Quality degradation indicators
    pub degradation_indicators: DegradationIndicators,
}

/// Perceptual quality assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerceptualQuality {
    /// Fluency assessment (how natural the flow feels)
    pub fluency: f32,
    /// Engagement level (how engaging the content is)
    pub engagement: f32,
    /// Clarity score (how clear and understandable)
    pub clarity: f32,
    /// Emotional appropriateness
    pub emotional_tone: f32,
    /// Conversational flow quality
    pub conversation_flow: f32,
    /// User experience score
    pub user_experience_score: f32,
    /// Cognitive load assessment
    pub cognitive_load: f32,
    /// Attention retention score
    pub attention_retention: f32,
    /// Engagement flow quality
    pub engagement_flow: f32,
}

/// Statistical analysis of quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatisticalAnalysis {
    /// Mean quality scores over time window
    pub mean_scores: QualityScores,
    /// Standard deviation of quality metrics
    pub std_deviation: QualityScores,
    /// Quality variance indicators
    pub variance: QualityScores,
    /// Quality distribution percentiles
    pub percentiles: QualityPercentiles,
    /// Correlation analysis between metrics
    pub correlations: QualityCorrelations,
    /// Total number of chunks
    pub chunk_count: usize,
    /// Total number of characters
    pub total_characters: usize,
    /// Average chunk size
    pub average_chunk_size: f32,
    /// Distribution skew
    pub distribution_skew: f32,
}

/// Quality scores structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityScores {
    pub smoothness: f32,
    pub naturalness: f32,
    pub responsiveness: f32,
    pub coherence: f32,
}

/// Quality percentiles for distribution analysis
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QualityPercentiles {
    pub p25: QualityScores,
    pub p50: QualityScores,
    pub p75: QualityScores,
    pub p90: QualityScores,
    pub p95: QualityScores,
}

/// Correlation analysis between quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityCorrelations {
    pub smoothness_naturalness: f32,
    pub responsiveness_coherence: f32,
    pub latency_quality: f32,
    pub consistency_smoothness: f32,
}

/// Performance benchmarks and comparisons
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceBenchmarks {
    /// Benchmark scores against target performance
    pub target_comparison: BenchmarkComparison,
    /// Historical performance comparison
    pub historical_comparison: BenchmarkComparison,
    /// Peer comparison (if available)
    pub peer_comparison: Option<BenchmarkComparison>,
    /// Performance ranking percentile
    pub performance_percentile: f32,
    /// Latency percentiles (p50, p95, p99)
    pub latency_percentiles: (f32, f32, f32),
    /// Throughput in megabits per second
    pub throughput_mbps: f32,
    /// Resource efficiency score
    pub resource_efficiency: f32,
    /// Scalability factor
    pub scalability_factor: f32,
}

/// Benchmark comparison structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkComparison {
    pub relative_performance: f32,  // -1.0 to 1.0 (worse to better)
    pub improvement_potential: f32, // 0.0 to 1.0
    pub confidence_level: f32,      // 0.0 to 1.0
}

/// Quality degradation indicators and alerts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DegradationIndicators {
    /// Is quality degrading?
    pub is_degrading: bool,
    /// Rate of degradation (per hour)
    pub degradation_rate: f32,
    /// Predicted time to threshold breach
    pub time_to_threshold_breach: Option<Duration>,
    /// Critical quality areas
    pub critical_areas: Vec<QualityArea>,
    /// Recommended actions
    pub recommended_actions: Vec<OptimizationRecommendation>,
    /// Number of buffer overflows
    pub buffer_overflows: usize,
    /// Number of quality drops
    pub quality_drops: usize,
    /// Number of recovery events
    pub recovery_events: usize,
    /// Number of timing violations
    pub timing_violations: usize,
}

/// Quality areas for targeted analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QualityArea {
    Smoothness,
    Naturalness,
    Responsiveness,
    Coherence,
    Consistency,
    OverallPerformance,
    Performance,
    Reliability,
}

/// Optimization recommendations based on quality analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationRecommendation {
    /// Type of optimization
    pub optimization_type: OptimizationType,
    /// Recommendation type (alias for optimization_type for backward compatibility)
    pub recommendation_type: OptimizationType,
    /// Priority level (0.0 to 1.0)
    pub priority: f32,
    /// Expected improvement
    pub expected_improvement: f32,
    /// Implementation complexity
    pub complexity: ComplexityLevel,
    /// Description of the recommendation
    pub description: String,
    /// Affected quality areas
    pub affected_areas: Vec<QualityArea>,
}

/// Types of optimizations available
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OptimizationType {
    ChunkSizeAdjustment,
    TimingOptimization,
    FlowRateAdjustment,
    BufferManagement,
    PipelineReorganization,
    ModelParameterTuning,
    InfrastructureUpgrade,
    Performance,
}

/// Complexity levels for implementation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityLevel {
    Low,    // Quick configuration changes
    Medium, // Code modifications required
    High,   // Significant architectural changes
}

// ================================================================================================
// QUALITY ANALYZER IMPLEMENTATION
// ================================================================================================

/// Quality analyzer for streaming performance
#[derive(Debug)]
pub struct QualityAnalyzer {
    /// Quality metrics window
    metrics_window: Arc<RwLock<VecDeque<QualityMeasurement>>>,
    /// Window size for analysis
    window_size: usize,
    /// Quality thresholds
    pub thresholds: QualityThresholds,
    /// Advanced analysis enabled
    advanced_analysis_enabled: bool,
    /// Historical metrics for trend analysis
    historical_metrics: Arc<RwLock<VecDeque<StreamingQuality>>>,
    /// Performance baselines
    performance_baselines: Arc<RwLock<Option<StreamingQuality>>>,
    /// Overall quality measurement
    pub overall_quality: QualityMeasurement,
    /// Current streaming quality metrics
    pub streaming_quality: StreamingQuality,
    /// Advanced metrics data
    pub advanced_metrics: AdvancedQualityMetrics,
    /// Optimization recommendations
    pub optimization_recommendations: Vec<OptimizationRecommendation>,
    /// Quality thresholds configuration
    pub quality_thresholds: QualityThresholds,
    /// Assessment metadata
    pub assessment_metadata: std::collections::HashMap<String, String>,
}

impl QualityAnalyzer {
    /// Create a new quality analyzer
    pub fn new() -> Self {
        use crate::pipeline::conversational::types::TrendDirection;

        Self {
            metrics_window: Arc::new(RwLock::new(VecDeque::with_capacity(100))),
            window_size: 100,
            thresholds: QualityThresholds::default(),
            advanced_analysis_enabled: true,
            historical_metrics: Arc::new(RwLock::new(VecDeque::with_capacity(1000))),
            performance_baselines: Arc::new(RwLock::new(None)),
            overall_quality: QualityMeasurement {
                timestamp: Instant::now(),
                smoothness: 0.8,
                naturalness: 0.8,
                responsiveness: 0.8,
                coherence: 0.8,
                latency_ms: 100.0,
                chunk_consistency: 0.8,
                score: 0.8,
                confidence: 0.7,
                trend: TrendDirection::Stable,
            },
            streaming_quality: StreamingQuality::default(),
            advanced_metrics: AdvancedQualityMetrics::default(),
            optimization_recommendations: Vec::new(),
            quality_thresholds: QualityThresholds::default(),
            assessment_metadata: std::collections::HashMap::new(),
        }
    }

    /// Create a new quality analyzer with custom configuration
    pub fn with_config(window_size: usize, thresholds: QualityThresholds) -> Self {
        use crate::pipeline::conversational::types::TrendDirection;

        Self {
            metrics_window: Arc::new(RwLock::new(VecDeque::with_capacity(window_size))),
            window_size,
            thresholds: thresholds.clone(),
            advanced_analysis_enabled: true,
            historical_metrics: Arc::new(RwLock::new(VecDeque::with_capacity(1000))),
            performance_baselines: Arc::new(RwLock::new(None)),
            overall_quality: QualityMeasurement {
                timestamp: Instant::now(),
                smoothness: 0.8,
                naturalness: 0.8,
                responsiveness: 0.8,
                coherence: 0.8,
                latency_ms: 100.0,
                chunk_consistency: 0.8,
                score: 0.8,
                confidence: 0.7,
                trend: TrendDirection::Stable,
            },
            streaming_quality: StreamingQuality::default(),
            advanced_metrics: AdvancedQualityMetrics::default(),
            optimization_recommendations: Vec::new(),
            quality_thresholds: thresholds,
            assessment_metadata: std::collections::HashMap::new(),
        }
    }

    /// Get metrics window for external access
    pub fn metrics_window(&self) -> &Arc<RwLock<VecDeque<QualityMeasurement>>> {
        &self.metrics_window
    }

    /// Get window size
    pub fn window_size(&self) -> usize {
        self.window_size
    }

    /// Get quality thresholds
    pub fn thresholds(&self) -> &QualityThresholds {
        &self.thresholds
    }

    /// Analyze chunk quality with comprehensive metrics
    pub async fn analyze_chunk_quality(
        &self,
        chunk: &StreamChunk,
        delivery_time: Duration,
    ) -> QualityMeasurement {
        let smoothness = self.calculate_smoothness(chunk, delivery_time).await;
        let naturalness = self.calculate_naturalness(chunk).await;
        let responsiveness = self.calculate_responsiveness(delivery_time);
        let coherence = self.calculate_coherence(chunk).await;
        let chunk_consistency = self.calculate_chunk_consistency(chunk).await;

        // Calculate overall score as weighted average
        let score =
            smoothness * 0.25 + naturalness * 0.25 + responsiveness * 0.25 + coherence * 0.25;

        let measurement = QualityMeasurement {
            timestamp: Instant::now(),
            smoothness,
            naturalness,
            responsiveness,
            coherence,
            latency_ms: delivery_time.as_millis() as f64,
            chunk_consistency,
            score,
            confidence: (score * 0.8 + chunk_consistency * 0.2).min(1.0).max(0.0),
            trend: TrendDirection::Stable,
        };

        // Add to metrics window
        let mut window = self.metrics_window.write().await;
        window.push_back(measurement.clone());

        // Keep window size
        if window.len() > self.window_size {
            window.pop_front();
        }

        measurement
    }

    /// Calculate overall streaming quality
    pub async fn calculate_overall_quality(&self) -> StreamingQuality {
        let window = self.metrics_window.read().await;

        if window.is_empty() {
            return StreamingQuality::default();
        }

        let count = window.len() as f32;
        let smoothness = window.iter().map(|m| m.smoothness).sum::<f32>() / count;
        let naturalness = window.iter().map(|m| m.naturalness).sum::<f32>() / count;
        let responsiveness = window.iter().map(|m| m.responsiveness).sum::<f32>() / count;
        let coherence = window.iter().map(|m| m.coherence).sum::<f32>() / count;

        let overall_quality = (smoothness + naturalness + responsiveness + coherence) / 4.0;

        let quality = StreamingQuality {
            smoothness,
            naturalness,
            responsiveness,
            coherence,
            overall_quality,
            chunk_consistency: 0.8,
            flow_smoothness: 0.8,
            timing_accuracy: 0.8,
            buffer_efficiency: 0.8,
        };

        // Add to historical metrics
        let mut historical = self.historical_metrics.write().await;
        historical.push_back(quality.clone());
        if historical.len() > 1000 {
            historical.pop_front();
        }

        quality
    }

    /// Calculate advanced quality metrics with comprehensive analysis
    pub async fn calculate_advanced_metrics(&self) -> AdvancedQualityMetrics {
        if !self.advanced_analysis_enabled {
            return AdvancedQualityMetrics::default();
        }

        let window = self.metrics_window.read().await;
        let historical = self.historical_metrics.read().await;

        AdvancedQualityMetrics {
            perceptual_quality: self.calculate_perceptual_quality(&window).await,
            statistical_analysis: self.calculate_statistical_analysis(&window).await,
            performance_benchmarks: self.calculate_performance_benchmarks(&historical).await,
            degradation_indicators: self
                .calculate_degradation_indicators(&window, &historical)
                .await,
        }
    }

    /// Check if quality meets thresholds
    pub async fn meets_quality_thresholds(&self) -> bool {
        let quality = self.calculate_overall_quality().await;

        quality.smoothness >= self.thresholds.min_smoothness
            && quality.naturalness >= self.thresholds.min_naturalness
            && quality.responsiveness >= self.thresholds.min_responsiveness
            && quality.coherence >= self.thresholds.min_coherence
            && quality.overall_quality >= self.thresholds.min_overall_quality
    }

    /// Get quality trends with sophisticated analysis
    pub async fn get_quality_trends(&self) -> QualityTrends {
        let window = self.metrics_window.read().await;

        if window.len() < 10 {
            return QualityTrends::default();
        }

        let recent = &window.as_slices().0[window.len() - 5..];
        let earlier = &window.as_slices().0[window.len() - 10..window.len() - 5];

        let recent_avg = recent
            .iter()
            .map(|m| (m.smoothness + m.naturalness + m.responsiveness + m.coherence) / 4.0)
            .sum::<f32>()
            / recent.len() as f32;
        let earlier_avg = earlier
            .iter()
            .map(|m| (m.smoothness + m.naturalness + m.responsiveness + m.coherence) / 4.0)
            .sum::<f32>()
            / earlier.len() as f32;

        let overall_trend = self.calculate_trend_direction(recent_avg, earlier_avg);

        // Calculate individual metric trends
        let smoothness_trend = self.calculate_metric_trend(recent, earlier, |m| m.smoothness);
        let naturalness_trend = self.calculate_metric_trend(recent, earlier, |m| m.naturalness);
        let responsiveness_trend =
            self.calculate_metric_trend(recent, earlier, |m| m.responsiveness);
        let coherence_trend = self.calculate_metric_trend(recent, earlier, |m| m.coherence);

        QualityTrends {
            overall_trend,
            smoothness_trend,
            naturalness_trend,
            responsiveness_trend,
            coherence_trend,
        }
    }

    /// Generate optimization recommendations based on quality analysis
    pub async fn generate_optimization_recommendations(&self) -> Vec<OptimizationRecommendation> {
        let quality = self.calculate_overall_quality().await;
        let trends = self.get_quality_trends().await;
        let mut recommendations = Vec::new();

        // Analyze each quality dimension and provide recommendations
        if quality.smoothness < self.thresholds.min_smoothness {
            recommendations.push(OptimizationRecommendation {
                optimization_type: OptimizationType::ChunkSizeAdjustment,
                recommendation_type: OptimizationType::ChunkSizeAdjustment,
                priority: 0.8,
                expected_improvement: 0.15,
                complexity: ComplexityLevel::Low,
                description: "Adjust chunk sizes to improve smoothness - consider smaller, more consistent chunks".to_string(),
                affected_areas: vec![QualityArea::Smoothness],
            });
        }

        if quality.responsiveness < self.thresholds.min_responsiveness {
            recommendations.push(OptimizationRecommendation {
                optimization_type: OptimizationType::TimingOptimization,
                recommendation_type: OptimizationType::TimingOptimization,
                priority: 0.9,
                expected_improvement: 0.2,
                complexity: ComplexityLevel::Medium,
                description:
                    "Optimize timing algorithms to reduce latency and improve responsiveness"
                        .to_string(),
                affected_areas: vec![QualityArea::Responsiveness],
            });
        }

        if quality.naturalness < self.thresholds.min_naturalness {
            recommendations.push(OptimizationRecommendation {
                optimization_type: OptimizationType::ModelParameterTuning,
                recommendation_type: OptimizationType::ModelParameterTuning,
                priority: 0.7,
                expected_improvement: 0.1,
                complexity: ComplexityLevel::High,
                description:
                    "Fine-tune model parameters to improve naturalness of generated content"
                        .to_string(),
                affected_areas: vec![QualityArea::Naturalness],
            });
        }

        if quality.coherence < self.thresholds.min_coherence {
            recommendations.push(OptimizationRecommendation {
                optimization_type: OptimizationType::PipelineReorganization,
                recommendation_type: OptimizationType::PipelineReorganization,
                priority: 0.6,
                expected_improvement: 0.12,
                complexity: ComplexityLevel::High,
                description:
                    "Reorganize processing pipeline to maintain better coherence across chunks"
                        .to_string(),
                affected_areas: vec![QualityArea::Coherence],
            });
        }

        // Check for declining trends
        if trends.overall_trend == TrendDirection::Declining {
            recommendations.push(OptimizationRecommendation {
                optimization_type: OptimizationType::InfrastructureUpgrade,
                recommendation_type: OptimizationType::InfrastructureUpgrade,
                priority: 0.5,
                expected_improvement: 0.25,
                complexity: ComplexityLevel::High,
                description:
                    "Consider infrastructure upgrades to address declining performance trends"
                        .to_string(),
                affected_areas: vec![QualityArea::OverallPerformance],
            });
        }

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

    /// Set performance baseline for comparison
    pub async fn set_performance_baseline(&self, baseline: StreamingQuality) {
        let mut baselines = self.performance_baselines.write().await;
        *baselines = Some(baseline);
    }

    /// Clear quality metrics and reset analyzer
    pub async fn reset(&self) {
        let mut window = self.metrics_window.write().await;
        window.clear();

        let mut historical = self.historical_metrics.write().await;
        historical.clear();
    }

    // ================================================================================================
    // PRIVATE QUALITY CALCULATION METHODS
    // ================================================================================================

    /// Calculate smoothness with advanced algorithms
    async fn calculate_smoothness(&self, chunk: &StreamChunk, delivery_time: Duration) -> f32 {
        let mut smoothness = 0.8;

        // Timing consistency analysis
        let window = self.metrics_window.read().await;
        if window.len() > 1 {
            let timing_variance = self.calculate_timing_variance(&window);
            smoothness *= (1.0 - timing_variance.min(0.5)) * 2.0;
        }

        // Content length consistency
        let length_factor = self.calculate_length_consistency_factor(chunk);
        smoothness *= length_factor;

        // Delivery time smoothness
        let target_time_ms = 100.0;
        let actual_time_ms = delivery_time.as_millis() as f64;
        let timing_factor = if actual_time_ms <= target_time_ms * 1.5 {
            1.0
        } else {
            (target_time_ms / actual_time_ms).max(0.3) as f32
        };
        smoothness *= timing_factor;

        smoothness.max(0.0).min(1.0)
    }

    /// Calculate naturalness with linguistic analysis
    async fn calculate_naturalness(&self, chunk: &StreamChunk) -> f32 {
        let content = &chunk.content;
        let mut naturalness = 0.8;

        // Linguistic pattern analysis
        naturalness *= self.analyze_linguistic_patterns(content);

        // Content flow analysis
        naturalness *= self.analyze_content_flow(chunk).await;

        // Punctuation and structure analysis
        naturalness *= self.analyze_punctuation_structure(content);

        naturalness.max(0.0).min(1.0)
    }

    /// Calculate responsiveness based on delivery metrics
    fn calculate_responsiveness(&self, delivery_time: Duration) -> f32 {
        let target_time_ms = 100.0;
        let actual_time_ms = delivery_time.as_millis() as f64;

        if actual_time_ms <= target_time_ms {
            1.0
        } else if actual_time_ms <= target_time_ms * 2.0 {
            (target_time_ms / actual_time_ms).max(0.5) as f32
        } else {
            (target_time_ms / actual_time_ms).max(0.1) as f32
        }
    }

    /// Calculate coherence with context awareness
    async fn calculate_coherence(&self, chunk: &StreamChunk) -> f32 {
        let mut coherence = 0.8;

        // Content coherence analysis
        coherence *= self.analyze_content_coherence(chunk);

        // Context consistency (if available from previous chunks)
        coherence *= self.analyze_context_consistency(chunk).await;

        // Semantic coherence
        coherence *= self.analyze_semantic_coherence(chunk);

        coherence.max(0.0).min(1.0)
    }

    /// Calculate chunk consistency with statistical analysis
    async fn calculate_chunk_consistency(&self, chunk: &StreamChunk) -> f32 {
        let window = self.metrics_window.read().await;

        if window.len() < 2 {
            return 1.0;
        }

        // Calculate variance in chunk characteristics
        let recent_window: Vec<_> = window.iter().rev().take(10).collect();
        let sizes: Vec<usize> = recent_window.iter().map(|_| chunk.content.len()).collect();

        if sizes.is_empty() {
            return 1.0;
        }

        let mean_size = sizes.iter().sum::<usize>() as f32 / sizes.len() as f32;
        let variance = sizes
            .iter()
            .map(|&size| {
                let diff = size as f32 - mean_size;
                diff * diff
            })
            .sum::<f32>()
            / sizes.len() as f32;

        // Convert variance to consistency score
        let consistency = 1.0 / (1.0 + variance / (mean_size * mean_size + 1.0));
        consistency.max(0.0).min(1.0)
    }

    /// Calculate perceptual quality metrics
    async fn calculate_perceptual_quality(
        &self,
        window: &VecDeque<QualityMeasurement>,
    ) -> PerceptualQuality {
        if window.is_empty() {
            return PerceptualQuality::default();
        }

        let count = window.len() as f32;

        PerceptualQuality {
            fluency: window.iter().map(|m| m.smoothness * m.coherence).sum::<f32>() / count,
            engagement: window.iter().map(|m| m.naturalness * 0.9).sum::<f32>() / count,
            clarity: window.iter().map(|m| m.coherence * 0.95).sum::<f32>() / count,
            emotional_tone: window.iter().map(|m| m.naturalness * 0.8).sum::<f32>() / count,
            conversation_flow: window
                .iter()
                .map(|m| (m.smoothness + m.responsiveness) / 2.0)
                .sum::<f32>()
                / count,
            user_experience_score: window
                .iter()
                .map(|m| (m.smoothness + m.naturalness + m.responsiveness) / 3.0)
                .sum::<f32>()
                / count,
            cognitive_load: window.iter().map(|m| (1.0 - m.coherence) * 0.5).sum::<f32>() / count,
            attention_retention: window.iter().map(|m| m.responsiveness * m.coherence).sum::<f32>()
                / count,
            engagement_flow: window
                .iter()
                .map(|m| (m.naturalness + m.responsiveness) / 2.0)
                .sum::<f32>()
                / count,
        }
    }

    /// Calculate statistical analysis of quality metrics
    async fn calculate_statistical_analysis(
        &self,
        window: &VecDeque<QualityMeasurement>,
    ) -> StatisticalAnalysis {
        if window.is_empty() {
            return StatisticalAnalysis::default();
        }

        let smoothness_values: Vec<f32> = window.iter().map(|m| m.smoothness).collect();
        let naturalness_values: Vec<f32> = window.iter().map(|m| m.naturalness).collect();
        let responsiveness_values: Vec<f32> = window.iter().map(|m| m.responsiveness).collect();
        let coherence_values: Vec<f32> = window.iter().map(|m| m.coherence).collect();

        let total_chars: usize = window.iter().map(|m| (m.latency_ms * 10.0) as usize).sum();
        let chunk_count = window.len();
        let avg_size = if chunk_count > 0 { total_chars as f32 / chunk_count as f32 } else { 0.0 };

        StatisticalAnalysis {
            mean_scores: QualityScores {
                smoothness: self.calculate_mean(&smoothness_values),
                naturalness: self.calculate_mean(&naturalness_values),
                responsiveness: self.calculate_mean(&responsiveness_values),
                coherence: self.calculate_mean(&coherence_values),
            },
            std_deviation: QualityScores {
                smoothness: self.calculate_std_dev(&smoothness_values),
                naturalness: self.calculate_std_dev(&naturalness_values),
                responsiveness: self.calculate_std_dev(&responsiveness_values),
                coherence: self.calculate_std_dev(&coherence_values),
            },
            variance: QualityScores {
                smoothness: self.calculate_variance(&smoothness_values),
                naturalness: self.calculate_variance(&naturalness_values),
                responsiveness: self.calculate_variance(&responsiveness_values),
                coherence: self.calculate_variance(&coherence_values),
            },
            percentiles: self.calculate_percentiles(
                &smoothness_values,
                &naturalness_values,
                &responsiveness_values,
                &coherence_values,
            ),
            correlations: self.calculate_correlations(window),
            chunk_count,
            total_characters: total_chars,
            average_chunk_size: avg_size,
            distribution_skew: self.calculate_std_dev(&smoothness_values)
                / (self.calculate_mean(&smoothness_values) + 0.001),
        }
    }

    /// Calculate performance benchmarks
    async fn calculate_performance_benchmarks(
        &self,
        historical: &VecDeque<StreamingQuality>,
    ) -> PerformanceBenchmarks {
        let baselines = self.performance_baselines.read().await;
        let window = self.metrics_window.read().await;

        if let Some(baseline) = baselines.as_ref() {
            if let Some(current) = historical.back() {
                let target_comparison = self.compare_to_baseline(current, baseline);
                let historical_comparison = self.compare_to_historical(current, historical);

                let latency_values: Vec<f32> = window.iter().map(|m| m.latency_ms as f32).collect();
                let p50 = self.calculate_percentile_value(&latency_values, 0.50);
                let p95 = self.calculate_percentile_value(&latency_values, 0.95);
                let p99 = self.calculate_percentile_value(&latency_values, 0.99);

                // Calculate throughput: measurements per second, converted to approximate MB/s
                // Assuming avg chunk size of ~100 bytes per measurement
                let time_window_secs = if window.len() > 1 {
                    // Safe: window.len() > 1 guarantees both back() and front() return Some
                    let back_timestamp = window
                        .back()
                        .expect("window.back() guaranteed by len() > 1 check")
                        .timestamp;
                    let front_timestamp = window
                        .front()
                        .expect("window.front() guaranteed by len() > 1 check")
                        .timestamp;
                    let elapsed = back_timestamp.duration_since(front_timestamp);
                    elapsed.as_secs_f32().max(1.0)
                } else {
                    1.0
                };
                let measurements_per_sec = window.len() as f32 / time_window_secs;
                let throughput_mbps = (measurements_per_sec * 100.0) / 1_000_000.0; // bytes to MB

                // Calculate resource efficiency: inverse of latency normalized by quality
                // Higher quality with lower latency = better efficiency
                let avg_latency = latency_values.iter().sum::<f32>() / latency_values.len() as f32;
                let avg_quality = window.iter().map(|m| m.score).sum::<f32>() / window.len() as f32;
                let resource_efficiency = if avg_latency > 0.0 {
                    (avg_quality * 100.0 / avg_latency).min(1.0).max(0.0)
                } else {
                    avg_quality
                };

                // Calculate scalability factor: consistency of quality across window
                // Lower variance = better scalability
                let quality_variance = {
                    let qualities: Vec<f32> = window.iter().map(|m| m.score).collect();
                    let mean = avg_quality;
                    let variance = qualities.iter().map(|&q| (q - mean).powi(2)).sum::<f32>()
                        / qualities.len() as f32;
                    variance
                };
                let scalability_factor = (1.0 - quality_variance).max(0.0).min(1.0);

                PerformanceBenchmarks {
                    target_comparison,
                    historical_comparison,
                    peer_comparison: None, // Would require external data
                    performance_percentile: self
                        .calculate_performance_percentile(current, historical),
                    latency_percentiles: (p50, p95, p99),
                    throughput_mbps,
                    resource_efficiency,
                    scalability_factor,
                }
            } else {
                PerformanceBenchmarks::default()
            }
        } else {
            PerformanceBenchmarks::default()
        }
    }

    /// Calculate degradation indicators
    async fn calculate_degradation_indicators(
        &self,
        window: &VecDeque<QualityMeasurement>,
        historical: &VecDeque<StreamingQuality>,
    ) -> DegradationIndicators {
        if historical.len() < 10 {
            return DegradationIndicators::default();
        }

        let recent_quality =
            historical.iter().rev().take(5).map(|q| q.overall_quality).sum::<f32>() / 5.0;
        let earlier_quality =
            historical.iter().rev().skip(5).take(5).map(|q| q.overall_quality).sum::<f32>() / 5.0;

        let is_degrading = recent_quality < earlier_quality - 0.05;
        let degradation_rate = if is_degrading {
            (earlier_quality - recent_quality) / 5.0 // Per measurement period
        } else {
            0.0
        };

        let critical_areas = self.identify_critical_areas(window).await;
        let recommended_actions = if is_degrading {
            self.generate_optimization_recommendations().await
        } else {
            Vec::new()
        };

        // Track buffer overflows by detecting when metrics window is full and we're adding more
        let buffer_overflows = if window.len() >= self.window_size {
            // Count measurements where the window is nearly full (above 95% capacity)
            if window.len() as f32 / self.window_size as f32 > 0.95 {
                1
            } else {
                0
            }
        } else {
            0
        };

        // Track recovery events by detecting quality improvements after drops
        // Convert VecDeque to Vec to use windows() method
        let window_vec: Vec<&QualityMeasurement> = window.iter().collect();
        let recovery_events = window_vec
            .windows(2)
            .filter(|pair| {
                // Recovery: quality was below threshold and then improved significantly
                pair[0].score < 0.7 && pair[1].score >= 0.7
            })
            .count();

        DegradationIndicators {
            is_degrading,
            degradation_rate,
            time_to_threshold_breach: self.estimate_time_to_threshold_breach(degradation_rate),
            critical_areas,
            recommended_actions,
            buffer_overflows,
            quality_drops: window.iter().filter(|m| m.score < 0.7).count(),
            recovery_events,
            timing_violations: window.iter().filter(|m| m.latency_ms > 200.0).count(),
        }
    }

    // ================================================================================================
    // UTILITY AND HELPER METHODS
    // ================================================================================================

    fn calculate_trend_direction(&self, recent: f32, earlier: f32) -> TrendDirection {
        let threshold = 0.05;
        if recent > earlier + threshold {
            TrendDirection::Improving
        } else if recent < earlier - threshold {
            TrendDirection::Declining
        } else {
            TrendDirection::Stable
        }
    }

    fn calculate_metric_trend<F>(
        &self,
        recent: &[QualityMeasurement],
        earlier: &[QualityMeasurement],
        extractor: F,
    ) -> TrendDirection
    where
        F: Fn(&QualityMeasurement) -> f32,
    {
        let recent_avg = recent.iter().map(&extractor).sum::<f32>() / recent.len() as f32;
        let earlier_avg = earlier.iter().map(&extractor).sum::<f32>() / earlier.len() as f32;
        self.calculate_trend_direction(recent_avg, earlier_avg)
    }

    fn calculate_timing_variance(&self, window: &VecDeque<QualityMeasurement>) -> f32 {
        if window.len() < 2 {
            return 0.0;
        }

        let latencies: Vec<f64> = window.iter().map(|m| m.latency_ms).collect();
        let mean = latencies.iter().sum::<f64>() / latencies.len() as f64;
        let variance =
            latencies.iter().map(|&l| (l - mean).powi(2)).sum::<f64>() / latencies.len() as f64;

        (variance.sqrt() / mean.max(1.0)) as f32
    }

    fn calculate_length_consistency_factor(&self, chunk: &StreamChunk) -> f32 {
        let length = chunk.content.len();
        if length < 5 {
            0.6
        } else if length > 200 {
            0.8
        } else {
            1.0
        }
    }

    fn analyze_linguistic_patterns(&self, content: &str) -> f32 {
        let mut score: f32 = 1.0;

        // Check for natural hesitation markers
        if content.contains("um") || content.contains("uh") || content.contains("er") {
            score *= 1.1; // These can be natural
        }

        // Check for proper capitalization
        if let Some(first_char) = content.chars().next() {
            if first_char.is_lowercase() && content.len() > 1 {
                score *= 0.9;
            }
        }

        // Check for excessive repetition
        let words: Vec<&str> = content.split_whitespace().collect();
        if words.len() > 1 {
            let mut repeated = 0;
            for i in 1..words.len() {
                if words[i] == words[i - 1] {
                    repeated += 1;
                }
            }
            if repeated > words.len() / 3 {
                score *= 0.7;
            }
        }

        score.max(0.0_f32).min(1.0_f32)
    }

    async fn analyze_content_flow(&self, _chunk: &StreamChunk) -> f32 {
        // Placeholder for sophisticated content flow analysis
        // Would analyze semantic coherence, topic consistency, etc.
        0.9
    }

    fn analyze_punctuation_structure(&self, content: &str) -> f32 {
        let mut score: f32 = 1.0;

        // Check sentence ending
        if content.trim().ends_with(['.', '!', '?']) {
            score *= 1.1;
        }

        // Check for proper comma usage (basic)
        let comma_count = content.matches(',').count();
        let word_count = content.split_whitespace().count();
        if word_count > 10 && comma_count == 0 {
            score *= 0.9; // Long sentences without commas might be unnatural
        }

        score.max(0.0_f32).min(1.0_f32)
    }

    fn analyze_content_coherence(&self, chunk: &StreamChunk) -> f32 {
        let content = &chunk.content.trim();

        if content.is_empty() {
            return 0.0;
        }

        let mut coherence = 0.9;

        // Check for sentence fragments
        if matches!(chunk.chunk_type, ChunkType::Sentence) && !content.ends_with(['.', '!', '?']) {
            coherence *= 0.8;
        }

        // Check for proper word boundaries
        if chunk.content.starts_with(' ') || chunk.content.ends_with(' ') {
            coherence *= 0.95; // Minor penalty for boundary issues
        }

        coherence
    }

    async fn analyze_context_consistency(&self, _chunk: &StreamChunk) -> f32 {
        // Placeholder for context consistency analysis
        // Would check against previous chunks for topic drift, style consistency, etc.
        0.9
    }

    fn analyze_semantic_coherence(&self, _chunk: &StreamChunk) -> f32 {
        // Placeholder for semantic coherence analysis
        // Would use NLP techniques to analyze semantic consistency
        0.9
    }

    fn calculate_mean(&self, values: &[f32]) -> f32 {
        if values.is_empty() {
            0.0
        } else {
            values.iter().sum::<f32>() / values.len() as f32
        }
    }

    fn calculate_std_dev(&self, values: &[f32]) -> f32 {
        if values.len() < 2 {
            return 0.0;
        }

        let mean = self.calculate_mean(values);
        let variance =
            values.iter().map(|&x| (x - mean).powi(2)).sum::<f32>() / values.len() as f32;
        variance.sqrt()
    }

    fn calculate_variance(&self, values: &[f32]) -> f32 {
        self.calculate_std_dev(values).powi(2)
    }

    fn calculate_percentile_value(&self, values: &[f32], percentile: f32) -> f32 {
        if values.is_empty() {
            return 0.0;
        }
        let mut sorted = values.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        let index = ((percentile * (sorted.len() - 1) as f32) as usize).min(sorted.len() - 1);
        sorted[index]
    }

    fn calculate_percentiles(
        &self,
        smoothness: &[f32],
        naturalness: &[f32],
        responsiveness: &[f32],
        coherence: &[f32],
    ) -> QualityPercentiles {
        QualityPercentiles {
            p25: QualityScores {
                smoothness: self.percentile(smoothness, 0.25),
                naturalness: self.percentile(naturalness, 0.25),
                responsiveness: self.percentile(responsiveness, 0.25),
                coherence: self.percentile(coherence, 0.25),
            },
            p50: QualityScores {
                smoothness: self.percentile(smoothness, 0.50),
                naturalness: self.percentile(naturalness, 0.50),
                responsiveness: self.percentile(responsiveness, 0.50),
                coherence: self.percentile(coherence, 0.50),
            },
            p75: QualityScores {
                smoothness: self.percentile(smoothness, 0.75),
                naturalness: self.percentile(naturalness, 0.75),
                responsiveness: self.percentile(responsiveness, 0.75),
                coherence: self.percentile(coherence, 0.75),
            },
            p90: QualityScores {
                smoothness: self.percentile(smoothness, 0.90),
                naturalness: self.percentile(naturalness, 0.90),
                responsiveness: self.percentile(responsiveness, 0.90),
                coherence: self.percentile(coherence, 0.90),
            },
            p95: QualityScores {
                smoothness: self.percentile(smoothness, 0.95),
                naturalness: self.percentile(naturalness, 0.95),
                responsiveness: self.percentile(responsiveness, 0.95),
                coherence: self.percentile(coherence, 0.95),
            },
        }
    }

    fn percentile(&self, values: &[f32], p: f32) -> f32 {
        if values.is_empty() {
            return 0.0;
        }

        let mut sorted = values.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let index = ((sorted.len() - 1) as f32 * p) as usize;
        sorted[index]
    }

    fn calculate_correlations(&self, window: &VecDeque<QualityMeasurement>) -> QualityCorrelations {
        if window.len() < 2 {
            return QualityCorrelations::default();
        }

        let smoothness: Vec<f32> = window.iter().map(|m| m.smoothness).collect();
        let naturalness: Vec<f32> = window.iter().map(|m| m.naturalness).collect();
        let responsiveness: Vec<f32> = window.iter().map(|m| m.responsiveness).collect();
        let coherence: Vec<f32> = window.iter().map(|m| m.coherence).collect();
        let latency: Vec<f32> = window.iter().map(|m| m.latency_ms as f32).collect();
        let consistency: Vec<f32> = window.iter().map(|m| m.chunk_consistency).collect();

        QualityCorrelations {
            smoothness_naturalness: self.correlation(&smoothness, &naturalness),
            responsiveness_coherence: self.correlation(&responsiveness, &coherence),
            latency_quality: -self.correlation(&latency, &smoothness), // Negative correlation expected
            consistency_smoothness: self.correlation(&consistency, &smoothness),
        }
    }

    fn correlation(&self, x: &[f32], y: &[f32]) -> f32 {
        if x.len() != y.len() || x.len() < 2 {
            return 0.0;
        }

        let mean_x = self.calculate_mean(x);
        let mean_y = self.calculate_mean(y);

        let numerator: f32 =
            x.iter().zip(y.iter()).map(|(&xi, &yi)| (xi - mean_x) * (yi - mean_y)).sum();
        let sum_sq_x: f32 = x.iter().map(|&xi| (xi - mean_x).powi(2)).sum();
        let sum_sq_y: f32 = y.iter().map(|&yi| (yi - mean_y).powi(2)).sum();

        let denominator = (sum_sq_x * sum_sq_y).sqrt();
        if denominator == 0.0 {
            0.0
        } else {
            numerator / denominator
        }
    }

    fn compare_to_baseline(
        &self,
        current: &StreamingQuality,
        baseline: &StreamingQuality,
    ) -> BenchmarkComparison {
        let relative_performance = (current.overall_quality - baseline.overall_quality)
            / baseline.overall_quality.max(0.1);

        BenchmarkComparison {
            relative_performance: relative_performance.max(-1.0).min(1.0),
            improvement_potential: (1.0 - current.overall_quality).max(0.0),
            confidence_level: 0.8, // Static for now, could be dynamic
        }
    }

    fn compare_to_historical(
        &self,
        current: &StreamingQuality,
        historical: &VecDeque<StreamingQuality>,
    ) -> BenchmarkComparison {
        if historical.len() < 5 {
            return BenchmarkComparison::default();
        }

        let historical_avg =
            historical.iter().map(|q| q.overall_quality).sum::<f32>() / historical.len() as f32;
        let relative_performance =
            (current.overall_quality - historical_avg) / historical_avg.max(0.1);

        BenchmarkComparison {
            relative_performance: relative_performance.max(-1.0).min(1.0),
            improvement_potential: (1.0 - current.overall_quality).max(0.0),
            confidence_level: 0.9,
        }
    }

    fn calculate_performance_percentile(
        &self,
        current: &StreamingQuality,
        historical: &VecDeque<StreamingQuality>,
    ) -> f32 {
        if historical.is_empty() {
            return 0.5;
        }

        let better_count = historical
            .iter()
            .filter(|q| q.overall_quality < current.overall_quality)
            .count();
        better_count as f32 / historical.len() as f32
    }

    async fn identify_critical_areas(
        &self,
        window: &VecDeque<QualityMeasurement>,
    ) -> Vec<QualityArea> {
        let mut critical_areas = Vec::new();

        if let Some(latest) = window.back() {
            if latest.smoothness < self.thresholds.min_smoothness {
                critical_areas.push(QualityArea::Smoothness);
            }
            if latest.naturalness < self.thresholds.min_naturalness {
                critical_areas.push(QualityArea::Naturalness);
            }
            if latest.responsiveness < self.thresholds.min_responsiveness {
                critical_areas.push(QualityArea::Responsiveness);
            }
            if latest.coherence < self.thresholds.min_coherence {
                critical_areas.push(QualityArea::Coherence);
            }
            if latest.chunk_consistency < 0.7 {
                critical_areas.push(QualityArea::Consistency);
            }
        }

        critical_areas
    }

    fn estimate_time_to_threshold_breach(&self, degradation_rate: f32) -> Option<Duration> {
        if degradation_rate <= 0.0 {
            return None;
        }

        // Estimate based on current degradation rate
        let time_periods = (self.thresholds.min_overall_quality / degradation_rate) as u64;
        Some(Duration::from_secs(time_periods * 60)) // Assuming 1-minute periods
    }
}

// ================================================================================================
// DEFAULT IMPLEMENTATIONS
// ================================================================================================

impl Default for PerceptualQuality {
    fn default() -> Self {
        Self {
            fluency: 0.8,
            engagement: 0.8,
            clarity: 0.8,
            emotional_tone: 0.8,
            conversation_flow: 0.8,
            user_experience_score: 0.8,
            cognitive_load: 0.3,
            attention_retention: 0.8,
            engagement_flow: 0.8,
        }
    }
}

impl Default for StatisticalAnalysis {
    fn default() -> Self {
        Self {
            mean_scores: QualityScores::default(),
            std_deviation: QualityScores::default(),
            variance: QualityScores::default(),
            percentiles: QualityPercentiles::default(),
            correlations: QualityCorrelations::default(),
            chunk_count: 0,
            total_characters: 0,
            average_chunk_size: 0.0,
            distribution_skew: 0.0,
        }
    }
}

impl Default for QualityScores {
    fn default() -> Self {
        Self {
            smoothness: 0.8,
            naturalness: 0.8,
            responsiveness: 0.8,
            coherence: 0.8,
        }
    }
}

impl Default for QualityCorrelations {
    fn default() -> Self {
        Self {
            smoothness_naturalness: 0.0,
            responsiveness_coherence: 0.0,
            latency_quality: 0.0,
            consistency_smoothness: 0.0,
        }
    }
}

impl Default for PerformanceBenchmarks {
    fn default() -> Self {
        Self {
            target_comparison: BenchmarkComparison::default(),
            historical_comparison: BenchmarkComparison::default(),
            peer_comparison: None,
            performance_percentile: 0.5,
            latency_percentiles: (100.0, 200.0, 300.0),
            throughput_mbps: 1.0,
            resource_efficiency: 0.8,
            scalability_factor: 1.0,
        }
    }
}

impl Default for BenchmarkComparison {
    fn default() -> Self {
        Self {
            relative_performance: 0.0,
            improvement_potential: 0.2,
            confidence_level: 0.5,
        }
    }
}

impl Default for DegradationIndicators {
    fn default() -> Self {
        Self {
            is_degrading: false,
            degradation_rate: 0.0,
            time_to_threshold_breach: None,
            critical_areas: Vec::new(),
            recommended_actions: Vec::new(),
            buffer_overflows: 0,
            quality_drops: 0,
            recovery_events: 0,
            timing_violations: 0,
        }
    }
}

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

// ================================================================================================
// QUALITY ANALYSIS TRAIT
// ================================================================================================

/// Trait for quality analysis functionality
#[async_trait]
pub trait QualityAnalysis {
    /// Analyze the quality of a stream chunk
    async fn analyze_quality(
        &self,
        chunk: &StreamChunk,
        delivery_time: Duration,
    ) -> QualityMeasurement;

    /// Get overall streaming quality assessment
    async fn get_overall_quality(&self) -> StreamingQuality;

    /// Check if current quality meets defined thresholds
    async fn meets_thresholds(&self) -> bool;

    /// Get quality trends and predictions
    async fn get_trends(&self) -> QualityTrends;

    /// Generate actionable optimization recommendations
    async fn get_recommendations(&self) -> Vec<OptimizationRecommendation>;
}

#[async_trait]
impl QualityAnalysis for QualityAnalyzer {
    async fn analyze_quality(
        &self,
        chunk: &StreamChunk,
        delivery_time: Duration,
    ) -> QualityMeasurement {
        self.analyze_chunk_quality(chunk, delivery_time).await
    }

    async fn get_overall_quality(&self) -> StreamingQuality {
        self.calculate_overall_quality().await
    }

    async fn meets_thresholds(&self) -> bool {
        self.meets_quality_thresholds().await
    }

    async fn get_trends(&self) -> QualityTrends {
        self.get_quality_trends().await
    }

    async fn get_recommendations(&self) -> Vec<OptimizationRecommendation> {
        self.generate_optimization_recommendations().await
    }
}

// ================================================================================================
// TESTS
// ================================================================================================

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

    fn make_chunk(content: &str, complexity: f32) -> StreamChunk {
        StreamChunk {
            content: content.to_string(),
            index: 0,
            chunk_type: ChunkType::Content,
            timing: ChunkTiming::default(),
            metadata: ChunkMetadata::with_complexity(complexity),
        }
    }

    // --- StreamingQuality tests ---

    #[test]
    fn test_streaming_quality_default_values_in_range() {
        let quality = StreamingQuality::default();
        assert!(
            quality.smoothness >= 0.0 && quality.smoothness <= 1.0,
            "smoothness must be in [0.0, 1.0]"
        );
        assert!(
            quality.naturalness >= 0.0 && quality.naturalness <= 1.0,
            "naturalness must be in [0.0, 1.0]"
        );
        assert!(
            quality.responsiveness >= 0.0 && quality.responsiveness <= 1.0,
            "responsiveness must be in [0.0, 1.0]"
        );
        assert!(
            quality.coherence >= 0.0 && quality.coherence <= 1.0,
            "coherence must be in [0.0, 1.0]"
        );
        assert!(
            quality.overall_quality >= 0.0 && quality.overall_quality <= 1.0,
            "overall_quality must be in [0.0, 1.0]"
        );
    }

    #[test]
    fn test_streaming_quality_default_chunk_consistency_in_range() {
        let quality = StreamingQuality::default();
        assert!(quality.chunk_consistency >= 0.0 && quality.chunk_consistency <= 1.0);
        assert!(quality.flow_smoothness >= 0.0 && quality.flow_smoothness <= 1.0);
        assert!(quality.timing_accuracy >= 0.0 && quality.timing_accuracy <= 1.0);
        assert!(quality.buffer_efficiency >= 0.0 && quality.buffer_efficiency <= 1.0);
    }

    // --- QualityThresholds tests ---

    #[test]
    fn test_quality_thresholds_default_min_overall_quality_in_range() {
        let thresholds = QualityThresholds::default();
        assert!(
            thresholds.min_overall_quality >= 0.0 && thresholds.min_overall_quality <= 1.0,
            "min_overall_quality must be in [0.0, 1.0]"
        );
    }

    #[test]
    fn test_quality_thresholds_minimum_acceptable_less_than_target() {
        let thresholds = QualityThresholds::default();
        assert!(
            thresholds.minimum_acceptable <= thresholds.target_quality,
            "minimum_acceptable ({}) should be <= target_quality ({})",
            thresholds.minimum_acceptable,
            thresholds.target_quality
        );
    }

    #[test]
    fn test_quality_thresholds_target_less_than_excellent() {
        let thresholds = QualityThresholds::default();
        assert!(
            thresholds.target_quality <= thresholds.excellent_threshold,
            "target_quality ({}) should be <= excellent_threshold ({})",
            thresholds.target_quality,
            thresholds.excellent_threshold
        );
    }

    #[test]
    fn test_quality_thresholds_max_latency_positive() {
        let thresholds = QualityThresholds::default();
        assert!(
            thresholds.max_latency_ms > 0.0,
            "max_latency_ms should be positive, got {}",
            thresholds.max_latency_ms
        );
    }

    // --- QualityAnalyzer tests ---

    #[test]
    fn test_quality_analyzer_new() {
        let analyzer = QualityAnalyzer::new();
        assert_eq!(
            analyzer.window_size(),
            100,
            "default window size should be 100"
        );
    }

    #[test]
    fn test_quality_analyzer_default() {
        let analyzer = QualityAnalyzer::default();
        assert_eq!(analyzer.window_size(), 100);
    }

    #[tokio::test]
    async fn test_quality_analyzer_analyze_chunk_quality_returns_measurement() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Hello world, this is a test sentence.", 0.5);
        let delivery_time = Duration::from_millis(80);
        let measurement = analyzer.analyze_chunk_quality(&chunk, delivery_time).await;
        assert!(
            measurement.smoothness >= 0.0 && measurement.smoothness <= 1.0,
            "smoothness must be in [0.0, 1.0]"
        );
        assert!(
            measurement.naturalness >= 0.0 && measurement.naturalness <= 1.0,
            "naturalness must be in [0.0, 1.0]"
        );
        assert!(
            measurement.responsiveness >= 0.0 && measurement.responsiveness <= 1.0,
            "responsiveness must be in [0.0, 1.0]"
        );
        assert!(
            measurement.coherence >= 0.0 && measurement.coherence <= 1.0,
            "coherence must be in [0.0, 1.0]"
        );
    }

    #[tokio::test]
    async fn test_quality_analyzer_score_normalized() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Test content for score normalization check.", 0.4);
        let delivery_time = Duration::from_millis(50);
        let measurement = analyzer.analyze_chunk_quality(&chunk, delivery_time).await;
        assert!(
            measurement.score >= 0.0 && measurement.score <= 1.0,
            "overall score must be normalized in [0.0, 1.0], got {}",
            measurement.score
        );
    }

    #[tokio::test]
    async fn test_quality_analyzer_high_latency_lowers_responsiveness() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Test content for latency measurement.", 0.5);
        let fast_delivery = Duration::from_millis(50);
        let slow_delivery = Duration::from_millis(500);
        let fast_measurement = analyzer.analyze_chunk_quality(&chunk, fast_delivery).await;
        let slow_measurement = analyzer.analyze_chunk_quality(&chunk, slow_delivery).await;
        assert!(
            fast_measurement.responsiveness >= slow_measurement.responsiveness,
            "faster delivery should produce >= responsiveness score: {} >= {}",
            fast_measurement.responsiveness,
            slow_measurement.responsiveness
        );
    }

    #[tokio::test]
    async fn test_quality_analyzer_calculate_overall_quality_bounded() {
        let analyzer = QualityAnalyzer::new();
        // Populate with some measurements
        let chunk = make_chunk("Some streaming content for quality check.", 0.5);
        for _ in 0..5 {
            analyzer.analyze_chunk_quality(&chunk, Duration::from_millis(100)).await;
        }
        let quality = analyzer.calculate_overall_quality().await;
        assert!(
            quality.overall_quality >= 0.0 && quality.overall_quality <= 1.0,
            "overall_quality must be in [0.0, 1.0]"
        );
        assert!(quality.smoothness >= 0.0 && quality.smoothness <= 1.0);
    }

    #[tokio::test]
    async fn test_quality_analyzer_meets_quality_thresholds_initially() {
        let analyzer = QualityAnalyzer::new();
        // Empty window - should meet thresholds with default quality
        let meets = analyzer.meets_quality_thresholds().await;
        // No strict assertion on value - just verify no panic
        let _ = meets;
    }

    #[tokio::test]
    async fn test_quality_analyzer_quality_trends_stable_initially() {
        let analyzer = QualityAnalyzer::new();
        let trends = analyzer.get_quality_trends().await;
        // Without measurements, overall trend should be Stable
        assert_eq!(
            std::mem::discriminant(&trends.overall_trend),
            std::mem::discriminant(&TrendDirection::Stable),
            "initial trend should be Stable"
        );
    }

    #[tokio::test]
    async fn test_quality_analyzer_get_optimization_recommendations() {
        let analyzer = QualityAnalyzer::new();
        let recommendations = analyzer.generate_optimization_recommendations().await;
        // Should return a Vec (possibly empty) without panicking
        let _ = recommendations.len();
    }

    #[tokio::test]
    async fn test_quality_analyzer_accumulates_window() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Accumulate measurements in the quality window", 0.5);
        for i in 0..10 {
            let delivery_time = Duration::from_millis(50 + i * 10);
            analyzer.analyze_chunk_quality(&chunk, delivery_time).await;
        }
        let window = analyzer.metrics_window().read().await;
        assert_eq!(
            window.len(),
            10,
            "window should contain exactly 10 measurements"
        );
    }

    #[tokio::test]
    async fn test_quality_analyzer_window_respects_capacity() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Testing window capacity limit", 0.5);
        // Push more than window_size (100) measurements
        for i in 0..150u64 {
            let delivery_time = Duration::from_millis(50 + i % 100);
            analyzer.analyze_chunk_quality(&chunk, delivery_time).await;
        }
        let window = analyzer.metrics_window().read().await;
        assert!(
            window.len() <= analyzer.window_size(),
            "window should not exceed capacity: {} <= {}",
            window.len(),
            analyzer.window_size()
        );
    }

    // --- PerceptualQuality tests ---

    #[test]
    fn test_perceptual_quality_default_values_in_range() {
        let pq = PerceptualQuality::default();
        assert!(pq.fluency >= 0.0 && pq.fluency <= 1.0);
        assert!(pq.engagement >= 0.0 && pq.engagement <= 1.0);
        assert!(pq.clarity >= 0.0 && pq.clarity <= 1.0);
        assert!(pq.user_experience_score >= 0.0 && pq.user_experience_score <= 1.0);
        assert!(pq.cognitive_load >= 0.0 && pq.cognitive_load <= 1.0);
    }

    // --- StatisticalAnalysis tests ---

    #[test]
    fn test_statistical_analysis_default_chunk_count_zero() {
        let stats = StatisticalAnalysis::default();
        assert_eq!(stats.chunk_count, 0);
        assert_eq!(stats.total_characters, 0);
    }

    // --- DegradationIndicators tests ---

    #[test]
    fn test_degradation_indicators_default_not_degrading() {
        let indicators = DegradationIndicators::default();
        assert!(!indicators.is_degrading, "default should not be degrading");
        assert_eq!(indicators.degradation_rate, 0.0);
        assert!(indicators.time_to_threshold_breach.is_none());
    }

    // --- Quality trait delegation tests ---

    #[tokio::test]
    async fn test_quality_analysis_trait_analyze_quality() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Trait delegation test content", 0.5);
        let measurement = analyzer.analyze_quality(&chunk, Duration::from_millis(75)).await;
        assert!(measurement.score >= 0.0 && measurement.score <= 1.0);
    }

    #[tokio::test]
    async fn test_quality_analysis_trait_get_overall_quality() {
        let analyzer = QualityAnalyzer::new();
        let quality = analyzer.get_overall_quality().await;
        assert!(quality.overall_quality >= 0.0 && quality.overall_quality <= 1.0);
    }

    #[tokio::test]
    async fn test_quality_analysis_trait_meets_thresholds() {
        let analyzer = QualityAnalyzer::new();
        let result = analyzer.meets_thresholds().await;
        let _ = result; // no panic
    }

    #[tokio::test]
    async fn test_quality_analysis_trait_get_trends() {
        let analyzer = QualityAnalyzer::new();
        let trends = analyzer.get_trends().await;
        let _ = trends; // no panic, verify all sub-trends accessible
    }

    #[tokio::test]
    async fn test_quality_analysis_trait_get_recommendations() {
        let analyzer = QualityAnalyzer::new();
        let recs = analyzer.get_recommendations().await;
        let _ = recs.len();
    }

    // --- Score normalization edge cases ---

    #[tokio::test]
    async fn test_quality_score_very_slow_delivery_still_bounded() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Edge case: extremely slow delivery", 0.9);
        // 10 second delivery
        let measurement = analyzer.analyze_chunk_quality(&chunk, Duration::from_secs(10)).await;
        assert!(
            measurement.responsiveness >= 0.0 && measurement.responsiveness <= 1.0,
            "responsiveness must stay in [0.0, 1.0] even with very slow delivery"
        );
        assert!(
            measurement.score >= 0.0 && measurement.score <= 1.0,
            "overall score must stay in [0.0, 1.0] even with very slow delivery"
        );
    }

    #[tokio::test]
    async fn test_quality_score_instant_delivery_bounded() {
        let analyzer = QualityAnalyzer::new();
        let chunk = make_chunk("Edge case: instant delivery", 0.1);
        let measurement = analyzer.analyze_chunk_quality(&chunk, Duration::from_millis(1)).await;
        assert!(
            measurement.responsiveness >= 0.0 && measurement.responsiveness <= 1.0,
            "responsiveness must be in [0.0, 1.0] for instant delivery"
        );
    }
}