libgrammstein 0.1.0

Hybrid language model (N-gram + Embeddings) for WFST text correction
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
//! Combined LaTeX scorer integrating n-gram, embedding, and neural components.
//!
//! This module provides a unified scoring interface that combines multiple
//! scoring components for comprehensive LaTeX sequence evaluation.

use crate::latex::embedding::CommandCategory;
use crate::latex::ngram::{LaTeXMode, ModeDetector};
use crate::latex::tokenizer::{LaTeXToken, LaTeXTokenKind};
use std::collections::HashMap;

/// Configuration for the combined scorer.
#[derive(Debug, Clone)]
pub struct ScorerConfig {
    /// Weight for n-gram score component.
    pub ngram_weight: f64,
    /// Weight for embedding similarity score.
    pub embedding_weight: f64,
    /// Weight for neural rescorer score.
    pub neural_weight: f64,
    /// Weight for structural validity score.
    pub structural_weight: f64,
    /// Weight for RAG retrieval score.
    pub rag_weight: f64,
    /// Whether to normalize component scores before combining.
    pub normalize_components: bool,
    /// Minimum score threshold for acceptance.
    pub min_score: f64,
}

impl Default for ScorerConfig {
    fn default() -> Self {
        Self {
            ngram_weight: 0.30,
            embedding_weight: 0.15,
            neural_weight: 0.25,
            structural_weight: 0.20,
            rag_weight: 0.10,
            normalize_components: true,
            min_score: 0.0,
        }
    }
}

impl ScorerConfig {
    /// Create a config emphasizing statistical scoring.
    pub fn statistical() -> Self {
        Self {
            ngram_weight: 0.50,
            embedding_weight: 0.20,
            neural_weight: 0.10,
            structural_weight: 0.15,
            rag_weight: 0.05,
            ..Default::default()
        }
    }

    /// Create a config emphasizing neural scoring.
    pub fn neural() -> Self {
        Self {
            ngram_weight: 0.20,
            embedding_weight: 0.15,
            neural_weight: 0.45,
            structural_weight: 0.15,
            rag_weight: 0.05,
            ..Default::default()
        }
    }

    /// Create a config emphasizing structural validity.
    pub fn structural() -> Self {
        Self {
            ngram_weight: 0.20,
            embedding_weight: 0.10,
            neural_weight: 0.15,
            structural_weight: 0.45,
            rag_weight: 0.10,
            ..Default::default()
        }
    }
}

/// Individual component score with metadata.
#[derive(Debug, Clone)]
pub struct ComponentScore {
    /// Name of the scoring component.
    pub name: String,
    /// Raw score value.
    pub raw_score: f64,
    /// Normalized score (0.0 to 1.0).
    pub normalized_score: f64,
    /// Weight used in combination.
    pub weight: f64,
    /// Additional details about the score.
    pub details: HashMap<String, String>,
}

impl ComponentScore {
    /// Create a new component score.
    pub fn new(name: &str, raw_score: f64, weight: f64) -> Self {
        // Default normalization: assume raw_score is already in a reasonable range
        let normalized = raw_score.clamp(0.0, 1.0);
        Self {
            name: name.to_string(),
            raw_score,
            normalized_score: normalized,
            weight,
            details: HashMap::new(),
        }
    }

    /// Set the normalized score explicitly.
    pub fn with_normalized(mut self, normalized: f64) -> Self {
        self.normalized_score = normalized.clamp(0.0, 1.0);
        self
    }

    /// Add a detail.
    pub fn with_detail(mut self, key: &str, value: &str) -> Self {
        self.details.insert(key.to_string(), value.to_string());
        self
    }

    /// Get the weighted score.
    pub fn weighted_score(&self) -> f64 {
        self.normalized_score * self.weight
    }
}

/// Result of scoring a LaTeX sequence.
#[derive(Debug, Clone)]
pub struct ScoringResult {
    /// The scored sequence as text.
    pub sequence: String,
    /// Combined final score.
    pub score: f64,
    /// Individual component scores.
    pub components: Vec<ComponentScore>,
    /// Detected dominant mode.
    pub mode: LaTeXMode,
    /// Whether the sequence passes minimum score threshold.
    pub passes_threshold: bool,
    /// Confidence in the score (based on component agreement).
    pub confidence: f64,
}

impl ScoringResult {
    /// Create a new scoring result.
    pub fn new(sequence: String, score: f64, mode: LaTeXMode) -> Self {
        Self {
            sequence,
            score,
            components: Vec::new(),
            mode,
            passes_threshold: true,
            confidence: 1.0,
        }
    }

    /// Add a component score.
    pub fn add_component(&mut self, component: ComponentScore) {
        self.components.push(component);
    }

    /// Get a component by name.
    pub fn component(&self, name: &str) -> Option<&ComponentScore> {
        self.components.iter().find(|c| c.name == name)
    }

    /// Compute confidence based on component agreement.
    pub fn compute_confidence(&mut self) {
        if self.components.len() < 2 {
            self.confidence = 1.0;
            return;
        }

        // Compute standard deviation of normalized scores
        let scores: Vec<f64> = self.components.iter().map(|c| c.normalized_score).collect();
        let mean: f64 = scores.iter().sum::<f64>() / scores.len() as f64;
        let variance: f64 =
            scores.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / scores.len() as f64;
        let std_dev = variance.sqrt();

        // Lower std_dev = higher confidence (components agree)
        self.confidence = (1.0 - std_dev.min(0.5) * 2.0).max(0.0);
    }
}

/// Combined LaTeX scorer.
pub struct LaTeXScorer {
    /// Configuration.
    config: ScorerConfig,
    /// Mode detector for context analysis.
    mode_detector: ModeDetector,
    /// Cache for recent scores.
    cache: HashMap<String, ScoringResult>,
    /// Maximum cache size.
    max_cache_size: usize,
}

impl LaTeXScorer {
    /// Create a new scorer with default configuration.
    pub fn new() -> Self {
        Self::with_config(ScorerConfig::default())
    }

    /// Create a scorer with custom configuration.
    pub fn with_config(config: ScorerConfig) -> Self {
        Self {
            config,
            mode_detector: ModeDetector::new(),
            cache: HashMap::new(),
            max_cache_size: 10000,
        }
    }

    /// Create a builder for more complex configuration.
    pub fn builder() -> LaTeXScorerBuilder {
        LaTeXScorerBuilder::new()
    }

    /// Score a sequence of LaTeX tokens.
    pub fn score(&mut self, tokens: &[LaTeXToken]) -> ScoringResult {
        let sequence = tokens_to_string(tokens);

        // Check cache
        if let Some(cached) = self.cache.get(&sequence) {
            return cached.clone();
        }

        // Detect mode
        let mode = self.mode_detector.sequence_mode(tokens);

        // Compute component scores
        let mut components = Vec::new();

        // Structural score
        let structural = self.compute_structural_score(tokens);
        components.push(
            ComponentScore::new("structural", structural, self.config.structural_weight)
                .with_normalized(structural),
        );

        // Local token fluency score.
        let ngram = self.compute_local_fluency_score(tokens);
        components.push(
            ComponentScore::new("ngram", ngram, self.config.ngram_weight).with_normalized(ngram),
        );

        // Semantic coherence score.
        let embedding = self.compute_semantic_coherence_score(tokens);
        components.push(
            ComponentScore::new("embedding", embedding, self.config.embedding_weight)
                .with_normalized(embedding),
        );

        // Combine scores
        let combined = self.combine_scores(&components);

        let mut result = ScoringResult::new(sequence.clone(), combined, mode);
        result.components = components;
        result.passes_threshold = combined >= self.config.min_score;
        result.compute_confidence();

        // Cache result
        if self.cache.len() >= self.max_cache_size {
            self.cache.clear();
        }
        self.cache.insert(sequence, result.clone());

        result
    }

    /// Score multiple sequences and return sorted results.
    pub fn score_candidates(&mut self, candidates: &[&[LaTeXToken]]) -> Vec<ScoringResult> {
        let mut results: Vec<ScoringResult> =
            candidates.iter().map(|tokens| self.score(tokens)).collect();

        results.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        results
    }

    /// Get the best scoring candidate.
    pub fn best_candidate(&mut self, candidates: &[&[LaTeXToken]]) -> Option<ScoringResult> {
        self.score_candidates(candidates).into_iter().next()
    }

    /// Compute structural validity score.
    fn compute_structural_score(&self, tokens: &[LaTeXToken]) -> f64 {
        if tokens.is_empty() {
            return 0.0;
        }

        let mut score = 1.0;
        let mut brace_stack: Vec<char> = Vec::new();
        let mut math_stack: Vec<char> = Vec::new();
        let mut penalties = 0.0;

        for token in tokens {
            match &token.kind {
                // Track braces
                LaTeXTokenKind::OpenBrace(kind) => {
                    let c = match kind {
                        crate::latex::tokenizer::BraceKind::Curly => '{',
                        crate::latex::tokenizer::BraceKind::Square => '[',
                        crate::latex::tokenizer::BraceKind::Paren => '(',
                    };
                    brace_stack.push(c);
                }
                LaTeXTokenKind::CloseBrace(kind) => {
                    let expected = match kind {
                        crate::latex::tokenizer::BraceKind::Curly => '{',
                        crate::latex::tokenizer::BraceKind::Square => '[',
                        crate::latex::tokenizer::BraceKind::Paren => '(',
                    };
                    if brace_stack.pop() != Some(expected) {
                        penalties += 0.2; // Mismatched brace
                    }
                }

                // Track math delimiters
                LaTeXTokenKind::MathOpen(mode) => {
                    let c = match mode {
                        crate::latex::tokenizer::MathMode::InlineDollar => '$',
                        crate::latex::tokenizer::MathMode::DisplayDoubleDollar => 'D',
                        crate::latex::tokenizer::MathMode::InlineParen => '(',
                        crate::latex::tokenizer::MathMode::DisplayBracket => '[',
                        crate::latex::tokenizer::MathMode::Environment => 'E',
                    };
                    math_stack.push(c);
                }
                LaTeXTokenKind::MathClose(mode) => {
                    let expected = match mode {
                        crate::latex::tokenizer::MathMode::InlineDollar => '$',
                        crate::latex::tokenizer::MathMode::DisplayDoubleDollar => 'D',
                        crate::latex::tokenizer::MathMode::InlineParen => '(',
                        crate::latex::tokenizer::MathMode::DisplayBracket => '[',
                        crate::latex::tokenizer::MathMode::Environment => 'E',
                    };
                    if math_stack.pop() != Some(expected) {
                        penalties += 0.3; // Mismatched math delimiter
                    }
                }

                // Penalize unknown tokens
                LaTeXTokenKind::Unknown(_) => {
                    penalties += 0.1;
                }

                _ => {}
            }
        }

        // Penalize unclosed structures
        penalties += brace_stack.len() as f64 * 0.15;
        penalties += math_stack.len() as f64 * 0.2;

        score = (score - penalties).max(0.0);
        score
    }

    /// Compute local token fluency from adjacent LaTeX token transitions.
    fn compute_local_fluency_score(&self, tokens: &[LaTeXToken]) -> f64 {
        if tokens.is_empty() {
            return 0.0;
        }

        if tokens.len() == 1 {
            return match tokens[0].kind {
                LaTeXTokenKind::Unknown(_) => 0.25,
                _ => 0.70,
            };
        }

        let mut total = 0.0;
        let mut transitions = 0usize;
        for pair in tokens.windows(2) {
            total += self.transition_fluency(&pair[0], &pair[1]);
            transitions += 1;
        }

        let transition_score = total / transitions as f64;
        let command_ratio = tokens
            .iter()
            .filter(|t| matches!(t.kind, LaTeXTokenKind::Command(_)))
            .count() as f64
            / tokens.len() as f64;
        let density_score = (1.0 - (command_ratio - 0.20).abs() * 1.5).clamp(0.35, 1.0);

        (transition_score * 0.85 + density_score * 0.15).clamp(0.0, 1.0)
    }

    fn transition_fluency(&self, previous: &LaTeXToken, current: &LaTeXToken) -> f64 {
        use LaTeXTokenKind::*;

        match (&previous.kind, &current.kind) {
            (Command(cmd), OpenBrace(_)) if command_takes_group(cmd) => 1.0,
            (Command(cmd), _) if command_takes_group(cmd) => 0.45,
            (OpenBrace(_), CloseBrace(_)) => 0.55,
            (OpenBrace(_), _) | (_, CloseBrace(_)) => 0.85,
            (MathOpen(_), MathClose(_)) => 0.40,
            (MathOpen(_), _) | (_, MathClose(_)) => 0.95,
            (Identifier(_), Operator(_)) | (Number(_), Operator(_)) => 0.95,
            (Operator(_), Identifier(_)) | (Operator(_), Number(_)) | (Operator(_), Command(_)) => {
                0.95
            }
            (Subscript | Superscript, Identifier(_))
            | (Subscript | Superscript, Number(_))
            | (Subscript | Superscript, Command(_))
            | (Subscript | Superscript, OpenBrace(_)) => 0.95,
            (Subscript | Superscript, _) => 0.35,
            (Command(left), Command(right)) => command_pair_fluency(left, right),
            (Unknown(_), _) | (_, Unknown(_)) => 0.20,
            (Text(_), Text(_)) | (Identifier(_), Identifier(_)) => 0.75,
            _ => 0.70,
        }
    }

    /// Compute semantic coherence from token modes and command categories.
    fn compute_semantic_coherence_score(&self, tokens: &[LaTeXToken]) -> f64 {
        if tokens.is_empty() {
            return 0.0;
        }

        let mode = self.mode_detector.sequence_mode(tokens);
        let mode_matches = tokens
            .iter()
            .filter(|t| self.mode_detector.token_mode(t) == mode)
            .count();
        let mode_score = mode_matches as f64 / tokens.len() as f64;

        let command_categories: Vec<CommandCategory> = tokens
            .iter()
            .filter_map(|token| match &token.kind {
                LaTeXTokenKind::Command(command) => Some(CommandCategory::from_command(command)),
                _ => None,
            })
            .collect();

        let category_score = if command_categories.len() < 2 {
            1.0
        } else {
            let coherent_pairs = command_categories
                .windows(2)
                .filter(|pair| command_categories_are_compatible(pair[0], pair[1]))
                .count();
            coherent_pairs as f64 / (command_categories.len() - 1) as f64
        };

        let unknown_penalty = tokens
            .iter()
            .filter(|token| matches!(token.kind, LaTeXTokenKind::Unknown(_)))
            .count() as f64
            / tokens.len() as f64;

        (mode_score * 0.55 + category_score * 0.45 - unknown_penalty * 0.35).clamp(0.0, 1.0)
    }

    /// Combine component scores according to weights.
    fn combine_scores(&self, components: &[ComponentScore]) -> f64 {
        let mut total_weight = 0.0;
        let mut weighted_sum = 0.0;

        for component in components {
            weighted_sum += component.weighted_score();
            total_weight += component.weight;
        }

        if total_weight > 0.0 {
            weighted_sum / total_weight
        } else {
            0.0
        }
    }

    /// Clear the score cache.
    pub fn clear_cache(&mut self) {
        self.cache.clear();
    }

    /// Get cache statistics.
    pub fn cache_stats(&self) -> (usize, usize) {
        (self.cache.len(), self.max_cache_size)
    }

    /// Get the configuration.
    pub fn config(&self) -> &ScorerConfig {
        &self.config
    }
}

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

/// Builder for LaTeXScorer with fluent API.
pub struct LaTeXScorerBuilder {
    config: ScorerConfig,
}

impl LaTeXScorerBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            config: ScorerConfig::default(),
        }
    }

    /// Set n-gram weight.
    pub fn ngram_weight(mut self, weight: f64) -> Self {
        self.config.ngram_weight = weight;
        self
    }

    /// Set embedding weight.
    pub fn embedding_weight(mut self, weight: f64) -> Self {
        self.config.embedding_weight = weight;
        self
    }

    /// Set neural weight.
    pub fn neural_weight(mut self, weight: f64) -> Self {
        self.config.neural_weight = weight;
        self
    }

    /// Set structural weight.
    pub fn structural_weight(mut self, weight: f64) -> Self {
        self.config.structural_weight = weight;
        self
    }

    /// Set RAG weight.
    pub fn rag_weight(mut self, weight: f64) -> Self {
        self.config.rag_weight = weight;
        self
    }

    /// Set minimum score threshold.
    pub fn min_score(mut self, min: f64) -> Self {
        self.config.min_score = min;
        self
    }

    /// Enable/disable component normalization.
    pub fn normalize_components(mut self, normalize: bool) -> Self {
        self.config.normalize_components = normalize;
        self
    }

    /// Use statistical preset.
    pub fn statistical_preset(mut self) -> Self {
        self.config = ScorerConfig::statistical();
        self
    }

    /// Use neural preset.
    pub fn neural_preset(mut self) -> Self {
        self.config = ScorerConfig::neural();
        self
    }

    /// Use structural preset.
    pub fn structural_preset(mut self) -> Self {
        self.config = ScorerConfig::structural();
        self
    }

    /// Build the scorer.
    pub fn build(self) -> LaTeXScorer {
        LaTeXScorer::with_config(self.config)
    }
}

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

/// Convert tokens to a string representation.
fn tokens_to_string(tokens: &[LaTeXToken]) -> String {
    tokens.iter().map(|t| t.text()).collect::<Vec<_>>().join("")
}

fn command_takes_group(command: &str) -> bool {
    matches!(
        command,
        "frac"
            | "sqrt"
            | "binom"
            | "overline"
            | "underline"
            | "hat"
            | "bar"
            | "vec"
            | "text"
            | "textbf"
            | "textit"
            | "emph"
            | "section"
            | "subsection"
            | "subsubsection"
            | "begin"
            | "end"
    )
}

fn command_pair_fluency(left: &str, right: &str) -> f64 {
    match (left, right) {
        ("left", "right") | ("begin", "end") => 0.20,
        ("left", _) | (_, "right") => 0.60,
        _ => {
            let left_category = CommandCategory::from_command(left);
            let right_category = CommandCategory::from_command(right);
            if command_categories_are_compatible(left_category, right_category) {
                0.85
            } else {
                0.55
            }
        }
    }
}

fn command_categories_are_compatible(left: CommandCategory, right: CommandCategory) -> bool {
    use CommandCategory::*;

    matches!(
        (left, right),
        (GreekLetter, GreekLetter)
            | (Operator, GreekLetter)
            | (Operator, Function)
            | (Function, GreekLetter)
            | (Function, Operator)
            | (Relation, GreekLetter)
            | (Relation, Function)
            | (Accent, GreekLetter)
            | (Accent, Function)
            | (Delimiter, Delimiter)
            | (Environment, Environment)
            | (Formatting, Formatting)
            | (Structure, Structure)
            | (Arrow, Arrow)
            | (Spacing, _)
            | (_, Spacing)
    ) || left == right
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::latex::tokenizer::LaTeXTokenizer;

    #[test]
    fn test_basic_scoring() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        let tokens = tokenizer.tokenize(r"\alpha + \beta");
        let result = scorer.score(&tokens);

        assert!(!result.sequence.is_empty());
        assert!(result.score >= 0.0 && result.score <= 1.0);
        assert!(!result.components.is_empty());
    }

    #[test]
    fn test_structural_scoring() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        // Well-formed should score higher
        let well_formed = tokenizer.tokenize(r"\frac{a}{b}");
        let malformed = tokenizer.tokenize(r"\frac{a}{b");

        let score_well = scorer.score(&well_formed);
        let score_mal = scorer.score(&malformed);

        assert!(score_well.score >= score_mal.score);
    }

    #[test]
    fn test_builder() {
        let scorer = LaTeXScorer::builder()
            .ngram_weight(0.5)
            .structural_weight(0.5)
            .min_score(0.3)
            .build();

        assert_eq!(scorer.config().ngram_weight, 0.5);
        assert_eq!(scorer.config().structural_weight, 0.5);
        assert_eq!(scorer.config().min_score, 0.3);
    }

    #[test]
    fn test_presets() {
        let statistical = ScorerConfig::statistical();
        assert!(statistical.ngram_weight > statistical.neural_weight);

        let neural = ScorerConfig::neural();
        assert!(neural.neural_weight > neural.ngram_weight);

        let structural = ScorerConfig::structural();
        assert!(structural.structural_weight > structural.ngram_weight);
    }

    #[test]
    fn test_candidate_ranking() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        let candidates: Vec<Vec<LaTeXToken>> = vec![
            tokenizer.tokenize(r"\alpha"),
            tokenizer.tokenize(r"\frac{1}{2}"),
            tokenizer.tokenize(r"$x^2$"),
        ];

        let refs: Vec<&[LaTeXToken]> = candidates.iter().map(|v| v.as_slice()).collect();
        let results = scorer.score_candidates(&refs);

        assert_eq!(results.len(), 3);
        // Results should be sorted by score (descending)
        for i in 1..results.len() {
            assert!(results[i - 1].score >= results[i].score);
        }
    }

    #[test]
    fn test_caching() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        let tokens = tokenizer.tokenize(r"\alpha");

        // First call
        let result1 = scorer.score(&tokens);
        assert_eq!(scorer.cache_stats().0, 1);

        // Second call should use cache
        let result2 = scorer.score(&tokens);
        assert_eq!(result1.score, result2.score);

        scorer.clear_cache();
        assert_eq!(scorer.cache_stats().0, 0);
    }

    #[test]
    fn test_confidence() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        let tokens = tokenizer.tokenize(r"\frac{a}{b}");
        let result = scorer.score(&tokens);

        assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
    }

    #[test]
    fn test_component_scores() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::new();

        let tokens = tokenizer.tokenize(r"\alpha + \beta = \gamma");
        let result = scorer.score(&tokens);

        assert!(result.component("structural").is_some());
        assert!(result.component("ngram").is_some());
        assert!(result.component("embedding").is_some());
    }

    #[test]
    fn test_local_fluency_rewards_latex_argument_structure() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::builder()
            .ngram_weight(1.0)
            .embedding_weight(0.0)
            .neural_weight(0.0)
            .structural_weight(0.0)
            .rag_weight(0.0)
            .build();

        let fluent = scorer.score(&tokenizer.tokenize(r"\frac{a}{b}"));
        let abrupt = scorer.score(&tokenizer.tokenize(r"\frac \alpha \beta"));

        let fluent_score = fluent.component("ngram").expect("ngram");
        let abrupt_score = abrupt.component("ngram").expect("ngram");
        assert!(fluent_score.normalized_score > abrupt_score.normalized_score);
    }

    #[test]
    fn test_semantic_coherence_penalizes_unknown_tokens() {
        let tokenizer = LaTeXTokenizer::new();
        let mut scorer = LaTeXScorer::builder()
            .ngram_weight(0.0)
            .embedding_weight(1.0)
            .neural_weight(0.0)
            .structural_weight(0.0)
            .rag_weight(0.0)
            .build();

        let coherent = scorer.score(&tokenizer.tokenize(r"\alpha + \beta"));
        let mut noisy_tokens = tokenizer.tokenize(r"\alpha + \beta");
        noisy_tokens.push(LaTeXToken::new(
            LaTeXTokenKind::Unknown("@@".to_string()),
            0,
            2,
            false,
        ));
        let noisy = scorer.score(&noisy_tokens);

        let coherent_score = coherent.component("embedding").expect("embedding");
        let noisy_score = noisy.component("embedding").expect("embedding");
        assert!(coherent_score.normalized_score > noisy_score.normalized_score);
    }
}