codebook_config 0.3.41

Configuration handling for the Codebook spell checker
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
use glob::Pattern;
use log::warn;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// A single `[[overrides]]` block in the config file.
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct OverrideBlock {
    /// Required: glob patterns matched against file path relative to project root
    pub paths: Vec<String>,

    // --- Replace fields (replace the base list entirely) ---
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dictionaries: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub words: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flag_words: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ignore_patterns: Option<Vec<String>>,

    // --- Append fields (append to the resolved list) ---
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_dictionaries: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_words: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_flag_words: Option<Vec<String>>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_ignore_patterns: Option<Vec<String>>,
}

impl<'de> Deserialize<'de> for OverrideBlock {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        fn to_lowercase_vec(v: Vec<String>) -> Vec<String> {
            v.into_iter().map(|s| s.to_ascii_lowercase()).collect()
        }

        fn to_lowercase_opt(v: Option<Vec<String>>) -> Option<Vec<String>> {
            v.map(to_lowercase_vec)
        }

        #[derive(Deserialize)]
        struct Helper {
            #[serde(default)]
            paths: Vec<String>,
            #[serde(default)]
            dictionaries: Option<Vec<String>>,
            #[serde(default)]
            words: Option<Vec<String>>,
            #[serde(default)]
            flag_words: Option<Vec<String>>,
            #[serde(default)]
            ignore_patterns: Option<Vec<String>>,
            #[serde(default)]
            extra_dictionaries: Option<Vec<String>>,
            #[serde(default)]
            extra_words: Option<Vec<String>>,
            #[serde(default)]
            extra_flag_words: Option<Vec<String>>,
            #[serde(default)]
            extra_ignore_patterns: Option<Vec<String>>,
        }

        let helper = Helper::deserialize(deserializer)?;
        Ok(OverrideBlock {
            paths: helper.paths,
            // Lowercase word-related fields
            dictionaries: to_lowercase_opt(helper.dictionaries),
            words: to_lowercase_opt(helper.words),
            flag_words: to_lowercase_opt(helper.flag_words),
            extra_dictionaries: to_lowercase_opt(helper.extra_dictionaries),
            extra_words: to_lowercase_opt(helper.extra_words),
            extra_flag_words: to_lowercase_opt(helper.extra_flag_words),
            // Don't lowercase patterns or paths
            ignore_patterns: helper.ignore_patterns,
            extra_ignore_patterns: helper.extra_ignore_patterns,
        })
    }
}

impl OverrideBlock {
    /// Returns true if this override block is valid (has non-empty paths with at least one valid glob).
    pub fn is_valid(&self) -> bool {
        if self.paths.is_empty() {
            return false;
        }
        self.paths.iter().any(|p| Pattern::new(p).is_ok())
    }

    /// Check if this override applies to the given relative file path.
    pub fn matches_path(&self, relative_path: &Path) -> bool {
        let path_str = relative_path.to_string_lossy();
        self.paths.iter().any(|pattern| {
            Pattern::new(pattern)
                .map(|p| p.matches(&path_str))
                .unwrap_or(false)
        })
    }

    /// Returns true if any field besides `paths` is set (the override has an effect).
    pub fn has_effect(&self) -> bool {
        self.dictionaries.is_some()
            || self.words.is_some()
            || self.flag_words.is_some()
            || self.ignore_patterns.is_some()
            || self.extra_dictionaries.is_some()
            || self.extra_words.is_some()
            || self.extra_flag_words.is_some()
            || self.extra_ignore_patterns.is_some()
    }
}

#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct ConfigSettings {
    /// List of dictionaries to use for spell checking
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dictionaries: Vec<String>,

    /// Custom allowlist of words
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub words: Vec<String>,

    /// Words that should always be flagged
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flag_words: Vec<String>,

    /// Glob patterns for paths to include
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include_paths: Vec<String>,

    /// Glob patterns for paths to ignore
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ignore_paths: Vec<String>,

    /// Regex patterns for text to ignore
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ignore_patterns: Vec<String>,

    /// Whether to use global configuration
    #[serde(
        default = "default_use_global",
        skip_serializing_if = "is_default_use_global"
    )]
    pub use_global: bool,

    /// Minimum word length to check (words shorter than this are ignored)
    #[serde(
        default = "default_min_word_length",
        skip_serializing_if = "is_default_min_word_length"
    )]
    pub min_word_length: usize,

    /// Tag prefixes to include (if non-empty, only matching tags are checked)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include_tags: Vec<String>,

    /// Tag prefixes to exclude (takes precedence over include_tags)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude_tags: Vec<String>,

    /// Scoped configuration overrides
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub overrides: Vec<OverrideBlock>,
}

fn default_use_global() -> bool {
    true
}

fn is_default_use_global(value: &bool) -> bool {
    *value == default_use_global()
}

fn default_min_word_length() -> usize {
    3
}

fn is_default_min_word_length(value: &usize) -> bool {
    *value == default_min_word_length()
}

impl Default for ConfigSettings {
    fn default() -> Self {
        Self {
            dictionaries: vec![],
            words: Vec::new(),
            flag_words: Vec::new(),
            include_paths: Vec::new(),
            ignore_paths: Vec::new(),
            ignore_patterns: Vec::new(),
            use_global: true,
            min_word_length: default_min_word_length(),
            include_tags: Vec::new(),
            exclude_tags: Vec::new(),
            overrides: Vec::new(),
        }
    }
}

impl<'de> Deserialize<'de> for ConfigSettings {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Helper {
            #[serde(default)]
            dictionaries: Vec<String>,
            #[serde(default)]
            words: Vec<String>,
            #[serde(default)]
            flag_words: Vec<String>,
            #[serde(default)]
            include_paths: Vec<String>,
            #[serde(default)]
            ignore_paths: Vec<String>,
            #[serde(default)]
            ignore_patterns: Vec<String>,
            #[serde(default = "default_use_global")]
            use_global: bool,
            #[serde(default = "default_min_word_length")]
            min_word_length: usize,
            #[serde(default)]
            include_tags: Vec<String>,
            #[serde(default)]
            exclude_tags: Vec<String>,
            #[serde(default)]
            overrides: Vec<OverrideBlock>,
        }

        // Dictionary IDs are language codes (e.g. "en_US") — normalize to lowercase
        // so lookups are case-insensitive. Word lists keep their original casing and
        // are compared via unicase::eq.
        let helper = Helper::deserialize(deserializer)?;

        // Filter out invalid override blocks
        let overrides: Vec<OverrideBlock> = helper
            .overrides
            .into_iter()
            .filter(|o| {
                if !o.is_valid() {
                    warn!("Skipping invalid override block (empty or invalid paths)");
                    return false;
                }
                if !o.has_effect() {
                    warn!("Skipping no-op override block (no settings specified)");
                    return false;
                }
                true
            })
            .collect();

        Ok(ConfigSettings {
            dictionaries: helper
                .dictionaries
                .into_iter()
                .map(|s| s.to_ascii_lowercase())
                .collect(),
            words: helper.words,
            flag_words: helper.flag_words,
            include_paths: helper.include_paths,
            ignore_paths: helper.ignore_paths,
            ignore_patterns: helper.ignore_patterns,
            use_global: helper.use_global,
            min_word_length: helper.min_word_length,
            include_tags: helper.include_tags,
            exclude_tags: helper.exclude_tags,
            overrides,
        })
    }
}

impl ConfigSettings {
    /// Merge another config settings into this one, sorting and deduplicating all collections.
    /// Overrides are appended (preserving order: self's overrides first, then other's).
    pub fn merge(&mut self, other: ConfigSettings) {
        // Add items from the other config
        self.dictionaries.extend(other.dictionaries);
        self.words.extend(other.words);
        self.flag_words.extend(other.flag_words);
        self.include_paths.extend(other.include_paths);
        self.ignore_paths.extend(other.ignore_paths);
        self.ignore_patterns.extend(other.ignore_patterns);
        self.include_tags.extend(other.include_tags);
        self.exclude_tags.extend(other.exclude_tags);

        // Append overrides (global first, then project — order matters)
        self.overrides.extend(other.overrides);

        // The use_global setting from the other config is ignored during merging
        // as this is a per-config setting

        // Override min_word_length if the other config has a non-default value
        if other.min_word_length != default_min_word_length() {
            self.min_word_length = other.min_word_length;
        }

        // Sort and deduplicate each collection (but NOT overrides)
        self.sort_and_dedup();
    }

    /// Sort and deduplicate all collections in the config (but not overrides).
    pub fn sort_and_dedup(&mut self) {
        // Sort and deduplicate each Vec
        sort_and_dedup(&mut self.dictionaries);
        sort_and_dedup(&mut self.words);
        sort_and_dedup(&mut self.flag_words);
        sort_and_dedup(&mut self.include_paths);
        sort_and_dedup(&mut self.ignore_paths);
        sort_and_dedup(&mut self.ignore_patterns);
        sort_and_dedup(&mut self.include_tags);
        sort_and_dedup(&mut self.exclude_tags);
        // Note: overrides are NOT sorted — order matters for resolution
    }

    /// Apply a single override block to this settings (mutates in place).
    /// Replace fields are applied first, then append fields.
    pub fn apply_override(&mut self, ovr: &OverrideBlock) {
        // Replace fields: fully replace the list
        if let Some(ref v) = ovr.dictionaries {
            self.dictionaries = v.clone();
        }
        if let Some(ref v) = ovr.words {
            self.words = v.clone();
        }
        if let Some(ref v) = ovr.flag_words {
            self.flag_words = v.clone();
        }
        if let Some(ref v) = ovr.ignore_patterns {
            self.ignore_patterns = v.clone();
        }

        // Append fields: extend the current list
        if let Some(ref v) = ovr.extra_dictionaries {
            self.dictionaries.extend(v.clone());
        }
        if let Some(ref v) = ovr.extra_words {
            self.words.extend(v.clone());
        }
        if let Some(ref v) = ovr.extra_flag_words {
            self.flag_words.extend(v.clone());
        }
        if let Some(ref v) = ovr.extra_ignore_patterns {
            self.ignore_patterns.extend(v.clone());
        }
    }

    /// Resolve the effective settings for a specific file path by applying matching overrides.
    /// Returns a new ConfigSettings with overrides applied and the overrides list cleared.
    pub fn resolve_for_path(&self, path: &Path) -> ConfigSettings {
        let mut resolved = self.clone();
        resolved.overrides = vec![]; // Resolved config has no overrides

        for ovr in &self.overrides {
            if ovr.matches_path(path) {
                resolved.apply_override(ovr);
            }
        }

        resolved
    }
}

/// Check if a tag matches a pattern using prefix matching.
/// "comment" matches "comment", "comment.line", "comment.block", etc.
fn tag_matches_pattern(tag: &str, pattern: &str) -> bool {
    tag == pattern || tag.starts_with(pattern) && tag.as_bytes().get(pattern.len()) == Some(&b'.')
}

impl ConfigSettings {
    /// Determine whether a capture tag should be spell-checked based on
    /// include_tags and exclude_tags. exclude_tags takes precedence.
    pub fn should_check_tag(&self, tag: &str) -> bool {
        // exclude_tags takes precedence
        if self
            .exclude_tags
            .iter()
            .any(|p| tag_matches_pattern(tag, p))
        {
            return false;
        }
        // if include_tags is set, tag must match at least one
        if !self.include_tags.is_empty() {
            return self
                .include_tags
                .iter()
                .any(|p| tag_matches_pattern(tag, p));
        }
        true
    }

    /// Insert a word into the allowlist, returning true when it was newly added.
    /// Existing entries differing only in case are treated as duplicates.
    pub fn insert_word(&mut self, word: &str) -> bool {
        if self.words.iter().any(|w| unicase::eq(w.as_str(), word)) {
            return false;
        }
        self.words.push(word.to_string());
        self.words.sort();
        true
    }

    /// Insert a path into the ignore list, returning true when it was newly added.
    pub fn insert_ignore(&mut self, file: &str) -> bool {
        let file = file.to_string();
        if self.ignore_paths.contains(&file) {
            return false;
        }
        self.ignore_paths.push(file);
        self.ignore_paths.sort();
        self.ignore_paths.dedup();
        true
    }

    /// Insert a path into the include list, returning true when it was newly added.
    pub fn insert_include(&mut self, file: &str) -> bool {
        let file = file.to_string();
        if self.include_paths.contains(&file) {
            return false;
        }
        self.include_paths.push(file);
        self.include_paths.sort();
        self.include_paths.dedup();
        true
    }

    /// Resolve configured dictionary IDs, providing a default when none are set.
    pub fn dictionary_ids(&self) -> Vec<String> {
        if self.dictionaries.is_empty() {
            vec!["en_us".to_string()]
        } else {
            self.dictionaries.clone()
        }
    }

    /// Determine whether a path should be included based on the configured glob patterns.
    pub fn should_include_path(&self, path: &Path) -> bool {
        if self.include_paths.is_empty() {
            return true;
        }
        let path_str = path.to_string_lossy();
        match_pattern(&self.include_paths, &path_str)
    }

    /// Determine whether a path should be ignored based on the configured glob patterns.
    pub fn should_ignore_path(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        match_pattern(&self.ignore_paths, &path_str)
    }

    /// Check if a word is explicitly allowed.
    pub fn is_allowed_word(&self, word: &str) -> bool {
        self.words.iter().any(|w| unicase::eq(w.as_str(), word))
    }

    /// Check if a word should be flagged.
    pub fn should_flag_word(&self, word: &str) -> bool {
        self.flag_words.iter().any(|w| unicase::eq(w.as_str(), word))
    }

    /// Retrieve the configured minimum word length.
    pub fn min_word_length(&self) -> usize {
        self.min_word_length
    }
}

fn match_pattern(patterns: &[String], path_str: &str) -> bool {
    patterns.iter().any(|pattern| {
        Pattern::new(pattern)
            .map(|p| p.matches(path_str))
            .unwrap_or(false)
    })
}

/// Helper function to sort and deduplicate a Vec of strings
fn sort_and_dedup(vec: &mut Vec<String>) {
    vec.sort();
    vec.dedup();
}

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

    #[test]
    fn test_default() {
        let config = ConfigSettings::default();
        assert_eq!(config.dictionaries, Vec::<String>::new());
        assert_eq!(config.words, Vec::<String>::new());
        assert_eq!(config.flag_words, Vec::<String>::new());
        assert_eq!(config.include_paths, Vec::<String>::new());
        assert_eq!(config.ignore_paths, Vec::<String>::new());
        assert_eq!(config.ignore_patterns, Vec::<String>::new());
        assert!(config.use_global);
        assert_eq!(config.min_word_length, 3);
        assert!(config.overrides.is_empty());
    }

    #[test]
    fn test_deserialization() {
        let toml_str = r#"
        dictionaries = ["EN_US", "en_GB"]
        words = ["CodeBook", "Rust", "Апгрейдить"]
        flag_words = ["TODO", "FIXME", "Ошибка"]
        include_paths = ["src/**/*.rs", "lib/"]
        ignore_paths = ["**/*.md", "target/"]
        ignore_patterns = ["^```.*$", "^//.*$"]
        use_global = false
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();

        assert_eq!(config.dictionaries, vec!["en_us", "en_gb"]);
        assert_eq!(config.words, vec!["CodeBook", "Rust", "Апгрейдить"]);
        assert_eq!(config.flag_words, vec!["TODO", "FIXME", "Ошибка"]);
        assert_eq!(config.include_paths, vec!["src/**/*.rs", "lib/"]);
        assert_eq!(config.ignore_paths, vec!["**/*.md", "target/"]);

        // Don't test the exact order, just check that both elements are present
        assert_eq!(config.ignore_patterns.len(), 2);
        assert!(config.ignore_patterns.contains(&"^```.*$".to_string()));
        assert!(config.ignore_patterns.contains(&"^//.*$".to_string()));

        assert!(!config.use_global);
    }

    #[test]
    fn test_min_word_length_deserialization() {
        // Test with explicit value
        let toml_str = r#"
        min_word_length = 2
        "#;
        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert_eq!(config.min_word_length, 2);

        // Test with default value (when not specified)
        let toml_str = r#"
        dictionaries = ["en_us"]
        "#;
        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert_eq!(config.min_word_length, 3);
    }

    #[test]
    fn test_serialization() {
        let config = ConfigSettings {
            dictionaries: vec!["en_us".to_string()],
            words: vec!["rust".to_string()],
            ..Default::default()
        };

        let serialized = toml::to_string(&config).unwrap();
        assert!(serialized.contains("dictionaries = [\"en_us\"]"));
        assert!(serialized.contains("words = [\"rust\"]"));
        // Defaults should not be there
        assert!(!serialized.contains("use_global = true"));
        assert!(!serialized.contains("min_word_length = 3"));
    }

    #[test]
    fn test_serialization_roundtrip_include_paths() {
        let config = ConfigSettings {
            include_paths: vec!["src/**/*.rs".to_string(), "lib/".to_string()],
            ..Default::default()
        };

        let serialized = toml::to_string(&config).unwrap();
        assert!(serialized.contains("include_paths"));

        let deserialized: ConfigSettings = toml::from_str(&serialized).unwrap();
        assert_eq!(deserialized.include_paths, vec!["src/**/*.rs", "lib/"]);
    }

    #[test]
    fn test_merge() {
        let mut base = ConfigSettings {
            dictionaries: vec!["en_us".to_string()],
            words: vec!["codebook".to_string()],
            flag_words: vec!["todo".to_string()],
            include_paths: vec!["src/".to_string()],
            ignore_paths: vec!["**/*.md".to_string()],
            ignore_patterns: vec!["^```.*$".to_string()],
            use_global: true,
            min_word_length: 3,
            ..Default::default()
        };

        let other = ConfigSettings {
            dictionaries: vec!["en_gb".to_string(), "en_us".to_string()],
            words: vec!["rust".to_string()],
            flag_words: vec!["fixme".to_string()],
            include_paths: vec!["lib/".to_string(), "src/".to_string()],
            ignore_paths: vec!["target/".to_string()],
            ignore_patterns: vec!["^//.*$".to_string()],
            use_global: false,
            min_word_length: 2,
            ..Default::default()
        };

        base.merge(other);

        // After merging and deduplicating, we should have combined items
        assert_eq!(base.dictionaries, vec!["en_gb", "en_us"]);
        assert_eq!(base.words, vec!["codebook", "rust"]);
        assert_eq!(base.flag_words, vec!["fixme", "todo"]);
        assert_eq!(base.include_paths, vec!["lib/", "src/"]);
        assert_eq!(base.ignore_paths, vec!["**/*.md", "target/"]);

        // Don't test the exact order, just check that both elements are present
        assert_eq!(base.ignore_patterns.len(), 2);
        assert!(base.ignore_patterns.contains(&"^```.*$".to_string()));
        assert!(base.ignore_patterns.contains(&"^//.*$".to_string()));

        // use_global from the base should be preserved
        assert!(base.use_global);
        // min_word_length from other should override base (since it's non-default)
        assert_eq!(base.min_word_length, 2);
    }

    #[test]
    fn test_merge_min_word_length_default() {
        let mut base = ConfigSettings {
            dictionaries: vec!["en_us".to_string()],
            min_word_length: 5,
            ..Default::default()
        };

        let other = ConfigSettings {
            dictionaries: vec!["en_gb".to_string()],
            min_word_length: 3, // default value
            ..Default::default()
        };

        base.merge(other);

        // min_word_length from base should be preserved when other has default
        assert_eq!(base.min_word_length, 5);
    }

    #[test]
    fn test_sort_and_dedup() {
        let mut config = ConfigSettings {
            dictionaries: vec![
                "en_gb".to_string(),
                "en_us".to_string(),
                "en_gb".to_string(),
            ],
            words: vec![
                "rust".to_string(),
                "codebook".to_string(),
                "rust".to_string(),
            ],
            flag_words: vec!["fixme".to_string(), "todo".to_string(), "fixme".to_string()],
            include_paths: vec![],
            ignore_paths: vec![
                "target/".to_string(),
                "**/*.md".to_string(),
                "target/".to_string(),
            ],
            ignore_patterns: vec![
                "^//.*$".to_string(),
                "^```.*$".to_string(),
                "^//.*$".to_string(),
            ],
            use_global: true,
            min_word_length: 3,
            ..Default::default()
        };

        config.sort_and_dedup();

        assert_eq!(config.dictionaries, vec!["en_gb", "en_us"]);
        assert_eq!(config.words, vec!["codebook", "rust"]);
        assert_eq!(config.flag_words, vec!["fixme", "todo"]);
        assert_eq!(config.ignore_paths, vec!["**/*.md", "target/"]);

        // Don't test the exact order, just check that both elements are present and duplicates removed
        assert_eq!(config.ignore_patterns.len(), 2);
        assert!(config.ignore_patterns.contains(&"^```.*$".to_string()));
        assert!(config.ignore_patterns.contains(&"^//.*$".to_string()));
    }

    #[test]
    fn test_use_global_default() {
        let toml_str = r#"
        dictionaries = ["EN_US"]
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert!(config.use_global);
    }

    #[test]
    fn test_empty_deserialization() {
        let toml_str = "";
        let config: ConfigSettings = toml::from_str(toml_str).unwrap();

        assert_eq!(config, ConfigSettings::default());
    }

    #[test]
    fn test_unicode_words_ignore_case() {
        let mut config = ConfigSettings::default();

        assert!(config.insert_word("Апгрейдить"));
        assert!(!config.insert_word("апгрейдить"));
        assert_eq!(config.words, vec!["Апгрейдить"]);
        assert!(config.is_allowed_word("АПГРЕЙДИТЬ"));
        assert!(config.is_allowed_word("апгрейдить"));

        config.flag_words.push("ошибка".to_string());
        assert!(config.should_flag_word("Ошибка"));
    }

    #[test]
    fn test_include_tags_deserialization() {
        let toml_str = r#"
        include_tags = ["comment", "string"]
        "#;
        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert_eq!(config.include_tags, vec!["comment", "string"]);
        assert!(config.exclude_tags.is_empty());
    }

    #[test]
    fn test_exclude_tags_deserialization() {
        let toml_str = r#"
        exclude_tags = ["identifier.variable", "identifier.parameter"]
        "#;
        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert!(config.include_tags.is_empty());
        assert_eq!(
            config.exclude_tags,
            vec!["identifier.variable", "identifier.parameter"]
        );
    }

    #[test]
    fn test_tags_default_empty() {
        let config = ConfigSettings::default();
        assert!(config.include_tags.is_empty());
        assert!(config.exclude_tags.is_empty());
    }

    #[test]
    fn test_tags_serialization_omitted_when_empty() {
        let config = ConfigSettings::default();
        let serialized = toml::to_string(&config).unwrap();
        assert!(!serialized.contains("include_tags"));
        assert!(!serialized.contains("exclude_tags"));
    }

    #[test]
    fn test_tags_serialization_present_when_set() {
        let config = ConfigSettings {
            include_tags: vec!["comment".to_string()],
            ..Default::default()
        };
        let serialized = toml::to_string(&config).unwrap();
        assert!(serialized.contains("include_tags"));
    }

    #[test]
    fn test_tags_merge() {
        let mut base = ConfigSettings {
            include_tags: vec!["comment".to_string()],
            exclude_tags: vec!["identifier.type".to_string()],
            ..Default::default()
        };
        let other = ConfigSettings {
            include_tags: vec!["string".to_string(), "comment".to_string()],
            exclude_tags: vec!["identifier.module".to_string()],
            ..Default::default()
        };
        base.merge(other);
        assert_eq!(base.include_tags, vec!["comment", "string"]);
        assert_eq!(
            base.exclude_tags,
            vec!["identifier.module", "identifier.type"]
        );
    }

    #[test]
    fn test_should_check_tag_no_filters() {
        let config = ConfigSettings::default();
        assert!(config.should_check_tag("comment"));
        assert!(config.should_check_tag("string"));
        assert!(config.should_check_tag("identifier.function"));
    }

    #[test]
    fn test_should_check_tag_include_only() {
        let config = ConfigSettings {
            include_tags: vec!["comment".to_string(), "string".to_string()],
            ..Default::default()
        };
        assert!(config.should_check_tag("comment"));
        assert!(config.should_check_tag("comment.line"));
        assert!(config.should_check_tag("comment.block"));
        assert!(config.should_check_tag("string"));
        assert!(config.should_check_tag("string.special"));
        assert!(!config.should_check_tag("identifier"));
        assert!(!config.should_check_tag("identifier.function"));
    }

    #[test]
    fn test_should_check_tag_exclude_only() {
        let config = ConfigSettings {
            exclude_tags: vec!["identifier.variable".to_string()],
            ..Default::default()
        };
        assert!(config.should_check_tag("comment"));
        assert!(config.should_check_tag("identifier.function"));
        assert!(!config.should_check_tag("identifier.variable"));
    }

    #[test]
    fn test_should_check_tag_both_include_and_exclude() {
        // include comments and strings, but exclude string.heredoc
        let config = ConfigSettings {
            include_tags: vec!["comment".to_string(), "string".to_string()],
            exclude_tags: vec!["string.heredoc".to_string()],
            ..Default::default()
        };
        assert!(config.should_check_tag("comment"));
        assert!(config.should_check_tag("comment.line"));
        assert!(config.should_check_tag("string"));
        assert!(config.should_check_tag("string.special"));
        assert!(!config.should_check_tag("string.heredoc"));
        assert!(!config.should_check_tag("identifier.function"));
    }

    #[test]
    fn test_should_check_tag_exclude_prefix() {
        // Excluding "identifier" should exclude all identifier sub-tags
        let config = ConfigSettings {
            exclude_tags: vec!["identifier".to_string()],
            ..Default::default()
        };
        assert!(config.should_check_tag("comment"));
        assert!(config.should_check_tag("string"));
        assert!(!config.should_check_tag("identifier"));
        assert!(!config.should_check_tag("identifier.function"));
        assert!(!config.should_check_tag("identifier.type"));
    }

    #[test]
    fn test_partial_deserialization() {
        let toml_str = r#"
        dictionaries = ["EN_US"]
        words = ["CodeBook"]
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();

        assert_eq!(config.dictionaries, vec!["en_us"]);
        assert_eq!(config.words, vec!["CodeBook"]);
        assert_eq!(config.flag_words, Vec::<String>::new());
        assert_eq!(config.ignore_paths, Vec::<String>::new());
        assert_eq!(config.ignore_patterns, Vec::<String>::new());
        assert!(config.use_global);
    }

    // --- Override tests ---

    #[test]
    fn test_override_block_deserialization() {
        let toml_str = r#"
        words = ["base"]

        [[overrides]]
        paths = ["**/*.md"]
        extra_words = ["Markdown"]
        dictionaries = ["EN_GB"]
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert_eq!(config.overrides.len(), 1);
        let ovr = &config.overrides[0];
        assert_eq!(ovr.paths, vec!["**/*.md"]);
        assert_eq!(ovr.extra_words, Some(vec!["markdown".to_string()])); // lowercased
        assert_eq!(ovr.dictionaries, Some(vec!["en_gb".to_string()])); // lowercased
        assert_eq!(ovr.words, None);
        assert_eq!(ovr.ignore_patterns, None);
    }

    #[test]
    fn test_override_block_empty_paths_skipped() {
        let toml_str = r#"
        [[overrides]]
        paths = []
        extra_words = ["test"]
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert!(config.overrides.is_empty());
    }

    #[test]
    fn test_override_block_no_effect_skipped() {
        let toml_str = r#"
        [[overrides]]
        paths = ["**/*.md"]
        "#;

        let config: ConfigSettings = toml::from_str(toml_str).unwrap();
        assert!(config.overrides.is_empty());
    }

    #[test]
    fn test_override_matches_path() {
        let ovr = OverrideBlock {
            paths: vec!["**/*.md".to_string(), "docs/**/*".to_string()],
            extra_words: Some(vec!["test".to_string()]),
            ..OverrideBlock::default_for_test()
        };

        assert!(ovr.matches_path(Path::new("README.md")));
        assert!(ovr.matches_path(Path::new("src/guide.md")));
        assert!(ovr.matches_path(Path::new("docs/api/index.html")));
        assert!(!ovr.matches_path(Path::new("src/main.rs")));
    }

    #[test]
    fn test_apply_override_replace() {
        let mut settings = ConfigSettings {
            words: vec!["alpha".to_string(), "beta".to_string()],
            ..Default::default()
        };

        let ovr = OverrideBlock {
            paths: vec!["**/*.md".to_string()],
            words: Some(vec!["gamma".to_string()]),
            ..OverrideBlock::default_for_test()
        };

        settings.apply_override(&ovr);
        assert_eq!(settings.words, vec!["gamma"]);
    }

    #[test]
    fn test_apply_override_append() {
        let mut settings = ConfigSettings {
            words: vec!["alpha".to_string(), "beta".to_string()],
            ..Default::default()
        };

        let ovr = OverrideBlock {
            paths: vec!["**/*.md".to_string()],
            extra_words: Some(vec!["gamma".to_string()]),
            ..OverrideBlock::default_for_test()
        };

        settings.apply_override(&ovr);
        assert_eq!(settings.words, vec!["alpha", "beta", "gamma"]);
    }

    #[test]
    fn test_apply_override_replace_then_append() {
        let mut settings = ConfigSettings {
            words: vec!["alpha".to_string(), "beta".to_string()],
            ..Default::default()
        };

        let ovr = OverrideBlock {
            paths: vec!["**/*.md".to_string()],
            words: Some(vec!["gamma".to_string()]),
            extra_words: Some(vec!["delta".to_string()]),
            ..OverrideBlock::default_for_test()
        };

        settings.apply_override(&ovr);
        assert_eq!(settings.words, vec!["gamma", "delta"]);
    }

    #[test]
    fn test_apply_override_no_change() {
        let mut settings = ConfigSettings {
            words: vec!["alpha".to_string()],
            dictionaries: vec!["en_us".to_string()],
            ..Default::default()
        };

        let ovr = OverrideBlock {
            paths: vec!["**/*.md".to_string()],
            extra_flag_words: Some(vec!["hack".to_string()]),
            ..OverrideBlock::default_for_test()
        };

        settings.apply_override(&ovr);
        // words and dictionaries unchanged
        assert_eq!(settings.words, vec!["alpha"]);
        assert_eq!(settings.dictionaries, vec!["en_us"]);
        // flag_words changed
        assert_eq!(settings.flag_words, vec!["hack"]);
    }

    #[test]
    fn test_resolve_for_path_no_match() {
        let settings = ConfigSettings {
            words: vec!["base".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["**/*.md".to_string()],
                extra_words: Some(vec!["markdown".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        let resolved = settings.resolve_for_path(Path::new("src/main.rs"));
        assert_eq!(resolved.words, vec!["base"]);
        assert!(resolved.overrides.is_empty());
    }

    #[test]
    fn test_resolve_for_path_single_match() {
        let settings = ConfigSettings {
            words: vec!["base".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["**/*.md".to_string()],
                extra_words: Some(vec!["markdown".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        let resolved = settings.resolve_for_path(Path::new("README.md"));
        assert_eq!(resolved.words, vec!["base", "markdown"]);
        assert!(resolved.overrides.is_empty());
    }

    #[test]
    fn test_resolve_for_path_multiple_matches() {
        let settings = ConfigSettings {
            words: vec!["base".to_string()],
            overrides: vec![
                OverrideBlock {
                    paths: vec!["**/*.md".to_string()],
                    extra_words: Some(vec!["markdown".to_string()]),
                    ..OverrideBlock::default_for_test()
                },
                OverrideBlock {
                    paths: vec!["docs/**/*".to_string()],
                    extra_words: Some(vec!["documentation".to_string()]),
                    ..OverrideBlock::default_for_test()
                },
            ],
            ..Default::default()
        };

        let resolved = settings.resolve_for_path(Path::new("docs/guide.md"));
        assert_eq!(resolved.words, vec!["base", "markdown", "documentation"]);
    }

    #[test]
    fn test_resolve_for_path_replace_overrides_base() {
        let settings = ConfigSettings {
            dictionaries: vec!["en_us".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["docs/de/**/*".to_string()],
                dictionaries: Some(vec!["de".to_string()]),
                extra_words: Some(vec!["codebook".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        let resolved = settings.resolve_for_path(Path::new("docs/de/guide.md"));
        assert_eq!(resolved.dictionaries, vec!["de"]);
        assert_eq!(resolved.words, vec!["codebook"]);
    }

    #[test]
    fn test_merge_preserves_override_order() {
        let mut global = ConfigSettings {
            words: vec!["global".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["**/*.md".to_string()],
                extra_words: Some(vec!["from_global".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        let project = ConfigSettings {
            words: vec!["project".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["**/*.md".to_string()],
                extra_words: Some(vec!["from_project".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        global.merge(project);

        // Overrides should be: global first, then project
        assert_eq!(global.overrides.len(), 2);
        assert_eq!(
            global.overrides[0].extra_words,
            Some(vec!["from_global".to_string()])
        );
        assert_eq!(
            global.overrides[1].extra_words,
            Some(vec!["from_project".to_string()])
        );
    }

    #[test]
    fn test_serialization_with_overrides() {
        let config = ConfigSettings {
            words: vec!["base".to_string()],
            overrides: vec![OverrideBlock {
                paths: vec!["**/*.md".to_string()],
                extra_words: Some(vec!["markdown".to_string()]),
                ..OverrideBlock::default_for_test()
            }],
            ..Default::default()
        };

        let serialized = toml::to_string_pretty(&config).unwrap();
        let deserialized: ConfigSettings = toml::from_str(&serialized).unwrap();

        assert_eq!(config, deserialized);
    }

    #[test]
    fn test_config_settings_query_methods() {
        let settings = ConfigSettings {
            dictionaries: vec!["en_us".to_string()],
            words: vec!["codebook".to_string()],
            flag_words: vec!["todo".to_string()],
            min_word_length: 4,
            ..Default::default()
        };

        assert_eq!(settings.dictionary_ids(), vec!["en_us"]);
        assert!(settings.is_allowed_word("codebook"));
        assert!(settings.is_allowed_word("CODEBOOK")); // case insensitive
        assert!(!settings.is_allowed_word("unknown"));
        assert!(settings.should_flag_word("todo"));
        assert!(settings.should_flag_word("TODO")); // case insensitive
        assert!(!settings.should_flag_word("done"));
        assert_eq!(settings.min_word_length(), 4);
    }

    #[test]
    fn test_dictionary_ids_default() {
        let settings = ConfigSettings::default();
        assert_eq!(settings.dictionary_ids(), vec!["en_us"]);
    }

    impl OverrideBlock {
        /// Helper for tests: creates an OverrideBlock with all fields set to None/empty.
        fn default_for_test() -> Self {
            Self {
                paths: vec![],
                dictionaries: None,
                words: None,
                flag_words: None,
                ignore_patterns: None,
                extra_dictionaries: None,
                extra_words: None,
                extra_flag_words: None,
                extra_ignore_patterns: None,
            }
        }
    }
}