css-variable-lsp 0.3.2

A fast, Rust-based Language Server Protocol implementation for CSS Variables
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
use ls_types::{Position, Uri};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::color::{color_from_key, normalize_color, parse_color, NormalizedColorKey};
use crate::dom_tree::DomTree;
use crate::specificity::sort_by_cascade;
use crate::types::{Config, CssVariable, CssVariableUsage, LiteralColorOccurrence};

type LiteralColorMap = HashMap<Uri, HashMap<u32, Vec<LiteralColorOccurrence>>>;

/// Manages CSS variables across the workspace
#[derive(Clone)]
pub struct CssVariableManager {
    /// Map of variable name -> list of definitions
    variables: Arc<RwLock<HashMap<String, Vec<CssVariable>>>>,

    /// Map of variable name -> list of usages
    usages: Arc<RwLock<HashMap<String, Vec<CssVariableUsage>>>>,

    /// Literal color occurrences grouped by document and line
    /// Outer map: URI -> Inner map (line number -> colors on that line)
    literal_colors: Arc<RwLock<LiteralColorMap>>,

    /// Map of normalized colors to matching variable names
    color_variables: Arc<RwLock<HashMap<NormalizedColorKey, HashSet<String>>>>,

    /// Configuration
    config: Arc<RwLock<Config>>,

    /// DOM trees for HTML documents
    dom_trees: Arc<RwLock<HashMap<Uri, DomTree>>>,

    /// Set of tracked document URIs (for counting unique documents)
    tracked_documents: Arc<RwLock<HashSet<Uri>>>,
}

impl CssVariableManager {
    pub fn new(config: Config) -> Self {
        Self {
            variables: Arc::new(RwLock::new(HashMap::new())),
            usages: Arc::new(RwLock::new(HashMap::new())),
            literal_colors: Arc::new(RwLock::new(HashMap::new())),
            color_variables: Arc::new(RwLock::new(HashMap::new())),
            config: Arc::new(RwLock::new(config)),
            dom_trees: Arc::new(RwLock::new(HashMap::new())),
            tracked_documents: Arc::new(RwLock::new(HashSet::new())),
        }
    }

    /// Add a variable definition
    pub async fn add_variable(&self, variable: CssVariable) -> Result<(), String> {
        let config = self.config.read().await;

        // Check document limit
        if config.max_documents > 0 {
            let tracked = self.tracked_documents.read().await;
            if tracked.contains(&variable.uri) {
                // Document already tracked, no limit check needed
            } else if tracked.len() >= config.max_documents {
                return Err(format!(
                    "Maximum document limit ({}) reached. Cannot add more documents.",
                    config.max_documents
                ));
            }
            drop(tracked);

            // Track this document
            let mut tracked = self.tracked_documents.write().await;
            tracked.insert(variable.uri.clone());
        }

        let mut vars = self.variables.write().await;
        vars.entry(variable.name.clone())
            .or_insert_with(Vec::new)
            .push(variable);

        Ok(())
    }

    /// Add a variable usage
    pub async fn add_usage(&self, usage: CssVariableUsage) {
        let mut usages = self.usages.write().await;
        usages
            .entry(usage.name.clone())
            .or_insert_with(Vec::new)
            .push(usage);
    }

    /// Add a literal color occurrence
    pub async fn add_literal_color(&self, occurrence: LiteralColorOccurrence) {
        let mut literal_colors = self.literal_colors.write().await;
        let line = occurrence.range.start.line;
        literal_colors
            .entry(occurrence.uri.clone())
            .or_default()
            .entry(line)
            .or_default()
            .push(occurrence);
    }

    /// Get all definitions of a variable
    pub async fn get_variables(&self, name: &str) -> Vec<CssVariable> {
        let vars = self.variables.read().await;
        vars.get(name).cloned().unwrap_or_default()
    }

    /// Get all usages of a variable
    pub async fn get_usages(&self, name: &str) -> Vec<CssVariableUsage> {
        let usages = self.usages.read().await;
        usages.get(name).cloned().unwrap_or_default()
    }

    /// Resolve a variable name to a color using cascade ordering and var() chains.
    pub async fn resolve_variable_color(&self, name: &str) -> Option<ls_types::Color> {
        self.resolve_variable_color_key(name)
            .await
            .map(color_from_key)
    }

    /// Resolve a variable name to a normalized color key using cascade ordering and var() chains.
    pub async fn resolve_variable_color_key(&self, name: &str) -> Option<NormalizedColorKey> {
        let vars = self.variables.read().await;
        resolve_variable_color_key_from_map(name, &vars)
    }

    /// Get all variables (for completion)
    pub async fn get_all_variables(&self) -> Vec<CssVariable> {
        let vars = self.variables.read().await;
        vars.values().flatten().cloned().collect()
    }

    /// Get all references (definitions + usages) for a variable
    pub async fn get_references(&self, name: &str) -> (Vec<CssVariable>, Vec<CssVariableUsage>) {
        let definitions = self.get_variables(name).await;
        let usages = self.get_usages(name).await;
        (definitions, usages)
    }

    /// Get literal color occurrences in a specific document.
    pub async fn get_document_literal_colors(&self, uri: &Uri) -> Vec<LiteralColorOccurrence> {
        let literal_colors = self.literal_colors.read().await;
        literal_colors
            .get(uri)
            .map(|by_line| by_line.values().flatten().cloned().collect())
            .unwrap_or_default()
    }

    /// Get literal color occurrences at a specific position (O(1) line lookup + O(k) scan).
    pub async fn get_literal_colors_at_position(
        &self,
        uri: &Uri,
        position: Position,
    ) -> Vec<LiteralColorOccurrence> {
        let literal_colors = self.literal_colors.read().await;
        literal_colors
            .get(uri)
            .and_then(|by_line| by_line.get(&position.line).cloned())
            .unwrap_or_default()
    }

    /// Get all variables whose resolved color exactly matches the normalized color key.
    pub async fn get_variables_by_color_key(&self, key: &NormalizedColorKey) -> Vec<CssVariable> {
        let names = {
            let index = self.color_variables.read().await;
            index.get(key).cloned().unwrap_or_default()
        };
        let vars = self.variables.read().await;
        let mut matches = Vec::new();
        for name in names {
            if let Some(definitions) = vars.get(&name) {
                let mut definitions = definitions.clone();
                sort_by_cascade(&mut definitions);
                if let Some(variable) = definitions.into_iter().next() {
                    matches.push(variable);
                }
            }
        }
        matches.sort_by(|a, b| a.name.cmp(&b.name));
        matches
    }

    /// Get the set of resolved variable colors currently defined in a specific document.
    pub async fn get_document_resolved_color_keys(&self, uri: &Uri) -> HashSet<NormalizedColorKey> {
        let names = self.get_document_variable_names(uri).await;
        let vars = self.variables.read().await;
        names
            .into_iter()
            .filter_map(|name| resolve_variable_color_key_from_map(&name, &vars))
            .collect()
    }

    /// Remove all data for a document
    pub async fn remove_document(&self, uri: &Uri) {
        let mut vars = self.variables.write().await;
        let mut usages = self.usages.write().await;
        let mut literal_colors = self.literal_colors.write().await;
        let mut dom_trees = self.dom_trees.write().await;
        let mut tracked = self.tracked_documents.write().await;

        // Remove from tracked documents
        tracked.remove(uri);

        // Remove variables from this document
        for (_, var_list) in vars.iter_mut() {
            var_list.retain(|v| &v.uri != uri);
        }
        vars.retain(|_, var_list| !var_list.is_empty());

        // Remove usages from this document
        for (_, usage_list) in usages.iter_mut() {
            usage_list.retain(|u| &u.uri != uri);
        }
        usages.retain(|_, usage_list| !usage_list.is_empty());

        literal_colors.remove(uri);
        dom_trees.remove(uri);

        // FIX: Rebuild color index to remove stale entries
        drop(vars);
        drop(usages);
        drop(literal_colors);
        drop(dom_trees);
        drop(tracked);
        self.rebuild_color_index().await;
    }

    /// Get all variables defined in a specific document
    pub async fn get_document_variables(&self, uri: &Uri) -> Vec<CssVariable> {
        let vars = self.variables.read().await;
        vars.values()
            .flatten()
            .filter(|v| &v.uri == uri)
            .cloned()
            .collect()
    }

    /// Get the set of variable names defined in a specific document
    pub async fn get_document_variable_names(&self, uri: &Uri) -> HashSet<String> {
        let vars = self.get_document_variables(uri).await;
        vars.into_iter().map(|v| v.name).collect()
    }

    /// Get all variable usages in a specific document
    pub async fn get_document_usages(&self, uri: &Uri) -> Vec<CssVariableUsage> {
        let usages = self.usages.read().await;
        usages
            .values()
            .flatten()
            .filter(|u| &u.uri == uri)
            .cloned()
            .collect()
    }

    /// Set DOM tree for a document
    pub async fn set_dom_tree(&self, uri: Uri, dom_tree: DomTree) {
        let mut dom_trees = self.dom_trees.write().await;
        dom_trees.insert(uri, dom_tree);
    }

    /// Get DOM tree for a document
    pub async fn get_dom_tree(&self, uri: &Uri) -> Option<DomTree> {
        let dom_trees = self.dom_trees.read().await;
        dom_trees.get(uri).cloned()
    }

    /// Get current configuration
    pub async fn get_config(&self) -> Config {
        self.config.read().await.clone()
    }

    /// Replace the current configuration.
    pub async fn set_config(&self, config: Config) {
        let mut stored = self.config.write().await;
        *stored = config;
    }

    /// Rebuild the normalized-color -> variable-name lookup from current workspace state.
    pub async fn rebuild_color_index(&self) {
        let snapshot = {
            let vars = self.variables.read().await;
            vars.clone()
        };

        let mut color_variables: HashMap<NormalizedColorKey, HashSet<String>> = HashMap::new();
        for name in snapshot.keys() {
            if let Some(key) = resolve_variable_color_key_from_map(name, &snapshot) {
                color_variables.entry(key).or_default().insert(name.clone());
            }
        }

        let mut stored = self.color_variables.write().await;
        *stored = color_variables;
    }
}

fn extract_var_reference(value: &str) -> Option<String> {
    let trimmed = value.trim();
    let start = trimmed.find("var(")?;
    let mut idx = start + 4;
    let bytes = trimmed.as_bytes();
    let mut depth = 1i32;
    while idx < bytes.len() {
        match bytes[idx] {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            _ => {}
        }
        idx += 1;
    }
    if depth != 0 {
        return None;
    }

    let inner = trimmed[start + 4..idx].trim_start();
    let inner = inner.strip_prefix("--")?;
    let mut name_len = 0usize;
    for ch in inner.chars() {
        if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
            name_len += ch.len_utf8();
        } else {
            break;
        }
    }
    if name_len == 0 {
        return None;
    }
    Some(format!("--{}", &inner[..name_len]))
}

fn resolve_variable_color_key_from_map(
    name: &str,
    variables: &HashMap<String, Vec<CssVariable>>,
) -> Option<NormalizedColorKey> {
    let mut seen = HashSet::new();
    let mut current = name.to_string();

    loop {
        if seen.contains(&current) {
            return None;
        }
        seen.insert(current.clone());

        let mut definitions = variables.get(&current)?.clone();
        if definitions.is_empty() {
            return None;
        }

        sort_by_cascade(&mut definitions);
        let variable = &definitions[0];

        if let Some(next_name) = extract_var_reference(&variable.value) {
            current = next_name;
            continue;
        }

        return parse_color(&variable.value).map(normalize_color);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ls_types::{Position, Range, Uri};
    use std::str::FromStr;

    fn create_test_variable(name: &str, value: &str, selector: &str, uri: &str) -> CssVariable {
        CssVariable {
            name: name.to_string(),
            value: value.to_string(),
            selector: selector.to_string(),
            range: Range::new(Position::new(0, 0), Position::new(0, 10)),
            name_range: None,
            value_range: None,
            uri: Uri::from_str(uri).unwrap(),
            important: false,
            inline: false,
            source_position: 0,
        }
    }

    fn create_test_usage(name: &str, context: &str, uri: &str) -> CssVariableUsage {
        CssVariableUsage {
            name: name.to_string(),
            range: Range::new(Position::new(0, 0), Position::new(0, 10)),
            name_range: None,
            uri: Uri::from_str(uri).unwrap(),
            usage_context: context.to_string(),
            dom_node: None,
        }
    }

    fn create_literal_color(
        text: &str,
        uri: &str,
        color: &str,
        context: &str,
    ) -> LiteralColorOccurrence {
        LiteralColorOccurrence {
            text: text.to_string(),
            uri: Uri::from_str(uri).unwrap(),
            range: Range::new(Position::new(0, 0), Position::new(0, text.len() as u32)),
            usage_context: context.to_string(),
            normalized_color: crate::color::normalized_color_key(color).unwrap(),
        }
    }

    #[test]
    fn extract_var_reference_allows_fallbacks_and_trailing_tokens() {
        assert_eq!(
            extract_var_reference("var(--primary, #fff)"),
            Some("--primary".to_string())
        );
        assert_eq!(
            extract_var_reference("var(--primary) !important"),
            Some("--primary".to_string())
        );
        assert_eq!(
            extract_var_reference("calc(1px + var(--spacing))"),
            Some("--spacing".to_string())
        );
    }

    #[tokio::test]
    async fn test_manager_add_and_get_variables() {
        let manager = CssVariableManager::new(Config::default());
        let var = create_test_variable("--primary", "#3b82f6", ":root", "file:///test.css");

        manager
            .add_variable(var.clone())
            .await
            .expect("add_variable failed");

        let variables = manager.get_variables("--primary").await;
        assert_eq!(variables.len(), 1);
        assert_eq!(variables[0].name, "--primary");
        assert_eq!(variables[0].value, "#3b82f6");
    }

    #[tokio::test]
    async fn test_manager_multiple_definitions() {
        let manager = CssVariableManager::new(Config::default());

        let var1 = create_test_variable("--color", "red", ":root", "file:///test.css");
        let var2 = create_test_variable("--color", "blue", ".class", "file:///test.css");

        manager
            .add_variable(var1)
            .await
            .expect("add_variable failed");
        manager
            .add_variable(var2)
            .await
            .expect("add_variable failed");

        let variables = manager.get_variables("--color").await;
        assert_eq!(variables.len(), 2);
    }

    #[tokio::test]
    async fn test_manager_add_and_get_usages() {
        let manager = CssVariableManager::new(Config::default());
        let usage = create_test_usage("--primary", ".button", "file:///test.css");

        manager.add_usage(usage.clone()).await;

        let usages = manager.get_usages("--primary").await;
        assert_eq!(usages.len(), 1);
        assert_eq!(usages[0].name, "--primary");
        assert_eq!(usages[0].usage_context, ".button");
    }

    #[tokio::test]
    async fn test_manager_get_references() {
        let manager = CssVariableManager::new(Config::default());

        let var = create_test_variable("--spacing", "1rem", ":root", "file:///test.css");
        let usage = create_test_usage("--spacing", ".card", "file:///test.css");

        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");
        manager.add_usage(usage).await;

        let (defs, usages) = manager.get_references("--spacing").await;
        assert_eq!(defs.len(), 1);
        assert_eq!(usages.len(), 1);
    }

    #[tokio::test]
    async fn test_manager_remove_document() {
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();

        let var = create_test_variable("--primary", "blue", ":root", "file:///test.css");
        let usage = create_test_usage("--primary", ".button", "file:///test.css");
        let literal = create_literal_color("blue", "file:///test.css", "blue", ".button");

        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");
        manager.add_usage(usage).await;
        manager.add_literal_color(literal).await;

        // Verify they exist
        assert_eq!(manager.get_variables("--primary").await.len(), 1);
        assert_eq!(manager.get_usages("--primary").await.len(), 1);
        assert_eq!(manager.get_document_literal_colors(&uri).await.len(), 1);

        // Remove document
        manager.remove_document(&uri).await;

        // Verify they're gone
        assert_eq!(manager.get_variables("--primary").await.len(), 0);
        assert_eq!(manager.get_usages("--primary").await.len(), 0);
        assert_eq!(manager.get_document_literal_colors(&uri).await.len(), 0);
    }

    #[tokio::test]
    async fn test_manager_get_all_variables() {
        let manager = CssVariableManager::new(Config::default());

        manager
            .add_variable(create_test_variable(
                "--primary",
                "blue",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--secondary",
                "red",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--spacing",
                "1rem",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");

        let all_vars = manager.get_all_variables().await;
        assert_eq!(all_vars.len(), 3);
    }

    #[tokio::test]
    async fn test_manager_resolve_variable_color() {
        let manager = CssVariableManager::new(Config::default());

        let var = create_test_variable("--primary-color", "#3b82f6", ":root", "file:///test.css");
        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");

        let color = manager.resolve_variable_color("--primary-color").await;
        assert!(color.is_some());
    }

    #[tokio::test]
    async fn test_manager_resolve_variable_color_key_chain() {
        let manager = CssVariableManager::new(Config::default());

        manager
            .add_variable(create_test_variable(
                "--base-color",
                "#fff",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--alias-color",
                "var(--base-color)",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");

        let key = manager.resolve_variable_color_key("--alias-color").await;
        assert_eq!(key, crate::color::normalized_color_key("white"));
    }

    #[tokio::test]
    async fn test_manager_get_variables_by_color_key_excludes_non_colors() {
        let manager = CssVariableManager::new(Config::default());

        manager
            .add_variable(create_test_variable(
                "--spacing",
                "1rem",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--text-color",
                "#fff",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");

        manager.rebuild_color_index().await;

        let matches = manager
            .get_variables_by_color_key(&crate::color::normalized_color_key("white").unwrap())
            .await;
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].name, "--text-color");
    }

    #[tokio::test]
    async fn test_manager_get_variables_by_color_key_multiple_names() {
        let manager = CssVariableManager::new(Config::default());

        manager
            .add_variable(create_test_variable(
                "--text-color",
                "#fff",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--surface",
                "rgb(255 255 255)",
                ":root",
                "file:///test.css",
            ))
            .await
            .expect("add_variable failed");

        manager.rebuild_color_index().await;

        let matches = manager
            .get_variables_by_color_key(&crate::color::normalized_color_key("white").unwrap())
            .await;
        assert_eq!(matches.len(), 2);
        assert!(matches.iter().any(|var| var.name == "--surface"));
        assert!(matches.iter().any(|var| var.name == "--text-color"));
    }

    #[tokio::test]
    async fn test_manager_cross_file_references() {
        let manager = CssVariableManager::new(Config::default());

        // Variable defined in one file
        let var = create_test_variable("--theme", "dark", ":root", "file:///variables.css");
        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");

        // Used in another file
        let usage = create_test_usage("--theme", ".app", "file:///app.css");
        manager.add_usage(usage).await;

        let (defs, usages) = manager.get_references("--theme").await;
        assert_eq!(defs.len(), 1);
        assert_eq!(usages.len(), 1);
        assert_ne!(defs[0].uri, usages[0].uri);
    }

    #[tokio::test]
    async fn test_manager_document_isolation() {
        let manager = CssVariableManager::new(Config::default());
        let uri1 = Uri::from_str("file:///file1.css").unwrap();
        let _uri2 = Uri::from_str("file:///file2.css").unwrap();

        manager
            .add_variable(create_test_variable(
                "--color",
                "red",
                ":root",
                "file:///file1.css",
            ))
            .await
            .expect("add_variable failed");
        manager
            .add_variable(create_test_variable(
                "--color",
                "blue",
                ":root",
                "file:///file2.css",
            ))
            .await
            .expect("add_variable failed");

        // Should have both definitions
        assert_eq!(manager.get_variables("--color").await.len(), 2);

        // Remove one document
        manager.remove_document(&uri1).await;

        // Should only have one definition now
        let vars = manager.get_variables("--color").await;
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].value, "blue");
    }

    #[tokio::test]
    async fn test_manager_color_index_stale_after_remove() {
        // Regression test: color_variables becomes stale after remove_document()
        // when rebuild_color_index() is not called
        let manager = CssVariableManager::new(Config::default());
        let uri = Uri::from_str("file:///test.css").unwrap();
        let white_key = crate::color::normalized_color_key("white").unwrap();

        // Add a color variable and build the index
        let var = create_test_variable("--bg", "#ffffff", ":root", "file:///test.css");
        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");
        manager.rebuild_color_index().await;

        // Verify it's indexed
        assert_eq!(
            manager.get_variables_by_color_key(&white_key).await.len(),
            1,
            "Variable should be indexed by color"
        );

        // Remove document WITHOUT rebuilding index (simulates the bug)
        manager.remove_document(&uri).await;

        // After removal, the variable should be gone from both collections
        assert_eq!(
            manager.get_variables("--bg").await.len(),
            0,
            "Variable should be removed from variables map"
        );

        // The bug: color_variables still contains the stale entry,
        // but get_variables_by_color_key() silently skips names not found in variables.
        // This test verifies the current (buggy) behavior - returns 0 matches.
        let color_matches = manager.get_variables_by_color_key(&white_key).await;
        assert_eq!(
            color_matches.len(),
            0,
            "BUG: color index is stale, returns 0 instead of correctly handling removal"
        );

        // Workaround: manually rebuild to get correct behavior
        manager.rebuild_color_index().await;
        assert_eq!(
            manager.get_variables_by_color_key(&white_key).await.len(),
            0,
            "After rebuild, color index is correct"
        );
    }

    // Note: extract_var_name is not a public function, so we skip testing it directly

    #[tokio::test]
    async fn test_manager_important_flag() {
        let manager = CssVariableManager::new(Config::default());

        let mut var = create_test_variable("--color", "red", ":root", "file:///test.css");
        var.important = true;

        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");

        let vars = manager.get_variables("--color").await;
        assert_eq!(vars.len(), 1);
        assert!(vars[0].important);
    }

    #[tokio::test]
    async fn test_manager_inline_flag() {
        let manager = CssVariableManager::new(Config::default());

        let mut var = create_test_variable(
            "--inline-color",
            "green",
            "inline-style",
            "file:///test.html",
        );
        var.inline = true;

        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");

        let vars = manager.get_variables("--inline-color").await;
        assert_eq!(vars.len(), 1);
        assert!(vars[0].inline);
    }

    #[tokio::test]
    async fn test_manager_empty_queries() {
        let manager = CssVariableManager::new(Config::default());

        // Query for non-existent variable
        let vars = manager.get_variables("--does-not-exist").await;
        assert_eq!(vars.len(), 0);

        let usages = manager.get_usages("--does-not-exist").await;
        assert_eq!(usages.len(), 0);

        let (defs, usages) = manager.get_references("--does-not-exist").await;
        assert_eq!(defs.len(), 0);
        assert_eq!(usages.len(), 0);
    }

    /// Memory limit enforcement in CssVariableManager
    ///
    /// ISSUE: The manager uses unbounded HashMaps that can grow indefinitely.
    /// Large workspaces could accumulate many documents without cleanup.
    ///
    /// After fix: Should have a document limit enforced.
    #[tokio::test]
    async fn test_manager_has_memory_limits() {
        use ls_types::{Position, Range};
        use std::str::FromStr;

        let config = Config {
            max_documents: 100,
            ..Default::default()
        };

        let manager = CssVariableManager::new(config);

        // Try to add 200 documents (beyond the limit of 100)
        let mut success_count = 0;
        let mut failure_count = 0;

        for i in 0..200 {
            let var = CssVariable {
                name: format!("--var-{}", i),
                value: "red".to_string(),
                selector: ":root".to_string(),
                range: Range::new(Position::new(0, 0), Position::new(0, 10)),
                name_range: None,
                value_range: None,
                uri: Uri::from_str(&format!("file:///test/doc_{}.css", i)).unwrap(),
                important: false,
                inline: false,
                source_position: 0,
            };

            match manager.add_variable(var).await {
                Ok(()) => success_count += 1,
                Err(_) => failure_count += 1,
            }
        }

        // Verify the limit was enforced
        assert_eq!(
            success_count, 100,
            "Should successfully add exactly 100 documents (the limit)"
        );
        assert_eq!(
            failure_count, 100,
            "Should fail to add the remaining 100 documents beyond the limit"
        );

        // Check how many documents are actually stored
        let vars = manager.variables.read().await;
        assert!(
            vars.len() <= 100,
            "Manager should not have more than 100 documents, but has {}",
            vars.len()
        );
    }
    /// Bug demonstration: Color index can be stale during concurrent access
    ///
    /// ISSUE: rebuild_color_index() reads from variables and writes to color_variables.
    /// While individual operations are atomic, there's a brief window where the
    /// color index could be stale during concurrent updates.
    ///
    /// EXPECTED TO FAIL: This test proves the race condition exists.
    /// After fix: Color index should be properly synchronized.
    #[tokio::test]
    async fn test_manager_color_index_concurrent_consistency() {
        use ls_types::{Position, Range};
        use std::str::FromStr;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let config = Config::default();
        let manager = CssVariableManager::new(config);

        // Track inconsistencies between color index and variables
        let inconsistencies = Arc::new(AtomicUsize::new(0));

        // Add initial color variables
        let var = CssVariable {
            name: "--color-primary".to_string(),
            value: "#ff0000".to_string(),
            selector: ":root".to_string(),
            range: Range::new(Position::new(0, 0), Position::new(0, 10)),
            name_range: None,
            value_range: None,
            uri: Uri::from_str("file:///test/colors.css").unwrap(),
            important: false,
            inline: false,
            source_position: 0,
        };
        manager
            .add_variable(var)
            .await
            .expect("add_variable failed");
        manager.rebuild_color_index().await;

        // Spawn concurrent readers and writers
        let mut handles = vec![];

        // Writer: Continuously add color variables
        for i in 0..100 {
            let manager_clone = manager.clone();
            handles.push(tokio::spawn(async move {
                let var = CssVariable {
                    name: format!("--color-{}", i),
                    value: format!("hsl({}, 100%, 50%)", i * 3),
                    selector: ":root".to_string(),
                    range: Range::new(Position::new(0, 0), Position::new(0, 10)),
                    name_range: None,
                    value_range: None,
                    uri: Uri::from_str(&format!("file:///test/color_{}.css", i)).unwrap(),
                    important: false,
                    inline: false,
                    source_position: 0,
                };
                manager_clone
                    .add_variable(var)
                    .await
                    .expect("add_variable failed");
                // Rebuild index after each add to simulate real usage
                manager_clone.rebuild_color_index().await;
            }));
        }

        // Reader: Continuously check color index consistency
        let inconsistencies_clone = inconsistencies.clone();
        let manager_reader = manager.clone();
        handles.push(tokio::spawn(async move {
            for _ in 0..50 {
                // Get all variables
                let all_vars = manager_reader.get_all_variables().await;

                // Count color variables by checking if they have color values
                let color_count = all_vars
                    .iter()
                    .filter(|v| crate::color::parse_color(&v.value).is_some())
                    .count();

                // Rebuild and check the color index
                manager_reader.rebuild_color_index().await;

                // Get variables by a sample color key
                let white_key = crate::color::normalized_color_key("white").unwrap();
                let white_matches = manager_reader.get_variables_by_color_key(&white_key).await;

                // If the counts are wildly different, there's an inconsistency
                // (This is a simplified check - real race conditions are harder to detect)
                if white_matches.len() > color_count + 10 {
                    inconsistencies_clone.fetch_add(1, Ordering::SeqCst);
                }

                tokio::time::sleep(tokio::time::Duration::from_micros(1)).await;
            }
        }));

        // Wait for all operations
        for handle in handles {
            let _ = handle.await;
        }

        // BUG: Currently this assertion will FAIL because race condition exists
        // The color index may be temporarily stale during concurrent updates
        // After fix: inconsistencies should be 0
        assert_eq!(
            inconsistencies.load(Ordering::SeqCst),
            0,
            "Color index had {} inconsistencies during concurrent access",
            inconsistencies.load(Ordering::SeqCst)
        );
    }
}