oxirs-vec 0.2.4

Vector index abstractions for semantic similarity and AI-augmented querying
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
//! Adaptive compression techniques for vector data
//!
//! This module provides intelligent compression strategies that adapt to data characteristics,
//! optimizing compression ratio and decompression speed based on vector patterns and usage.

use crate::{
    compression::{create_compressor, CompressionMethod, VectorCompressor},
    Vector, VectorError,
};
use anyhow::Result;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

// Random functionality now provided by scirs2-core

/// Context information for compression decisions
#[derive(Debug, Clone)]
pub struct CompressionContext {
    pub domain: VectorDomain,
    pub access_frequency: AccessFrequency,
    pub quality_requirement: QualityRequirement,
    pub resource_constraints: ResourceConstraints,
    pub temporal_patterns: TemporalPatterns,
}

/// Vector domain types for domain-specific optimization
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum VectorDomain {
    TextEmbeddings,
    ImageFeatures,
    AudioFeatures,
    KnowledgeGraph,
    TimeSeriesData,
    Unknown,
}

/// Access frequency patterns
#[derive(Debug, Clone)]
pub enum AccessFrequency {
    VeryHigh, // Accessed multiple times per second
    High,     // Accessed multiple times per minute
    Moderate, // Accessed multiple times per hour
    Low,      // Accessed daily
    Archive,  // Rarely accessed
}

/// Quality requirements for different use cases
#[derive(Debug, Clone)]
pub enum QualityRequirement {
    Lossless,    // No quality loss acceptable
    HighQuality, // Minimal quality loss (>99% accuracy)
    Balanced,    // Moderate quality loss (>95% accuracy)
    Compressed,  // Higher compression priority (>90% accuracy)
    Aggressive,  // Maximum compression (<90% accuracy)
}

/// Resource constraints for compression decisions
#[derive(Debug, Clone)]
pub struct ResourceConstraints {
    pub cpu_usage_limit: f32,    // 0.0 to 1.0
    pub memory_usage_limit: f32, // 0.0 to 1.0
    pub compression_time_limit: Duration,
    pub decompression_time_limit: Duration,
}

/// Temporal patterns for time-aware compression
#[derive(Debug, Clone)]
pub struct TemporalPatterns {
    pub time_of_day_factor: f32, // Compression aggressiveness based on time
    pub load_factor: f32,        // Current system load
    pub seasonal_factor: f32,    // Long-term usage patterns
}

/// Enhanced statistics about vector data characteristics
#[derive(Debug, Clone)]
pub struct VectorStats {
    pub dimensions: usize,
    pub mean: f32,
    pub std_dev: f32,
    pub min_val: f32,
    pub max_val: f32,
    pub entropy: f32,
    pub sparsity: f32,                 // Fraction of near-zero values
    pub correlation: f32,              // Average correlation between dimensions
    pub intrinsic_dimension: f32,      // Estimated intrinsic dimensionality
    pub clustering_tendency: f32,      // Hopkins statistic
    pub temporal_stability: f32,       // Stability over time
    pub domain_affinity: VectorDomain, // Detected domain type
}

impl Default for CompressionContext {
    fn default() -> Self {
        Self {
            domain: VectorDomain::Unknown,
            access_frequency: AccessFrequency::Moderate,
            quality_requirement: QualityRequirement::Balanced,
            resource_constraints: ResourceConstraints {
                cpu_usage_limit: 0.7,
                memory_usage_limit: 0.8,
                compression_time_limit: Duration::from_millis(100),
                decompression_time_limit: Duration::from_millis(50),
            },
            temporal_patterns: TemporalPatterns {
                time_of_day_factor: 1.0,
                load_factor: 1.0,
                seasonal_factor: 1.0,
            },
        }
    }
}

impl VectorStats {
    /// Calculate enhanced statistics for a vector with context
    pub fn from_vector(vector: &Vector) -> Result<Self, VectorError> {
        Self::from_vector_with_context(vector, &CompressionContext::default())
    }

    /// Calculate statistics for a vector with compression context
    pub fn from_vector_with_context(
        vector: &Vector,
        context: &CompressionContext,
    ) -> Result<Self, VectorError> {
        let values = vector.as_f32();
        let n = values.len();

        if n == 0 {
            return Err(VectorError::InvalidDimensions("Empty vector".to_string()));
        }

        // Basic statistics
        let sum: f32 = values.iter().sum();
        let mean = sum / n as f32;

        let variance: f32 = values.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / n as f32;
        let std_dev = variance.sqrt();

        let min_val = values.iter().fold(f32::INFINITY, |a, &b| a.min(b));
        let max_val = values.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

        // Enhanced entropy estimation with domain-specific bins
        let bin_count = match context.domain {
            VectorDomain::TextEmbeddings => 128,
            VectorDomain::ImageFeatures => 256,
            VectorDomain::KnowledgeGraph => 64,
            _ => 256,
        };

        let mut histogram = vec![0u32; bin_count];
        let range = max_val - min_val;
        if range > 0.0 {
            for val in &values {
                let bucket = ((val - min_val) / range * (bin_count - 1) as f32)
                    .clamp(0.0, (bin_count - 1) as f32) as usize;
                histogram[bucket] += 1;
            }
        }

        let entropy = histogram
            .iter()
            .filter(|&&count| count > 0)
            .map(|&count| {
                let p = count as f32 / n as f32;
                -p * p.log2()
            })
            .sum();

        // Sparsity (fraction of values near zero)
        let threshold = std_dev * 0.1;
        let sparse_count = values.iter().filter(|&&x| x.abs() < threshold).count();
        let sparsity = sparse_count as f32 / n as f32;

        // Enhanced correlation analysis
        let correlation = Self::calculate_enhanced_correlation(&values);

        // Intrinsic dimensionality estimation using correlation dimension
        let intrinsic_dimension = Self::estimate_intrinsic_dimension(&values);

        // Clustering tendency using Hopkins statistic
        let clustering_tendency = Self::calculate_hopkins_statistic(&values);

        // Temporal stability (placeholder for now)
        let temporal_stability = 1.0;

        // Domain detection based on statistical patterns
        let domain_affinity = Self::detect_domain(&values, entropy, sparsity, correlation);

        Ok(VectorStats {
            dimensions: n,
            mean,
            std_dev,
            min_val,
            max_val,
            entropy,
            sparsity,
            correlation,
            intrinsic_dimension,
            clustering_tendency,
            temporal_stability,
            domain_affinity,
        })
    }

    /// Enhanced correlation analysis with multiple window sizes
    fn calculate_enhanced_correlation(values: &[f32]) -> f32 {
        let n = values.len();
        if n <= 1 {
            return 0.0;
        }

        let window_sizes = [5, 10, 20].iter().map(|&w| w.min(n / 2).max(2));
        let mut total_corr = 0.0;
        let mut total_count = 0;

        for window_size in window_sizes {
            if window_size >= n {
                continue;
            }

            for i in 0..(n - window_size) {
                let window1 = &values[i..i + window_size];
                let window2 = &values[i + 1..i + window_size + 1];

                let mean1: f32 = window1.iter().sum::<f32>() / window_size as f32;
                let mean2: f32 = window2.iter().sum::<f32>() / window_size as f32;

                let covariance: f32 = window1
                    .iter()
                    .zip(window2)
                    .map(|(a, b)| (a - mean1) * (b - mean2))
                    .sum();
                let var1: f32 = window1.iter().map(|x| (x - mean1).powi(2)).sum();
                let var2: f32 = window2.iter().map(|x| (x - mean2).powi(2)).sum();

                if var1 > 0.0 && var2 > 0.0 {
                    let corr = covariance / (var1.sqrt() * var2.sqrt());
                    total_corr += corr.abs();
                    total_count += 1;
                }
            }
        }

        if total_count > 0 {
            total_corr / total_count as f32
        } else {
            0.0
        }
    }

    /// Estimate intrinsic dimensionality using correlation dimension method
    fn estimate_intrinsic_dimension(values: &[f32]) -> f32 {
        let n = values.len();
        if n < 10 {
            return n as f32;
        }

        // Sample points for correlation dimension calculation
        let sample_size = n.min(100);
        let step = n / sample_size;
        let sampled: Vec<f32> = (0..sample_size).map(|i| values[i * step]).collect();

        // Calculate correlation dimension with multiple radii
        let mut log_radii = Vec::new();
        let mut log_counts = Vec::new();

        let max_val = sampled.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
        let min_val = sampled.iter().fold(f32::INFINITY, |a, &b| a.min(b));
        let range = max_val - min_val;

        if range <= 0.0 {
            return 1.0;
        }

        for radius_factor in [0.001, 0.01, 0.1, 0.5] {
            let radius = range * radius_factor;
            let mut count = 0;

            for i in 0..sampled.len() {
                for j in (i + 1)..sampled.len() {
                    if (sampled[i] - sampled[j]).abs() < radius {
                        count += 1;
                    }
                }
            }

            if count > 0 {
                log_radii.push(radius.ln());
                log_counts.push((count as f32).ln());
            }
        }

        // Linear regression to estimate dimension
        if log_radii.len() < 2 {
            return n as f32;
        }

        let mean_log_r: f32 = log_radii.iter().sum::<f32>() / log_radii.len() as f32;
        let mean_log_c: f32 = log_counts.iter().sum::<f32>() / log_counts.len() as f32;

        let numerator: f32 = log_radii
            .iter()
            .zip(&log_counts)
            .map(|(r, c)| (r - mean_log_r) * (c - mean_log_c))
            .sum();
        let denominator: f32 = log_radii.iter().map(|r| (r - mean_log_r).powi(2)).sum();

        if denominator > 0.0 {
            let slope = numerator / denominator;
            slope.abs().min(n as f32).max(1.0)
        } else {
            n as f32
        }
    }

    /// Calculate Hopkins statistic for clustering tendency
    fn calculate_hopkins_statistic(values: &[f32]) -> f32 {
        let n = values.len();
        if n < 10 {
            return 0.5; // Neutral value
        }

        let sample_size = (n / 10).clamp(5, 50);
        let min_val = values.iter().fold(f32::INFINITY, |a, &b| a.min(b));
        let max_val = values.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));

        if max_val <= min_val {
            return 0.5;
        }

        let mut w_sum = 0.0; // Sum of distances to nearest neighbor in data
        let mut u_sum = 0.0; // Sum of distances to nearest neighbor in uniform random data

        // Sample from actual data
        for i in 0..sample_size {
            let idx = (i * n / sample_size) % n;
            let point = values[idx];

            let mut min_dist = f32::INFINITY;
            for &other in values {
                if other != point {
                    let dist = (point - other).abs();
                    min_dist = min_dist.min(dist);
                }
            }
            w_sum += min_dist;
        }

        // Generate uniform random points and find nearest neighbors in data
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        42u64.hash(&mut hasher);
        let mut rng_state = hasher.finish();

        for _ in 0..sample_size {
            rng_state = rng_state.wrapping_mul(1103515245).wrapping_add(12345);
            let random_point = min_val + (max_val - min_val) * (rng_state as f32 / u64::MAX as f32);

            let mut min_dist = f32::INFINITY;
            for &data_point in values {
                let dist = (random_point - data_point).abs();
                min_dist = min_dist.min(dist);
            }
            u_sum += min_dist;
        }

        if w_sum + u_sum > 0.0 {
            u_sum / (w_sum + u_sum)
        } else {
            0.5
        }
    }

    /// Detect vector domain based on statistical patterns
    fn detect_domain(
        _values: &[f32],
        entropy: f32,
        sparsity: f32,
        correlation: f32,
    ) -> VectorDomain {
        // Text embeddings: moderate entropy, low sparsity, moderate correlation
        if entropy > 6.0
            && entropy < 8.0
            && sparsity < 0.3
            && correlation > 0.2
            && correlation < 0.6
        {
            return VectorDomain::TextEmbeddings;
        }

        // Image features: high entropy, variable sparsity, low correlation
        if entropy > 7.0 && correlation < 0.3 {
            return VectorDomain::ImageFeatures;
        }

        // Knowledge graph: lower entropy, higher sparsity, specific patterns
        if entropy < 6.0 && sparsity > 0.4 {
            return VectorDomain::KnowledgeGraph;
        }

        // Time series: high correlation, moderate entropy
        if correlation > 0.7 && entropy > 5.0 && entropy < 7.0 {
            return VectorDomain::TimeSeriesData;
        }

        VectorDomain::Unknown
    }

    /// Calculate aggregate statistics from multiple vectors
    pub fn from_vectors(vectors: &[Vector]) -> Result<Self, VectorError> {
        Self::from_vectors_with_context(vectors, &CompressionContext::default())
    }

    /// Calculate aggregate statistics from multiple vectors with context
    pub fn from_vectors_with_context(
        vectors: &[Vector],
        context: &CompressionContext,
    ) -> Result<Self, VectorError> {
        if vectors.is_empty() {
            return Err(VectorError::InvalidDimensions(
                "No vectors provided".to_string(),
            ));
        }

        let individual_stats: Result<Vec<_>, _> = vectors
            .iter()
            .map(|v| Self::from_vector_with_context(v, context))
            .collect();
        let stats = individual_stats?;

        let n = stats.len() as f32;

        Ok(VectorStats {
            dimensions: stats[0].dimensions,
            mean: stats.iter().map(|s| s.mean).sum::<f32>() / n,
            std_dev: stats.iter().map(|s| s.std_dev).sum::<f32>() / n,
            min_val: stats
                .iter()
                .map(|s| s.min_val)
                .fold(f32::INFINITY, |a, b| a.min(b)),
            max_val: stats
                .iter()
                .map(|s| s.max_val)
                .fold(f32::NEG_INFINITY, |a, b| a.max(b)),
            entropy: stats.iter().map(|s| s.entropy).sum::<f32>() / n,
            sparsity: stats.iter().map(|s| s.sparsity).sum::<f32>() / n,
            correlation: stats.iter().map(|s| s.correlation).sum::<f32>() / n,
            intrinsic_dimension: stats.iter().map(|s| s.intrinsic_dimension).sum::<f32>() / n,
            clustering_tendency: stats.iter().map(|s| s.clustering_tendency).sum::<f32>() / n,
            temporal_stability: stats.iter().map(|s| s.temporal_stability).sum::<f32>() / n,
            domain_affinity: Self::aggregate_domain_affinity(&stats),
        })
    }

    /// Aggregate domain affinity from multiple statistics
    fn aggregate_domain_affinity(stats: &[VectorStats]) -> VectorDomain {
        let mut domain_counts = HashMap::new();

        for stat in stats {
            *domain_counts
                .entry(stat.domain_affinity.clone())
                .or_insert(0) += 1;
        }

        domain_counts
            .into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(domain, _)| domain)
            .unwrap_or(VectorDomain::Unknown)
    }
}

/// Performance metrics for compression methods
#[derive(Debug, Clone)]
pub struct CompressionMetrics {
    pub method: CompressionMethod,
    pub compression_ratio: f32,
    pub compression_time: Duration,
    pub decompression_time: Duration,
    pub reconstruction_error: f32,
    pub usage_count: u64,
    pub avg_performance_score: f32,
}

impl CompressionMetrics {
    pub fn new(method: CompressionMethod) -> Self {
        Self {
            method,
            compression_ratio: 1.0,
            compression_time: Duration::ZERO,
            decompression_time: Duration::ZERO,
            reconstruction_error: 0.0,
            usage_count: 0,
            avg_performance_score: 0.0,
        }
    }

    /// Calculate performance score (higher is better)
    pub fn calculate_score(&self, priorities: &CompressionPriorities) -> f32 {
        let ratio_score = self.compression_ratio.min(0.9); // Cap at 90% compression
        let speed_score = 1.0 / (1.0 + self.compression_time.as_millis() as f32 / 1000.0);
        let accuracy_score = 1.0 / (1.0 + self.reconstruction_error);

        priorities.compression_weight * ratio_score
            + priorities.speed_weight * speed_score
            + priorities.accuracy_weight * accuracy_score
    }

    /// Update metrics with new measurement
    pub fn update(
        &mut self,
        compression_ratio: f32,
        comp_time: Duration,
        decomp_time: Duration,
        error: f32,
        priorities: &CompressionPriorities,
    ) {
        let alpha = 0.1; // Learning rate for exponential moving average

        self.compression_ratio = self.compression_ratio * (1.0 - alpha) + compression_ratio * alpha;
        self.compression_time = Duration::from_nanos(
            (self.compression_time.as_nanos() as f32 * (1.0 - alpha)
                + comp_time.as_nanos() as f32 * alpha) as u64,
        );
        self.decompression_time = Duration::from_nanos(
            (self.decompression_time.as_nanos() as f32 * (1.0 - alpha)
                + decomp_time.as_nanos() as f32 * alpha) as u64,
        );
        self.reconstruction_error = self.reconstruction_error * (1.0 - alpha) + error * alpha;
        self.usage_count += 1;

        self.avg_performance_score = self.calculate_score(priorities);
    }
}

/// Priorities for compression strategy selection
#[derive(Debug, Clone)]
pub struct CompressionPriorities {
    pub compression_weight: f32, // Importance of compression ratio
    pub speed_weight: f32,       // Importance of compression/decompression speed
    pub accuracy_weight: f32,    // Importance of reconstruction accuracy
}

impl Default for CompressionPriorities {
    fn default() -> Self {
        Self {
            compression_weight: 0.4,
            speed_weight: 0.3,
            accuracy_weight: 0.3,
        }
    }
}

/// Multi-level compression strategy
#[derive(Debug, Clone)]
pub struct MultiLevelCompression {
    pub levels: Vec<CompressionMethod>,
    pub thresholds: Vec<f32>, // Quality thresholds for each level
}

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

impl MultiLevelCompression {
    pub fn new() -> Self {
        Self {
            levels: vec![
                CompressionMethod::None,
                CompressionMethod::Quantization { bits: 16 },
                CompressionMethod::Quantization { bits: 8 },
                CompressionMethod::Pca { components: 0 }, // Will be set adaptively
                CompressionMethod::Zstd { level: 3 },
            ],
            thresholds: vec![0.0, 0.1, 0.3, 0.6, 0.8],
        }
    }

    /// Select compression level based on requirements
    pub fn select_level(&self, required_compression: f32) -> &CompressionMethod {
        for (i, &threshold) in self.thresholds.iter().enumerate() {
            if required_compression <= threshold {
                return &self.levels[i];
            }
        }
        self.levels
            .last()
            .expect("compression levels should not be empty")
    }
}

/// Adaptive compression engine that learns optimal strategies
pub struct AdaptiveCompressor {
    /// Current compression priorities
    priorities: CompressionPriorities,
    /// Performance metrics for each compression method
    metrics: Arc<RwLock<HashMap<String, CompressionMetrics>>>,
    /// Multi-level compression strategies
    multi_level: MultiLevelCompression,
    /// Cache of trained compressors
    compressor_cache: Arc<RwLock<HashMap<String, Box<dyn VectorCompressor + Send + Sync>>>>,
    /// Statistics cache for similar vectors
    stats_cache: Arc<RwLock<HashMap<String, (VectorStats, Instant)>>>,
    /// Learning parameters
    exploration_rate: f32,
    cache_ttl: Duration,
}

impl AdaptiveCompressor {
    pub fn new() -> Self {
        Self::new_with_priorities(CompressionPriorities::default())
    }

    pub fn new_with_priorities(priorities: CompressionPriorities) -> Self {
        Self {
            priorities,
            metrics: Arc::new(RwLock::new(HashMap::new())),
            multi_level: MultiLevelCompression::new(),
            compressor_cache: Arc::new(RwLock::new(HashMap::new())),
            stats_cache: Arc::new(RwLock::new(HashMap::new())),
            exploration_rate: 0.1,
            cache_ttl: Duration::from_secs(3600), // 1 hour cache TTL
        }
    }

    /// Analyze vector characteristics and recommend compression strategy
    pub fn analyze_and_recommend(
        &mut self,
        vectors: &[Vector],
    ) -> Result<CompressionMethod, VectorError> {
        let stats = VectorStats::from_vectors(vectors)?;
        let stats_key = self.generate_stats_key(&stats);

        // Check cache first
        {
            let cache = self
                .stats_cache
                .read()
                .expect("rwlock should not be poisoned");
            if let Some((cached_stats, timestamp)) = cache.get(&stats_key) {
                if timestamp.elapsed() < self.cache_ttl {
                    return Ok(self.recommend_from_stats(cached_stats));
                }
            }
        }

        // Cache the stats
        {
            let mut cache = self
                .stats_cache
                .write()
                .expect("rwlock should not be poisoned");
            cache.insert(stats_key, (stats.clone(), Instant::now()));
        }

        Ok(self.recommend_from_stats(&stats))
    }

    /// Recommend compression method based on vector statistics
    fn recommend_from_stats(&self, stats: &VectorStats) -> CompressionMethod {
        // High sparsity -> prefer quantization or PCA
        if stats.sparsity > 0.7 {
            return CompressionMethod::Quantization { bits: 4 };
        }

        // High correlation -> PCA works well
        if stats.correlation > 0.6 && stats.dimensions > 20 {
            let components = (stats.dimensions as f32 * 0.7) as usize;
            return CompressionMethod::Pca { components };
        }

        // Low entropy -> Zstd compression is effective
        if stats.entropy < 4.0 {
            return CompressionMethod::Zstd { level: 9 };
        }

        // High variance -> quantization with more bits
        if stats.std_dev > stats.mean.abs() {
            return CompressionMethod::Quantization { bits: 12 };
        }

        // Default: moderate quantization
        CompressionMethod::Quantization { bits: 8 }
    }

    /// Compress vector with adaptive strategy selection
    pub fn compress_adaptive(&mut self, vector: &Vector) -> Result<Vec<u8>, VectorError> {
        let stats = VectorStats::from_vector(vector)?;
        let method = self.recommend_from_stats(&stats);

        // Check if we should explore alternative methods
        if self.should_explore() {
            let alternative = self.get_alternative_method(&method);
            return self.compress_with_method(vector, &alternative);
        }

        self.compress_with_method(vector, &method)
    }

    /// Compress with specific method and update metrics
    pub fn compress_with_method(
        &mut self,
        vector: &Vector,
        method: &CompressionMethod,
    ) -> Result<Vec<u8>, VectorError> {
        let method_key = format!("{method:?}");
        let compressor = self.get_or_create_compressor(method)?;

        let start_time = Instant::now();
        let compressed = compressor.compress(vector)?;
        let compression_time = start_time.elapsed();

        // Measure reconstruction error
        let decompressed = compressor.decompress(&compressed, vector.dimensions)?;
        let error = self.calculate_reconstruction_error(vector, &decompressed)?;

        let compression_ratio = compressed.len() as f32 / (vector.dimensions * 4) as f32; // Assuming f32 vectors

        // Update metrics
        {
            let mut metrics = self.metrics.write().expect("rwlock should not be poisoned");
            let metric = metrics
                .entry(method_key)
                .or_insert_with(|| CompressionMetrics::new(method.clone()));
            metric.update(
                compression_ratio,
                compression_time,
                Duration::ZERO,
                error,
                &self.priorities,
            );
        }

        Ok(compressed)
    }

    /// Multi-level compression for extreme compression ratios
    pub fn compress_multi_level(
        &mut self,
        vector: &Vector,
        target_ratio: f32,
    ) -> Result<Vec<u8>, VectorError> {
        let mut current_vector = vector.clone();
        let mut compression_steps = Vec::new();
        let mut total_ratio = 1.0;

        while total_ratio > target_ratio && compression_steps.len() < 3 {
            let remaining_ratio = target_ratio / total_ratio;
            let method = self.multi_level.select_level(remaining_ratio);

            let compressor = self.get_or_create_compressor(method)?;
            let compressed = compressor.compress(&current_vector)?;

            let step_ratio = compressed.len() as f32 / (current_vector.dimensions * 4) as f32;
            total_ratio *= step_ratio;

            compression_steps.push((method.clone(), compressed.clone()));

            // Prepare for next level if needed
            if total_ratio > target_ratio {
                current_vector = compressor.decompress(&compressed, current_vector.dimensions)?;
            }
        }

        // Serialize the compression steps
        self.serialize_multi_level_result(compression_steps)
    }

    /// Get best performing compression method based on current metrics
    pub fn get_best_method(&self) -> CompressionMethod {
        let metrics = self.metrics.read().expect("rwlock should not be poisoned");
        let best = metrics.values().max_by(|a, b| {
            a.avg_performance_score
                .partial_cmp(&b.avg_performance_score)
                .expect("performance scores should be comparable")
        });

        best.map(|m| m.method.clone())
            .unwrap_or(CompressionMethod::Quantization { bits: 8 })
    }

    /// Get compression performance statistics
    pub fn get_performance_stats(&self) -> HashMap<String, CompressionMetrics> {
        self.metrics
            .read()
            .expect("rwlock should not be poisoned")
            .clone()
    }

    /// Update compression priorities
    pub fn update_priorities(&mut self, priorities: CompressionPriorities) {
        self.priorities = priorities;

        // Recalculate scores for all metrics
        let mut metrics = self.metrics.write().expect("rwlock should not be poisoned");
        for metric in metrics.values_mut() {
            metric.avg_performance_score = metric.calculate_score(&self.priorities);
        }
    }

    /// Clear caches and reset learning
    pub fn reset(&mut self) {
        self.metrics
            .write()
            .expect("rwlock should not be poisoned")
            .clear();
        self.compressor_cache
            .write()
            .expect("rwlock should not be poisoned")
            .clear();
        self.stats_cache
            .write()
            .expect("rwlock should not be poisoned")
            .clear();
    }

    // Private helper methods

    fn get_or_create_compressor(
        &self,
        method: &CompressionMethod,
    ) -> Result<Box<dyn VectorCompressor>, VectorError> {
        let method_key = format!("{method:?}");

        {
            let cache = self
                .compressor_cache
                .read()
                .expect("rwlock should not be poisoned");
            if cache.contains_key(&method_key) {
                // Note: We can't return a reference here due to trait object limitations
                // So we create a new instance
            }
        }

        // Create new compressor (existing create_compressor function)
        let compressor = create_compressor(method);

        // Cache it (though we can't use it directly due to trait object limitations)
        {
            let _cache = self
                .compressor_cache
                .write()
                .expect("rwlock should not be poisoned");
            // Note: This is a placeholder for caching logic
            // In practice, we might need to redesign this for trait objects
        }

        Ok(compressor)
    }

    fn calculate_reconstruction_error(
        &self,
        original: &Vector,
        reconstructed: &Vector,
    ) -> Result<f32, VectorError> {
        let orig_values = original.as_f32();
        let recon_values = reconstructed.as_f32();

        if orig_values.len() != recon_values.len() {
            return Err(VectorError::InvalidDimensions(
                "Dimension mismatch".to_string(),
            ));
        }

        let mse: f32 = orig_values
            .iter()
            .zip(recon_values.iter())
            .map(|(a, b)| (a - b).powi(2))
            .sum::<f32>()
            / orig_values.len() as f32;

        Ok(mse.sqrt()) // RMSE
    }

    fn generate_stats_key(&self, stats: &VectorStats) -> String {
        format!(
            "{}_{:.2}_{:.2}_{:.2}_{:.2}",
            stats.dimensions, stats.entropy, stats.sparsity, stats.correlation, stats.std_dev
        )
    }

    fn should_explore(&self) -> bool {
        #[allow(unused_imports)]
        use scirs2_core::random::{Random, Rng};
        let mut rng = Random::seed(42);
        rng.gen_range(0.0..1.0) < self.exploration_rate
    }

    fn get_alternative_method(&self, current: &CompressionMethod) -> CompressionMethod {
        match current {
            CompressionMethod::None => CompressionMethod::Quantization { bits: 8 },
            CompressionMethod::Quantization { bits } => {
                if *bits > 8 {
                    CompressionMethod::Quantization { bits: bits - 2 }
                } else {
                    CompressionMethod::Pca { components: 16 }
                }
            }
            CompressionMethod::Pca { components: _ } => CompressionMethod::Zstd { level: 6 },
            CompressionMethod::Zstd { level } => {
                if *level < 15 {
                    CompressionMethod::Zstd { level: level + 3 }
                } else {
                    CompressionMethod::Quantization { bits: 4 }
                }
            }
            _ => CompressionMethod::None,
        }
    }

    fn serialize_multi_level_result(
        &self,
        steps: Vec<(CompressionMethod, Vec<u8>)>,
    ) -> Result<Vec<u8>, VectorError> {
        use std::io::Write;

        let mut result = Vec::new();

        // Write number of steps
        result.write_all(&(steps.len() as u32).to_le_bytes())?;

        // Write each step
        for (method, data) in steps {
            // Serialize method (simplified)
            let method_id = match method {
                CompressionMethod::None => 0u8,
                CompressionMethod::Zstd { .. } => 1u8,
                CompressionMethod::Quantization { .. } => 2u8,
                CompressionMethod::Pca { .. } => 3u8,
                CompressionMethod::ProductQuantization { .. } => 4u8,
                CompressionMethod::Adaptive { .. } => 5u8,
            };
            result.push(method_id);

            // Write data length and data
            result.write_all(&(data.len() as u32).to_le_bytes())?;
            result.extend_from_slice(&data);
        }

        Ok(result)
    }
}

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

/// Domain-specific compression profiles
pub struct CompressionProfiles {
    profiles: HashMap<VectorDomain, CompressionPriorities>,
}

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

impl CompressionProfiles {
    pub fn new() -> Self {
        let mut profiles = HashMap::new();

        // Text embeddings: balance compression and quality
        profiles.insert(
            VectorDomain::TextEmbeddings,
            CompressionPriorities {
                compression_weight: 0.3,
                speed_weight: 0.4,
                accuracy_weight: 0.3,
            },
        );

        // Image features: favor compression due to redundancy
        profiles.insert(
            VectorDomain::ImageFeatures,
            CompressionPriorities {
                compression_weight: 0.5,
                speed_weight: 0.2,
                accuracy_weight: 0.3,
            },
        );

        // Knowledge graph: favor accuracy
        profiles.insert(
            VectorDomain::KnowledgeGraph,
            CompressionPriorities {
                compression_weight: 0.2,
                speed_weight: 0.3,
                accuracy_weight: 0.5,
            },
        );

        // Time series: balance speed and accuracy
        profiles.insert(
            VectorDomain::TimeSeriesData,
            CompressionPriorities {
                compression_weight: 0.3,
                speed_weight: 0.4,
                accuracy_weight: 0.3,
            },
        );

        // Audio features: favor compression
        profiles.insert(
            VectorDomain::AudioFeatures,
            CompressionPriorities {
                compression_weight: 0.4,
                speed_weight: 0.3,
                accuracy_weight: 0.3,
            },
        );

        Self { profiles }
    }

    pub fn get_profile(&self, domain: &VectorDomain) -> CompressionPriorities {
        self.profiles.get(domain).cloned().unwrap_or_default()
    }

    pub fn update_profile(&mut self, domain: VectorDomain, priorities: CompressionPriorities) {
        self.profiles.insert(domain, priorities);
    }
}

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

    #[test]
    fn test_vector_stats() -> Result<()> {
        let vector = Vector::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let stats = VectorStats::from_vector(&vector)?;

        assert_eq!(stats.dimensions, 5);
        assert_eq!(stats.mean, 3.0);
        assert!(stats.std_dev > 0.0);
        Ok(())
    }

    #[test]
    fn test_adaptive_compression() -> Result<()> {
        let vectors = vec![
            Vector::new(vec![1.0, 2.0, 3.0, 4.0]),
            Vector::new(vec![2.0, 3.0, 4.0, 5.0]),
            Vector::new(vec![3.0, 4.0, 5.0, 6.0]),
        ];

        let mut compressor = AdaptiveCompressor::new();
        let recommended = compressor.analyze_and_recommend(&vectors)?;

        // Should recommend some compression method
        assert!(!matches!(recommended, CompressionMethod::None));
        Ok(())
    }

    #[test]
    fn test_compression_metrics() {
        let method = CompressionMethod::Quantization { bits: 8 };
        let mut metrics = CompressionMetrics::new(method);
        let priorities = CompressionPriorities::default();

        metrics.update(
            0.5,
            Duration::from_millis(10),
            Duration::from_millis(5),
            0.01,
            &priorities,
        );

        assert!(metrics.avg_performance_score > 0.0);
        assert_eq!(metrics.usage_count, 1);
    }

    #[test]
    fn test_multi_level_compression() -> Result<()> {
        let mut compressor = AdaptiveCompressor::new();
        // Use a larger vector with repetitive patterns that compress well
        let values: Vec<f32> = (0..256).map(|i| (i % 16) as f32).collect();
        let vector = Vector::new(values);

        let compressed = compressor.compress_multi_level(&vector, 0.1)?;

        // Should achieve significant compression on this larger, repetitive vector
        // Original size would be 256 * 4 = 1024 bytes
        // Multi-level compression includes metadata overhead, so expect reasonable compression
        println!(
            "Compressed size: {} bytes, original size: {} bytes",
            compressed.len(),
            vector.dimensions * 4
        );
        assert!(compressed.len() < vector.dimensions * 4); // At least some compression
        assert!(compressed.len() < 900); // Should achieve at least 12% compression
        Ok(())
    }

    #[test]
    fn test_stats_aggregation() -> Result<()> {
        let vectors = vec![
            Vector::new(vec![1.0, 2.0]),
            Vector::new(vec![3.0, 4.0]),
            Vector::new(vec![5.0, 6.0]),
        ];

        let stats = VectorStats::from_vectors(&vectors)?;
        assert_eq!(stats.dimensions, 2);
        assert!(stats.mean > 0.0);
        Ok(())
    }
}