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
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
#![allow(dead_code)]
//! ONNX inference module for IntentForge v2
//!
//! Handles batch inference for text embeddings and scoring using
//! all-MiniLM-L6-v2 model with 384-dimensional output vectors.

use anyhow::{Context, Result};
use lru::LruCache;
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::{Arc, Mutex};

/// Tokenizer for text preprocessing
#[derive(Clone)]
pub struct Tokenizer {
    max_seq_length: usize,
    vocab: std::collections::HashMap<String, i64>,
}

/// Tokenized batch as raw Vec data with shape info
pub struct TokenizedBatch {
    pub input_ids: Vec<i64>,
    pub attention_mask: Vec<i64>,
    pub token_type_ids: Vec<i64>,
    pub shape: Vec<i64>,
}

impl Tokenizer {
    pub fn new(max_seq_length: usize) -> Self {
        let mut vocab = std::collections::HashMap::new();

        // Attempt to load BERT vocab if it exists in models/vocab.txt
        if let Ok(content) = std::fs::read_to_string("models/vocab.txt") {
            for (i, line) in content.lines().enumerate() {
                vocab.insert(line.to_string(), i as i64);
            }
            tracing::info!("Loaded {} tokens into Tokenizer vocab", vocab.len());
        } else {
            tracing::warn!("models/vocab.txt not found. Tokenizer will use fallback hashing.");
        }

        Self {
            max_seq_length,
            vocab,
        }
    }

    /// Tokenize a batch of texts into flat vectors with shape [batch, seq_len]
    pub fn tokenize_batch(&self, texts: &[String]) -> TokenizedBatch {
        let batch_size = texts.len();
        let seq_len = self.max_seq_length;
        let total = batch_size * seq_len;

        let mut input_ids = vec![0i64; total];
        let mut attention_mask = vec![0i64; total];
        let token_type_ids = vec![0i64; total];

        for (i, text) in texts.iter().enumerate() {
            let tokens = self.tokenize_text(text);
            for (j, &token_id) in tokens.iter().enumerate().take(seq_len) {
                let idx = i * seq_len + j;
                input_ids[idx] = token_id;
                attention_mask[idx] = 1;
            }
        }

        TokenizedBatch {
            input_ids,
            attention_mask,
            token_type_ids,
            shape: vec![batch_size as i64, seq_len as i64],
        }
    }

    /// Tokenize pairs of texts (e.g., query + document) for Cross-Encoders
    pub fn tokenize_pairs(&self, pairs: &[(String, String)]) -> TokenizedBatch {
        let batch_size = pairs.len();
        let seq_len = self.max_seq_length;
        let total = batch_size * seq_len;

        let mut input_ids = vec![0i64; total];
        let mut attention_mask = vec![0i64; total];
        let mut token_type_ids = vec![0i64; total];

        for (i, (text_a, text_b)) in pairs.iter().enumerate() {
            let tokens_a = self.tokenize_text_raw(text_a);
            let tokens_b = self.tokenize_text_raw(text_b);

            // BERT-style: [CLS] text_a [SEP] text_b [SEP]
            let mut combined = vec![101i64]; // [CLS]

            // Limit text_a and text_b to fit in seq_len
            let max_a = (seq_len - 3) / 2;
            let max_b = seq_len - 3 - tokens_a.len().min(max_a);

            for &t in tokens_a.iter().take(max_a) {
                combined.push(t);
            }
            combined.push(102i64); // [SEP]

            let sep_idx = combined.len();

            for &t in tokens_b.iter().take(max_b) {
                combined.push(t);
            }
            combined.push(102i64); // [SEP]

            for (j, &token_id) in combined.iter().enumerate().take(seq_len) {
                let idx = i * seq_len + j;
                input_ids[idx] = token_id;
                attention_mask[idx] = 1;
                if j >= sep_idx {
                    token_type_ids[idx] = 1;
                }
            }
        }

        TokenizedBatch {
            input_ids,
            attention_mask,
            token_type_ids,
            shape: vec![batch_size as i64, seq_len as i64],
        }
    }

    fn tokenize_text(&self, text: &str) -> Vec<i64> {
        let mut tokens = vec![101i64]; // [CLS]
        for word in text.split_whitespace().take(self.max_seq_length - 2) {
            tokens.push(self.hash_to_token_id(word));
        }
        tokens.push(102i64); // [SEP]
        tokens
    }

    fn tokenize_text_raw(&self, text: &str) -> Vec<i64> {
        text.split_whitespace()
            .map(|word| self.hash_to_token_id(word))
            .collect()
    }

    fn hash_to_token_id(&self, word: &str) -> i64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let lower = word.to_lowercase();
        if let Some(&id) = self.vocab.get(&lower) {
            return id;
        }
        let mut hasher = DefaultHasher::new();
        lower.hash(&mut hasher);
        let hash = hasher.finish();
        1000 + (hash % 29522) as i64
    }
}

/// Scoring rules and heuristics for content quality
#[derive(Clone)]
pub struct QualityScorer {
    min_length: usize,
    max_length: usize,
    stop_words: std::collections::HashSet<String>,
    high_signal_words: std::collections::HashSet<String>,
}

impl QualityScorer {
    pub fn new() -> Self {
        let mut high_signal = std::collections::HashSet::new();
        for word in &[
            "tutorial",
            "guide",
            "how-to",
            "comparison",
            "benchmark",
            "analysis",
            "framework",
            "library",
            "release",
            "announcement",
            "research",
            "paper",
        ] {
            high_signal.insert(word.to_string());
        }

        let mut stop_words = std::collections::HashSet::new();
        for word in &[
            "a", "an", "the", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with",
            "by", "from", "is", "it", "that", "this", "was", "are", "be", "has", "had", "have",
            "do", "does", "did", "will", "would", "could", "should", "may", "might", "can", "not",
            "no", "so", "if", "as", "its", "into", "about", "up", "out", "then", "than", "them",
            "they", "their", "there", "here", "when", "where", "which", "who", "whom", "what",
            "how", "all", "each", "every", "both", "few", "more", "most", "other", "some", "such",
            "only", "own", "same", "just", "also", "very", "too", "now", "i", "me", "my", "we",
            "us", "our", "you", "your", "he", "him", "his", "she", "her", "it", "its", "been",
            "being", "were", "am", "s", "t", "re", "ve", "ll", "d",
        ] {
            stop_words.insert(word.to_string());
        }

        Self {
            min_length: 100,
            max_length: 50000,
            stop_words,
            high_signal_words: high_signal,
        }
    }

    /// Calculate a rule-based score [0, 1]
    pub fn calculate_rule_score(&self, text: &str) -> f32 {
        let len = text.len();
        if len < self.min_length {
            return 0.1;
        }

        let words: Vec<&str> = text.split_whitespace().collect();
        if words.is_empty() {
            return 0.0;
        }

        // Length bonus/penalty (prefer medium-long content)
        let length_score = if len > 5000 {
            0.8 // Very long, potentially redundant
        } else if len > 1000 {
            1.0 // Ideal length
        } else {
            0.5 // Short but okay
        };

        // Signal word density
        let mut signal_count = 0;
        let mut content_words = Vec::new();
        for word in &words {
            let lower = word.to_lowercase();
            if self.high_signal_words.contains(&lower) {
                signal_count += 1;
            }
            if !self.stop_words.contains(&lower) {
                content_words.push(lower);
            }
        }
        let signal_score = (signal_count as f32 / 10.0).min(1.0);

        // Content word diversity (excluding stop words)
        let unique_ratio = if content_words.is_empty() {
            0.0
        } else {
            let unique: std::collections::HashSet<_> = content_words.iter().collect();
            unique.len() as f32 / content_words.len() as f32
        };

        (length_score * 0.4 + signal_score * 0.4 + unique_ratio * 0.2).min(1.0)
    }

    /// Calculate quality score with domain boost
    pub fn calculate_boosted_score(&self, text: &str, url: &str) -> f32 {
        let base_score = self.calculate_rule_score(text);
        let mut boost = 1.0f32;

        let url_lower = url.to_lowercase();
        if url_lower.contains("arxiv.org")
            || url_lower.contains("github.com")
            || url_lower.contains("docs.")
            || url_lower.contains(".edu")
            || url_lower.contains("rust-lang.org")
        {
            boost = 1.3;
        } else if url_lower.contains("techcrunch.com")
            || url_lower.contains("news.")
            || url_lower.contains("blog.")
        {
            boost = 0.9;
        }

        (base_score * boost).clamp(0.0, 1.0)
    }
}

/// Lightweight keyword-based intent scorer for pre-fetch filtering
#[derive(Clone)]
pub struct FastIntentScorer {
    weights: std::collections::HashMap<String, f32>,
    threshold: f32,
}

impl FastIntentScorer {
    pub fn new(threshold: f32) -> Self {
        let mut weights = std::collections::HashMap::new();
        // High-signal intent keywords
        let high_signal = [
            ("tutorial", 0.5),
            ("guide", 0.4),
            ("how-to", 0.5),
            ("benchmark", 0.4),
            ("analysis", 0.3),
            ("framework", 0.3),
            ("library", 0.3),
            ("release", 0.2),
            ("announcement", 0.2),
            ("research", 0.4),
            ("paper", 0.4),
            ("github", 0.3),
            ("arxiv", 0.4),
            ("medium", 0.1),
            ("dev.to", 0.2),
            ("documentation", 0.4),
            ("api", 0.3),
            ("rust", 0.2),
            ("python", 0.1),
            ("ai", 0.2),
            ("ml", 0.2),
            ("deeplearning", 0.3),
            ("opensource", 0.3),
        ];

        for (word, weight) in high_signal {
            weights.insert(word.to_string(), weight);
        }

        Self { weights, threshold }
    }

    /// Calculate a fast intent score [0, 1] based on URL and Title tokens
    pub fn score(&self, text: &str) -> f32 {
        let normalized = text.to_lowercase();
        let mut score = 0.1f32; // Baseline

        for (word, weight) in &self.weights {
            if normalized.contains(word) {
                score += weight;
            }
        }

        score.min(1.0)
    }

    /// Check if the text passes the intent threshold
    pub fn passes(&self, text: &str) -> bool {
        self.score(text) >= self.threshold
    }

    pub fn threshold(&self) -> f32 {
        self.threshold
    }
}

/// ONNX embedding model for batch inference
#[derive(Clone)]
pub struct EmbeddingModel {
    session: Option<Arc<Mutex<ort::session::Session>>>,
    rerank_session: Option<Arc<Mutex<ort::session::Session>>>,
    tokenizer: Tokenizer,
    scorer: QualityScorer,
    pub fast_scorer: FastIntentScorer,
    embedding_dim: usize,
    batch_size: usize,
    embedding_cache: Arc<Mutex<LruCache<String, Vec<f32>>>>,
}

impl EmbeddingModel {
    pub fn new(
        model_path: &str,
        embedding_dim: usize,
        max_seq_length: usize,
        batch_size: usize,
        fast_intent_threshold: f32,
    ) -> Result<Self> {
        let tokenizer = Tokenizer::new(max_seq_length);
        let scorer = QualityScorer::new();
        let fast_scorer = FastIntentScorer::new(fast_intent_threshold);

        let session = if Path::new(model_path).exists() {
            tracing::info!("Loading ONNX embedding model from '{}'...", model_path);

            let session = ort::session::Session::builder()
                .with_context(|| "Failed to create ONNX session builder")?
                .commit_from_file(model_path)
                .with_context(|| format!("Failed to load ONNX model from {}", model_path))?;

            Some(Arc::new(Mutex::new(session)))
        } else {
            tracing::warn!(
                "ONNX embedding model not found at '{}', using fallback hash embeddings",
                model_path
            );
            None
        };

        // Try to load rerank model if it exists (usually cross-encoder/ms-marco-MiniLM-L6-v2)
        let rerank_path = model_path.replace("all-MiniLM-L6-v2", "rerank-MiniLM-L6-v2");
        let rerank_session = if Path::new(&rerank_path).exists() {
            tracing::info!("Loading ONNX rerank model from '{}'...", rerank_path);

            let session = ort::session::Session::builder()
                .with_context(|| "Failed to create ONNX rerank session builder")?
                .commit_from_file(&rerank_path)
                .with_context(|| {
                    format!("Failed to load ONNX rerank model from {}", rerank_path)
                })?;

            Some(Arc::new(Mutex::new(session)))
        } else {
            tracing::warn!(
                "ONNX rerank model not found at '{}', reranking will use fallback",
                rerank_path
            );
            None
        };

        Ok(Self {
            session,
            rerank_session,
            tokenizer,
            scorer,
            fast_scorer,
            embedding_dim,
            batch_size,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1000).unwrap()))),
        })
    }

    pub fn is_loaded(&self) -> bool {
        self.session.is_some()
    }

    pub fn is_rerank_loaded(&self) -> bool {
        self.rerank_session.is_some()
    }

    /// Calculate quality score for text with domain boost
    pub fn calculate_quality_score(&self, text: &str, url: &str) -> f32 {
        self.scorer.calculate_boosted_score(text, url)
    }

    /// Get embedding dimension
    pub fn embedding_dim(&self) -> usize {
        self.embedding_dim
    }

    /// Generate embeddings for a batch of texts with LRU caching
    pub fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        if texts.is_empty() {
            return Ok(Vec::new());
        }

        // Check cache for each text, separate into cached vs missing
        let mut results = Vec::with_capacity(texts.len());
        let mut missing_indices = Vec::new();

        {
            let mut cache = self
                .embedding_cache
                .lock()
                .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?;
            for (i, text) in texts.iter().enumerate() {
                if let Some(embedding) = cache.get(text) {
                    results.push((i, embedding.clone()));
                } else {
                    missing_indices.push(i);
                }
            }
        }

        // Compute embeddings for missing texts
        if !missing_indices.is_empty() {
            let missing_texts: Vec<String> =
                missing_indices.iter().map(|&i| texts[i].clone()).collect();
            let computed = if self.session.is_some() {
                self.embed_with_model(&missing_texts)?
            } else {
                self.embed_fallback(&missing_texts)
            };

            // Store in cache and results
            let mut cache = self
                .embedding_cache
                .lock()
                .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?;
            for (idx, embedding) in missing_indices.into_iter().zip(computed.into_iter()) {
                cache.put(texts[idx].clone(), embedding.clone());
                results.push((idx, embedding));
            }
        }

        // Sort by original index
        results.sort_by_key(|(i, _)| *i);
        Ok(results.into_iter().map(|(_, emb)| emb).collect())
    }

    fn embed_with_model(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        let session_lock = self.session.as_ref().unwrap();
        let mut session = session_lock
            .lock()
            .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?;
        let mut all_embeddings = Vec::with_capacity(texts.len());

        for chunk in texts.chunks(self.batch_size) {
            let batch = self.tokenizer.tokenize_batch(chunk);

            let input_ids_tensor =
                ort::value::Tensor::from_array((batch.shape.clone(), batch.input_ids))
                    .with_context(|| "Failed to create input_ids tensor")?;
            let attention_mask_tensor =
                ort::value::Tensor::from_array((batch.shape.clone(), batch.attention_mask.clone()))
                    .with_context(|| "Failed to create attention_mask tensor")?;
            let token_type_ids_tensor =
                ort::value::Tensor::from_array((batch.shape, batch.token_type_ids))
                    .with_context(|| "Failed to create token_type_ids tensor")?;

            let outputs = session
                .run(ort::inputs![
                    "input_ids" => input_ids_tensor,
                    "attention_mask" => attention_mask_tensor,
                    "token_type_ids" => token_type_ids_tensor
                ])
                .with_context(|| "ONNX inference failed")?;

            let output_value = &outputs["last_hidden_state"];
            let (shape, data) = output_value.try_extract_tensor::<f32>()?;

            let batch_size_actual = chunk.len();
            let seq_len = shape[1] as usize;
            let hidden_dim = shape[2] as usize;

            for i in 0..batch_size_actual {
                let mut embedding = vec![0.0f32; self.embedding_dim];
                let mut count = 0usize;

                for j in 0..seq_len {
                    let mask_idx = i * seq_len + j;
                    if batch.attention_mask[mask_idx] == 1 {
                        for (k, val) in embedding
                            .iter_mut()
                            .enumerate()
                            .take(hidden_dim.min(self.embedding_dim))
                        {
                            let idx = i * seq_len * hidden_dim + j * hidden_dim + k;
                            *val += data[idx];
                        }
                        count += 1;
                    }
                }

                if count > 0 {
                    for val in embedding.iter_mut() {
                        *val /= count as f32;
                    }
                }

                let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
                if norm > 0.0 {
                    for val in embedding.iter_mut() {
                        *val /= norm;
                    }
                }

                all_embeddings.push(embedding);
            }
        }

        Ok(all_embeddings)
    }

    /// Rerank query-document pairs using Cross-Encoder
    pub fn rerank(&self, query: &str, documents: &[String]) -> Result<Vec<f32>> {
        if documents.is_empty() {
            return Ok(Vec::new());
        }

        if let Some(rerank_lock) = &self.rerank_session {
            let mut session = rerank_lock
                .lock()
                .map_err(|_| anyhow::anyhow!("Mutex poisoned"))?;

            let mut all_scores = Vec::with_capacity(documents.len());

            for chunk in documents.chunks(self.batch_size) {
                let pairs: Vec<(String, String)> = chunk
                    .iter()
                    .map(|doc| (query.to_string(), doc.clone()))
                    .collect();
                let batch = self.tokenizer.tokenize_pairs(&pairs);

                let input_ids_tensor =
                    ort::value::Tensor::from_array((batch.shape.clone(), batch.input_ids))
                        .with_context(|| "Failed to create input_ids tensor")?;
                let attention_mask_tensor =
                    ort::value::Tensor::from_array((batch.shape.clone(), batch.attention_mask))
                        .with_context(|| "Failed to create attention_mask tensor")?;
                let token_type_ids_tensor =
                    ort::value::Tensor::from_array((batch.shape, batch.token_type_ids))
                        .with_context(|| "Failed to create token_type_ids tensor")?;

                let outputs = session
                    .run(ort::inputs![
                        "input_ids" => input_ids_tensor,
                        "attention_mask" => attention_mask_tensor,
                        "token_type_ids" => token_type_ids_tensor
                    ])
                    .with_context(|| "ONNX rerank inference failed")?;

                // Cross-encoders usually output a single score per pair
                // The output name might vary, but "logits" or "output_0" are common
                let output_value = outputs
                    .get("logits")
                    .or_else(|| outputs.get("output_0"))
                    .context("Failed to find output tensor in rerank model")?;

                let (_, data) = output_value.try_extract_tensor::<f32>()?;

                for &score in data.iter() {
                    // Sigmoid for probability if needed, or just raw logits
                    let prob = 1.0 / (1.0 + (-score).exp());
                    all_scores.push(prob);
                }
            }

            Ok(all_scores)
        } else {
            // Fallback: use cosine similarity of embeddings
            let query_emb = self
                .embed_batch(&[query.to_string()])?
                .into_iter()
                .next()
                .unwrap();
            let doc_embs = self.embed_batch(documents.to_vec().as_slice())?;

            let scores = doc_embs
                .iter()
                .map(|doc_emb| crate::utils::cosine_similarity(&query_emb, doc_emb).clamp(0.0, 1.0))
                .collect();

            Ok(scores)
        }
    }

    pub fn embed_fallback(&self, texts: &[String]) -> Vec<Vec<f32>> {
        texts.iter().map(|text| self.hash_embedding(text)).collect()
    }

    fn hash_embedding(&self, text: &str) -> Vec<f32> {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut embedding = vec![0.0f32; self.embedding_dim];

        for (i, word) in text.split_whitespace().enumerate() {
            let mut hasher = DefaultHasher::new();
            word.to_lowercase().hash(&mut hasher);
            let hash = hasher.finish();

            for (j, val) in embedding.iter_mut().enumerate().take(self.embedding_dim) {
                let seed = (i * self.embedding_dim + j) as u64;
                let mut h = DefaultHasher::new();
                (hash ^ seed).hash(&mut h);
                let noise = (h.finish() as f64 / u64::MAX as f64) as f32;
                *val += noise;
            }
        }

        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for val in embedding.iter_mut() {
                *val /= norm;
            }
        }

        embedding
    }

    /// Score documents using hybrid rule-based and embedding diversity metrics
    pub fn score_batch(&self, texts: &[String]) -> Result<Vec<f32>> {
        if texts.is_empty() {
            return Ok(Vec::new());
        }

        let embeddings = self.embed_batch(texts)?;
        let mut scores = Vec::with_capacity(texts.len());

        for (i, text) in texts.iter().enumerate() {
            let emb = &embeddings[i];

            // Embedding diversity score
            let mean = emb.iter().sum::<f32>() / emb.len() as f32;
            let diversity = emb.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / emb.len() as f32;
            let embedding_score = (diversity.sqrt() * 10.0).clamp(0.0, 1.0);

            // Rule-based score
            let rule_score = self.scorer.calculate_rule_score(text);

            // Weighted average
            let final_score = (embedding_score * 0.4 + rule_score * 0.6).clamp(0.0, 1.0);
            scores.push(final_score);
        }

        Ok(scores)
    }

    pub fn batch_size(&self) -> usize {
        self.batch_size
    }
}

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

    #[test]
    fn test_tokenizer_basic() {
        let tokenizer = Tokenizer::new(128);
        let texts = vec!["hello world test".to_string()];
        let batch = tokenizer.tokenize_batch(&texts);

        assert_eq!(batch.shape, vec![1, 128]);

        // CLS token
        assert_eq!(batch.input_ids[0], 101);
        // SEP token (3 words + CLS + SEP = 5 tokens)
        assert_eq!(batch.input_ids[4], 102);
        // Attention mask should be 1 for first 5 positions
        assert_eq!(batch.attention_mask[0], 1);
        assert_eq!(batch.attention_mask[4], 1);
        assert_eq!(batch.attention_mask[5], 0);
    }

    #[test]
    fn test_tokenizer_batch() {
        let tokenizer = Tokenizer::new(64);
        let texts = vec![
            "first document".to_string(),
            "second document with more words".to_string(),
        ];
        let batch = tokenizer.tokenize_batch(&texts);

        assert_eq!(batch.shape, vec![2, 64]);
        // Both should have CLS
        assert_eq!(batch.input_ids[0], 101);
        assert_eq!(batch.input_ids[64], 101);
    }

    #[test]
    fn test_fallback_embedding() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let texts = vec!["hello world".to_string()];
        let embeddings = model.embed_fallback(&texts);

        assert_eq!(embeddings.len(), 1);
        assert_eq!(embeddings[0].len(), 384);

        let norm: f32 = embeddings[0].iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5);
    }

    #[test]
    fn test_fallback_embedding_deterministic() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let texts = vec!["test input".to_string()];
        let emb1 = model.embed_fallback(&texts);
        let emb2 = model.embed_fallback(&texts);

        assert_eq!(emb1, emb2);
    }

    #[test]
    fn test_fallback_embedding_different_inputs() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let emb1 = model.embed_fallback(&["hello world".to_string()]);
        let emb2 = model.embed_fallback(&["goodbye universe".to_string()]);

        assert_ne!(emb1[0], emb2[0]);
    }

    #[test]
    fn test_fallback_batch_embedding() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let texts = vec![
            "first document".to_string(),
            "second document".to_string(),
            "third document".to_string(),
        ];
        let embeddings = model.embed_fallback(&texts);

        assert_eq!(embeddings.len(), 3);
        for emb in &embeddings {
            assert_eq!(emb.len(), 384);
            let norm: f32 = emb.iter().map(|x| x * x).sum::<f32>().sqrt();
            assert!((norm - 1.0).abs() < 1e-5);
        }
    }

    #[test]
    fn test_embed_batch_fallback() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let model = model;
        let texts = vec!["hello world".to_string()];
        let embeddings = model.embed_batch(&texts).unwrap();

        assert_eq!(embeddings.len(), 1);
        assert_eq!(embeddings[0].len(), 384);
    }

    #[test]
    fn test_empty_batch() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let embeddings = model.embed_batch(&[]).unwrap();
        assert!(embeddings.is_empty());

        let scores = model.score_batch(&[]).unwrap();
        assert!(scores.is_empty());
    }

    #[test]
    fn test_score_batch() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let texts = vec![
            "short".to_string(),
            "a much longer document with many more words and details".to_string(),
        ];
        let scores = model.score_batch(&texts).unwrap();

        assert_eq!(scores.len(), 2);
        for score in &scores {
            assert!(*score >= 0.0 && *score <= 1.0);
        }
    }

    #[test]
    fn test_hash_embedding_distribution() {
        let model = EmbeddingModel {
            session: None,
            rerank_session: None,
            tokenizer: Tokenizer::new(128),
            scorer: QualityScorer::new(),
            fast_scorer: FastIntentScorer::new(0.4),
            embedding_dim: 384,
            batch_size: 32,
            embedding_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(10).unwrap()))),
        };

        let embedding = model.hash_embedding("test embedding distribution");

        let mean = embedding.iter().sum::<f32>() / embedding.len() as f32;
        let variance =
            embedding.iter().map(|x| (x - mean).powi(2)).sum::<f32>() / embedding.len() as f32;

        assert!(variance > 0.0, "Embedding should have non-zero variance");
    }

    #[test]
    fn test_model_not_loaded_without_file() {
        let model = EmbeddingModel::new("nonexistent_model.onnx", 384, 128, 32, 0.4).unwrap();
        assert!(!model.is_loaded());
    }
}