mcp-cpp-server 0.2.2

A high-performance Model Context Protocol (MCP) server for C++ code analysis using clangd LSP integration
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
//! Document symbols extraction functionality for C++ files
//!
//! This module provides LSP-based document symbol extraction that works with
//! clangd to get hierarchical symbol information from C++ files. Expects only
//! nested (hierarchical) responses due to client capabilities configuration.

use crate::clangd::session::ClangdSessionTrait;
use lsp_types::{DocumentSymbol, DocumentSymbolResponse, Position, Range};
use std::collections::VecDeque;
use std::path::Path;
use sublime_fuzzy::best_match;
use tracing::{trace, warn};

use crate::lsp::traits::LspClientTrait;
use crate::mcp_server::tools::analyze_symbols::AnalyzerError;
use crate::project::component_session::ComponentSession;
use crate::symbol::uri_from_pathbuf;

// Fuzzy matching threshold - accept all positive scores
const FUZZY_MATCH_THRESHOLD: isize = 0;

// ============================================================================
// SymbolContext - Rich symbol information with container hierarchy
// ============================================================================

/// Rich symbol context containing DocumentSymbol and container hierarchy
#[derive(Debug, Clone)]
pub struct SymbolContext {
    /// The LSP DocumentSymbol with full AST information
    pub document_symbol: lsp_types::DocumentSymbol,
    /// Container hierarchy path (e.g., ["Math", "Complex"] for Math::Complex::add)
    #[allow(dead_code)]
    pub container_path: Vec<String>,
}

/// Symbol match with fuzzy matching score
#[derive(Debug, Clone)]
struct ScoredSymbol<'a> {
    symbol: &'a DocumentSymbol,
    score: isize,
}

// ============================================================================
// Traits for Idiomatic Symbol Tree Operations
// ============================================================================

/// Trait for types that can check if they contain a position
pub trait PositionContains {
    /// Check if this range/symbol contains the given Position
    fn contains(&self, position: &Position) -> bool;
}

impl PositionContains for Range {
    fn contains(&self, position: &Position) -> bool {
        (position.line > self.start.line
            || (position.line == self.start.line && position.character >= self.start.character))
            && (position.line < self.end.line
                || (position.line == self.end.line && position.character <= self.end.character))
    }
}

impl PositionContains for DocumentSymbol {
    fn contains(&self, position: &Position) -> bool {
        self.selection_range.contains(position)
    }
}

/// Trait for symbol matching strategies - extensible for future use
#[allow(dead_code)]
pub trait SymbolMatcher {
    fn matches(&self, symbol: &DocumentSymbol) -> bool;
}

/// Specialized matcher for class member symbols with filtering capabilities
#[allow(dead_code)]
pub struct MemberMatcher {
    /// Target class name to extract members from
    pub class_name: String,
    /// Optional filter by member kinds (method, constructor, etc.)
    pub member_kinds: Option<Vec<lsp_types::SymbolKind>>,
    /// Filter for static methods only
    pub static_only: bool,
}

#[allow(dead_code)]
impl MemberMatcher {
    /// Create a new member matcher for the specified class
    pub fn for_class(class_name: &str) -> Self {
        Self {
            class_name: class_name.to_string(),
            member_kinds: None,
            static_only: false,
        }
    }

    /// Filter by specific member kinds (METHOD, CONSTRUCTOR, etc.)
    pub fn with_kinds(mut self, kinds: Vec<lsp_types::SymbolKind>) -> Self {
        self.member_kinds = Some(kinds);
        self
    }

    /// Filter for static methods only
    pub fn static_only(mut self) -> Self {
        self.static_only = true;
        self
    }

    /// Check if a symbol represents a callable member
    fn is_callable_member(symbol: &DocumentSymbol) -> bool {
        matches!(
            symbol.kind,
            lsp_types::SymbolKind::METHOD
                | lsp_types::SymbolKind::FUNCTION
                | lsp_types::SymbolKind::CONSTRUCTOR
        )
    }

    /// Determine if this is a static method based on symbol detail
    fn is_static_method(symbol: &DocumentSymbol) -> bool {
        if let Some(detail) = &symbol.detail {
            detail.contains("static") || detail.starts_with("static ")
        } else {
            false
        }
    }
}

impl SymbolMatcher for MemberMatcher {
    fn matches(&self, symbol: &DocumentSymbol) -> bool {
        // Only match callable members
        if !Self::is_callable_member(symbol) {
            return false;
        }

        // Filter by member kinds if specified
        if let Some(ref kinds) = self.member_kinds
            && !kinds.contains(&symbol.kind)
        {
            return false;
        }

        // Filter for static methods if requested
        if self.static_only && !Self::is_static_method(symbol) {
            return false;
        }

        true
    }
}

// ============================================================================
// Iterator for Tree Traversal
// ============================================================================

/// Iterator over document symbols with path context
pub struct DocumentSymbolIterator<'a> {
    stack: VecDeque<(&'a DocumentSymbol, Vec<&'a str>)>,
}

impl<'a> DocumentSymbolIterator<'a> {
    /// Create a new iterator starting from root symbols
    pub fn new(symbols: &'a [DocumentSymbol]) -> Self {
        let mut stack = VecDeque::new();
        for symbol in symbols {
            stack.push_back((symbol, vec![]));
        }
        Self { stack }
    }

    /// Create iterator with depth-first traversal order
    #[allow(dead_code)]
    pub fn depth_first(symbols: &'a [DocumentSymbol]) -> Self {
        Self::new(symbols)
    }

    /// Create iterator with breadth-first traversal order
    #[allow(dead_code)]
    pub fn breadth_first(symbols: &'a [DocumentSymbol]) -> Self {
        let mut stack = VecDeque::new();
        for symbol in symbols {
            stack.push_front((symbol, vec![]));
        }
        Self { stack }
    }
}

impl<'a> Iterator for DocumentSymbolIterator<'a> {
    type Item = (&'a DocumentSymbol, Vec<&'a str>);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some((symbol, path)) = self.stack.pop_front() {
            // Add children to stack for future iteration (depth-first by default)
            if let Some(children) = &symbol.children {
                let mut new_path = path.clone();
                new_path.push(&symbol.name);

                // Insert children in reverse order for depth-first (or normal order for breadth-first)
                for child in children.iter().rev() {
                    self.stack.push_front((child, new_path.clone()));
                }
            }

            Some((symbol, path))
        } else {
            None
        }
    }
}

// ============================================================================
// Symbol Search Builder
// ============================================================================

/// Builder pattern for flexible symbol searching
#[derive(Debug, Clone)]
pub struct SymbolSearchBuilder {
    position: Option<Position>,
    name: Option<String>,
    kind: Option<lsp_types::SymbolKind>,
    kinds: Option<Vec<lsp_types::SymbolKind>>,
    path_contains: Option<String>,
}

impl SymbolSearchBuilder {
    /// Create a new search builder
    pub fn new() -> Self {
        Self {
            position: None,
            name: None,
            kind: None,
            kinds: None,
            path_contains: None,
        }
    }

    /// Search for symbol at specific position
    pub fn at_position(mut self, position: Position) -> Self {
        self.position = Some(position);
        self
    }

    /// Search for symbol by name
    pub fn with_name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Search for symbol by kind
    pub fn with_kind(mut self, kind: lsp_types::SymbolKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// Search for symbols matching any of the given kinds
    pub fn with_kinds(mut self, kinds: &[lsp_types::SymbolKind]) -> Self {
        // Store the kinds for proper matching in matches_symbol
        self.kinds = Some(kinds.to_vec());
        self
    }

    /// Search for symbols whose path contains the given string
    #[allow(dead_code)]
    pub fn path_contains<S: Into<String>>(mut self, path_part: S) -> Self {
        self.path_contains = Some(path_part.into());
        self
    }

    /// Find the first matching symbol (highest scoring match)
    pub fn find_first(self, symbols: &[DocumentSymbol]) -> Option<&DocumentSymbol> {
        // Use find_all to get sorted results, then take the first (best)
        let results = self.find_all(symbols);
        results.first().copied()
    }

    /// Find all matching symbols, sorted by fuzzy match score (best first)
    pub fn find_all(self, symbols: &[DocumentSymbol]) -> Vec<&DocumentSymbol> {
        let mut scored_matches: Vec<ScoredSymbol> = DocumentSymbolIterator::new(symbols)
            .filter_map(|(symbol, path)| {
                // Check all criteria first
                if !self.matches_symbol(symbol, &path) {
                    return None;
                }
                // Get fuzzy score for sorting
                self.fuzzy_match_score(symbol)
                    .map(|score| ScoredSymbol { symbol, score })
            })
            .collect();

        // Sort by score (highest first)
        scored_matches.sort_by(|a, b| b.score.cmp(&a.score));

        // Return just the symbols
        scored_matches
            .into_iter()
            .map(|scored| scored.symbol)
            .collect()
    }

    /// Filter for class members only (methods, constructors, operators)
    #[allow(dead_code)]
    pub fn class_members_only(mut self) -> Self {
        self.kind = None; // Reset single kind filter
        self
    }

    /// Filter for static methods only
    #[allow(dead_code)]
    pub fn static_methods_only(mut self) -> Self {
        self.kind = Some(lsp_types::SymbolKind::METHOD);
        self
    }

    /// Filter for constructors only
    #[allow(dead_code)]
    pub fn constructors_only(mut self) -> Self {
        self.kind = Some(lsp_types::SymbolKind::CONSTRUCTOR);
        self
    }

    /// Filter for methods within a specific class (by path)
    #[allow(dead_code)]
    pub fn methods_in_class<S: Into<String>>(mut self, class_name: S) -> Self {
        let class_name = class_name.into();
        self.path_contains = Some(class_name.clone());
        self.kind = Some(lsp_types::SymbolKind::METHOD);
        self
    }

    /// Search across multiple files for symbols matching criteria
    pub async fn search_multiple_files(
        self,
        component_session: &ComponentSession,
        files: &[String],
        max_results: Option<u32>,
    ) -> Result<Vec<(String, Vec<DocumentSymbol>)>, AnalyzerError> {
        let mut file_results = Vec::new();

        for file_path in files {
            match self.search_single_file(component_session, file_path).await {
                Ok(symbols) => {
                    file_results.push((file_path.clone(), symbols));
                }
                Err(e) => {
                    trace!("Failed to search file {}: {}", file_path, e);
                    file_results.push((file_path.clone(), Vec::new()));
                }
            }
        }

        // Apply top-level limiting if specified
        if let Some(max) = max_results {
            let mut all_symbols = Vec::new();
            for (file_path, symbols) in &file_results {
                for symbol in symbols {
                    all_symbols.push((file_path.clone(), symbol.clone()));
                    if all_symbols.len() >= max as usize {
                        break;
                    }
                }
                if all_symbols.len() >= max as usize {
                    break;
                }
            }

            // Reconstruct file_results with limited symbols
            let mut limited_results = Vec::new();
            let mut current_file = String::new();
            let mut current_symbols = Vec::new();

            for (file_path, symbol) in all_symbols {
                if file_path != current_file {
                    if !current_file.is_empty() {
                        limited_results.push((current_file.clone(), current_symbols));
                        current_symbols = Vec::new();
                    }
                    current_file = file_path;
                }
                current_symbols.push(symbol);
            }

            if !current_file.is_empty() {
                limited_results.push((current_file, current_symbols));
            }

            Ok(limited_results)
        } else {
            Ok(file_results)
        }
    }

    /// Search a single file for symbols matching criteria  
    async fn search_single_file(
        &self,
        component_session: &ComponentSession,
        file_path: &str,
    ) -> Result<Vec<DocumentSymbol>, AnalyzerError> {
        trace!(
            "Searching single file: {} with criteria: {:?}",
            file_path, self
        );

        let file_uri = if file_path.starts_with("file://") {
            file_path
                .parse()
                .map_err(|e| AnalyzerError::NoData(format!("Invalid URI: {}", e)))?
        } else {
            uri_from_pathbuf(Path::new(file_path))
        };

        trace!("Getting document symbols for URI: {:?}", file_uri);
        let document_symbols = get_document_symbols(component_session, file_uri).await?;
        trace!("Found {} document symbols", document_symbols.len());

        let filtered_symbols: Vec<DocumentSymbol> = self
            .clone()
            .find_all(&document_symbols)
            .into_iter()
            .cloned()
            .collect();

        trace!(
            "After filtering: {} symbols match criteria",
            filtered_symbols.len()
        );
        Ok(filtered_symbols)
    }

    /// Get fuzzy match score for a symbol, returns None if no match
    fn fuzzy_match_score(&self, symbol: &DocumentSymbol) -> Option<isize> {
        if let Some(ref name) = self.name {
            if let Some(fuzzy_match) = best_match(name, &symbol.name)
                && fuzzy_match.score() >= FUZZY_MATCH_THRESHOLD
            {
                return Some(fuzzy_match.score());
            }
            None
        } else {
            // If no name filter, return a default score
            Some(0)
        }
    }

    /// Check if a symbol matches the search criteria
    fn matches_symbol(&self, symbol: &DocumentSymbol, path: &[&str]) -> bool {
        trace!(
            "Checking symbol '{}' (kind: {:?}) against criteria: {:?}",
            symbol.name, symbol.kind, self
        );

        // Position matching
        if let Some(ref position) = self.position
            && !symbol.contains(position)
        {
            trace!("Symbol '{}' rejected: position mismatch", symbol.name);
            return false;
        }

        // Name matching - use fuzzy matching
        if let Some(ref name) = self.name {
            if let Some(fuzzy_match) = best_match(name, &symbol.name) {
                if fuzzy_match.score() < FUZZY_MATCH_THRESHOLD {
                    trace!(
                        "Symbol '{}' rejected: fuzzy match score {} below threshold {}",
                        symbol.name,
                        fuzzy_match.score(),
                        FUZZY_MATCH_THRESHOLD
                    );
                    return false;
                }
                trace!(
                    "Symbol '{}' accepted: fuzzy match score {}",
                    symbol.name,
                    fuzzy_match.score()
                );
            } else {
                trace!(
                    "Symbol '{}' rejected: no fuzzy match found for query '{}'",
                    symbol.name, name
                );
                return false;
            }
        }

        // Kind matching - support both single kind and multiple kinds
        if let Some(kind) = self.kind {
            if symbol.kind != kind {
                trace!(
                    "Symbol '{}' rejected: kind {:?} != {:?}",
                    symbol.name, symbol.kind, kind
                );
                return false;
            }
        } else if let Some(ref kinds) = self.kinds
            && !kinds.contains(&symbol.kind)
        {
            trace!(
                "Symbol '{}' rejected: kind {:?} not in {:?}",
                symbol.name, symbol.kind, kinds
            );
            return false;
        }

        // Path matching
        if let Some(ref path_contains) = self.path_contains {
            let full_path = path.join("::");
            if !full_path.contains(path_contains) {
                trace!(
                    "Symbol '{}' rejected: path '{}' does not contain '{}'",
                    symbol.name, full_path, path_contains
                );
                return false;
            }
        }

        // Additional class member filtering for class_members_only
        if self.kind.is_none() && self.path_contains.is_some() {
            // When class_members_only is used, filter for callable members
            if !matches!(
                symbol.kind,
                lsp_types::SymbolKind::METHOD
                    | lsp_types::SymbolKind::FUNCTION
                    | lsp_types::SymbolKind::CONSTRUCTOR
            ) {
                trace!(
                    "Symbol '{}' rejected: class_members_only filter - not a callable member",
                    symbol.name
                );
                return false;
            }
        }

        trace!("Symbol '{}' matches criteria", symbol.name);
        true
    }
}

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

// ============================================================================
// Public API
// ============================================================================

/// Get document symbols for a symbol and find the matching DocumentSymbol
///
/// This function retrieves document symbols for the file containing the symbol,
/// then searches the hierarchical structure to find the matching DocumentSymbol
/// based on the symbol's name and location.
///
/// # Arguments
/// * `session` - Active clangd session
/// * `symbol_name` - Name of the symbol to find
/// * `symbol_location` - Location of the symbol
///
/// Get document symbols for a file URI, returning only hierarchical symbols
///
/// This function calls the LSP `textDocument/documentSymbol` method and expects
/// a hierarchical response due to our client capabilities. If a flat response
/// is received, it logs a warning and returns an error.
///
/// # Arguments
/// * `component_session` - Active component session
/// * `file_uri` - URI of the file to analyze
///
/// # Returns
/// * `Ok(Vec<DocumentSymbol>)` - Hierarchical document symbols
/// * `Err(AnalyzerError)` - LSP error or unexpected flat response
pub async fn get_document_symbols(
    component_session: &ComponentSession,
    file_uri: lsp_types::Uri,
) -> Result<Vec<DocumentSymbol>, AnalyzerError> {
    trace!("Requesting document symbols for URI: {:?}", file_uri);

    // Ensure file is ready
    let uri_str = file_uri.to_string();
    let file_path_str = uri_str.strip_prefix("file://").unwrap_or(&uri_str);

    component_session
        .ensure_file_ready(Path::new(file_path_str))
        .await?;

    let mut session = component_session.lsp_session().await;
    let client = session.client_mut();

    // Get document symbols from LSP
    let document_symbols = client
        .text_document_document_symbol(file_uri.clone())
        .await
        .map_err(AnalyzerError::from)?;

    trace!(
        "Document symbols response type: {:?}",
        match &document_symbols {
            DocumentSymbolResponse::Nested(_) => "Nested (hierarchical)",
            DocumentSymbolResponse::Flat(_) => "Flat (legacy)",
        }
    );

    // Extract hierarchical symbols or warn about flat response
    match document_symbols {
        DocumentSymbolResponse::Nested(nested_symbols) => {
            trace!(
                "Successfully received {} top-level hierarchical symbols",
                nested_symbols.len()
            );
            Ok(nested_symbols)
        }
        DocumentSymbolResponse::Flat(flat_symbols) => {
            warn!(
                "Received flat document symbols response for '{:?}' despite hierarchical support enabled. \
                 This is unexpected and may indicate a clangd configuration issue. \
                 Flat response contains {} symbols.",
                file_uri,
                flat_symbols.len()
            );
            Err(AnalyzerError::NoData(format!(
                "Unexpected flat document symbols response for '{:?}' despite hierarchical client capability. Expected nested DocumentSymbol format.",
                file_uri
            )))
        }
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Find a specific symbol within the hierarchical document symbols using position
///
/// This is a convenience function that uses the builder pattern internally.
/// For more complex searches, use `SymbolSearchBuilder` directly.
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols to search
/// * `target_line` - Target line number (0-based)
/// * `target_character` - Target character position (0-based)
///
/// # Returns
/// * `Some(&DocumentSymbol)` - Found symbol reference
/// * `None` - No symbol found at the target position
#[allow(dead_code)]
pub fn find_symbol_at_position<'a>(
    symbols: &'a [DocumentSymbol],
    position: &Position,
) -> Option<&'a DocumentSymbol> {
    SymbolSearchBuilder::new()
        .at_position(*position)
        .find_first(symbols)
}

/// Find symbol at position with container hierarchy path
pub fn find_symbol_at_position_with_path<'a>(
    symbols: &'a [DocumentSymbol],
    position: &Position,
) -> Option<(&'a DocumentSymbol, Vec<String>)> {
    find_symbol_recursive_with_path(symbols, position, Vec::new())
}

/// Recursive helper for path-aware symbol finding
fn find_symbol_recursive_with_path<'a>(
    symbols: &'a [DocumentSymbol],
    position: &Position,
    current_path: Vec<String>,
) -> Option<(&'a DocumentSymbol, Vec<String>)> {
    for symbol in symbols {
        if symbol.range.contains(position) {
            // Check children first for most specific match
            if let Some(children) = &symbol.children {
                let mut child_path = current_path.clone();
                child_path.push(symbol.name.clone());

                if let Some(result) =
                    find_symbol_recursive_with_path(children, position, child_path)
                {
                    return Some(result);
                }
            }
            // No more specific child found, this is the target
            return Some((symbol, current_path));
        }
    }
    None
}

/// Find symbols by name using idiomatic iterator approach
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols to search
/// * `name` - Symbol name to search for
///
/// # Returns
/// * `Vec<&DocumentSymbol>` - All symbols with matching name
#[allow(dead_code)]
pub fn find_symbols_by_name<'a>(
    symbols: &'a [DocumentSymbol],
    name: &str,
) -> Vec<&'a DocumentSymbol> {
    SymbolSearchBuilder::new().with_name(name).find_all(symbols)
}

/// Find symbols by kind using idiomatic iterator approach
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols to search
/// * `kind` - Symbol kind to search for
///
/// # Returns
/// * `Vec<&DocumentSymbol>` - All symbols with matching kind
#[allow(dead_code)]
pub fn find_symbols_by_kind(
    symbols: &[DocumentSymbol],
    kind: lsp_types::SymbolKind,
) -> Vec<&DocumentSymbol> {
    SymbolSearchBuilder::new().with_kind(kind).find_all(symbols)
}

/// Count total symbols in hierarchical document symbols using iterator
///
/// Uses functional programming approach with iterator combinators.
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols
///
/// # Returns
/// * `usize` - Total count of all symbols in the hierarchy
#[allow(dead_code)]
pub fn count_total_symbols(symbols: &[DocumentSymbol]) -> usize {
    DocumentSymbolIterator::new(symbols).count()
}

/// Count symbols by kind using iterator approach
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols
/// * `kind` - Symbol kind to count
///
/// # Returns
/// * `usize` - Count of symbols with matching kind
#[allow(dead_code)]
pub fn count_symbols_by_kind(symbols: &[DocumentSymbol], kind: lsp_types::SymbolKind) -> usize {
    DocumentSymbolIterator::new(symbols)
        .filter(|(symbol, _)| symbol.kind == kind)
        .count()
}

/// Get all symbol names with their paths
///
/// Returns a vector of (symbol_name, path) tuples for all symbols in the hierarchy.
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols
///
/// # Returns
/// * `Vec<(String, String)>` - Vector of (name, path) tuples
#[allow(dead_code)]
pub fn get_symbol_paths(symbols: &[DocumentSymbol]) -> Vec<(String, String)> {
    DocumentSymbolIterator::new(symbols)
        .map(|(symbol, path)| (symbol.name.clone(), path.join("::")))
        .collect()
}

/// Extract class members from hierarchical document symbols using the builder pattern
///
/// This function provides a higher-level interface for extracting class members
/// by finding the target class and collecting its callable members (methods, constructors, operators).
/// The search leverages the document symbol hierarchy for comprehensive member discovery.
///
/// # Arguments
/// * `symbols` - Hierarchical document symbols to search
/// * `class_name` - Name of the class to extract members from
///
/// # Returns
/// * `Vec<&DocumentSymbol>` - All callable members found within the specified class
#[allow(dead_code)]
pub fn extract_class_members<'a>(
    symbols: &'a [DocumentSymbol],
    class_name: &str,
) -> Vec<&'a DocumentSymbol> {
    // First find the target class
    if let Some(target_class) = SymbolSearchBuilder::new()
        .with_name(class_name)
        .with_kind(lsp_types::SymbolKind::CLASS)
        .find_first(symbols)
    {
        // Extract callable members from the class's children
        if let Some(children) = &target_class.children {
            return SymbolSearchBuilder::new()
                .class_members_only()
                .find_all(children);
        }
    }

    // Also search for struct types
    if let Some(target_struct) = SymbolSearchBuilder::new()
        .with_name(class_name)
        .with_kind(lsp_types::SymbolKind::STRUCT)
        .find_first(symbols)
        && let Some(children) = &target_struct.children
    {
        return SymbolSearchBuilder::new()
            .class_members_only()
            .find_all(children);
    }

    Vec::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::{Position, Range, SymbolKind};

    fn create_test_symbol(
        name: &str,
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
    ) -> DocumentSymbol {
        DocumentSymbol {
            name: name.to_string(),
            detail: None,
            kind: SymbolKind::CLASS,
            tags: None,
            #[allow(deprecated)]
            deprecated: None,
            range: Range {
                start: Position {
                    line: start_line,
                    character: start_char,
                },
                end: Position {
                    line: end_line,
                    character: end_char,
                },
            },
            selection_range: Range {
                start: Position {
                    line: start_line,
                    character: start_char,
                },
                end: Position {
                    line: start_line,
                    character: start_char + name.len() as u32,
                },
            },
            children: None,
        }
    }

    fn create_test_symbol_with_kind(
        name: &str,
        kind: SymbolKind,
        start_line: u32,
        start_char: u32,
        end_line: u32,
        end_char: u32,
    ) -> DocumentSymbol {
        let mut symbol = create_test_symbol(name, start_line, start_char, end_line, end_char);
        symbol.kind = kind;
        symbol
    }

    #[test]
    fn test_position_contains_trait() {
        let range = Range {
            start: Position {
                line: 10,
                character: 0,
            },
            end: Position {
                line: 10,
                character: 10,
            },
        };

        // Test position within range
        assert!(range.contains(&Position {
            line: 10,
            character: 5
        }));
        assert!(range.contains(&Position {
            line: 10,
            character: 5
        }));

        // Test position outside range
        assert!(!range.contains(&Position {
            line: 11,
            character: 5
        }));
        assert!(!range.contains(&Position {
            line: 10,
            character: 15
        }));
    }

    #[test]
    fn test_document_symbol_iterator() {
        let mut parent = create_test_symbol("Parent", 0, 0, 10, 0);
        let child1 = create_test_symbol("Child1", 2, 4, 4, 0);
        let child2 = create_test_symbol("Child2", 6, 4, 8, 0);

        parent.children = Some(vec![child1, child2]);
        let symbols = vec![parent];

        let collected: Vec<_> = DocumentSymbolIterator::new(&symbols)
            .map(|(symbol, path)| (symbol.name.clone(), path.join("::")))
            .collect();

        assert_eq!(collected.len(), 3);
        assert_eq!(collected[0], ("Parent".to_string(), "".to_string()));
        assert_eq!(collected[1], ("Child1".to_string(), "Parent".to_string()));
        assert_eq!(collected[2], ("Child2".to_string(), "Parent".to_string()));
    }

    #[test]
    fn test_symbol_search_builder_position() {
        let symbol = create_test_symbol("TestClass", 10, 0, 20, 0);
        let symbols = vec![symbol];

        // Position within selection range
        let found = SymbolSearchBuilder::new()
            .at_position(Position {
                line: 10,
                character: 5,
            })
            .find_first(&symbols);
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "TestClass");

        // Position outside range
        let not_found = SymbolSearchBuilder::new()
            .at_position(Position {
                line: 25,
                character: 0,
            })
            .find_first(&symbols);
        assert!(not_found.is_none());
    }

    #[test]
    fn test_symbol_search_builder_name() {
        let symbol1 = create_test_symbol("ClassA", 0, 0, 5, 0);
        let symbol2 = create_test_symbol("ClassB", 6, 0, 10, 0);
        let symbols = vec![symbol1, symbol2];

        let found = SymbolSearchBuilder::new()
            .with_name("ClassB")
            .find_first(&symbols);
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "ClassB");
    }

    #[test]
    fn test_symbol_search_builder_kind() {
        let class_symbol = create_test_symbol_with_kind("MyClass", SymbolKind::CLASS, 0, 0, 5, 0);
        let function_symbol =
            create_test_symbol_with_kind("myFunction", SymbolKind::FUNCTION, 6, 0, 8, 0);
        let symbols = vec![class_symbol, function_symbol];

        let functions = SymbolSearchBuilder::new()
            .with_kind(SymbolKind::FUNCTION)
            .find_all(&symbols);
        assert_eq!(functions.len(), 1);
        assert_eq!(functions[0].name, "myFunction");
    }

    #[test]
    fn test_symbol_search_builder_combined() {
        let mut parent = create_test_symbol_with_kind("Parent", SymbolKind::CLASS, 0, 0, 10, 0);
        let child = create_test_symbol_with_kind("method", SymbolKind::METHOD, 2, 4, 4, 0);

        parent.children = Some(vec![child]);
        let symbols = vec![parent];

        // Search for method by name and kind
        let found = SymbolSearchBuilder::new()
            .with_name("method")
            .with_kind(SymbolKind::METHOD)
            .find_first(&symbols);
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "method");

        // Search for method in specific path
        let found_with_path = SymbolSearchBuilder::new()
            .with_name("method")
            .path_contains("Parent")
            .find_first(&symbols);
        assert!(found_with_path.is_some());
        assert_eq!(found_with_path.unwrap().name, "method");
    }

    #[test]
    fn test_find_symbol_at_position() {
        let symbol = create_test_symbol("TestClass", 10, 0, 20, 0);
        let symbols = vec![symbol];

        // Position within selection range
        let found = find_symbol_at_position(
            &symbols,
            &Position {
                line: 10,
                character: 5,
            },
        );
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "TestClass");

        // Position outside range
        let not_found = find_symbol_at_position(
            &symbols,
            &Position {
                line: 25,
                character: 0,
            },
        );
        assert!(not_found.is_none());
    }

    #[test]
    fn test_find_symbols_by_name() {
        let symbol1 = create_test_symbol("Test", 0, 0, 5, 0);
        let symbol2 = create_test_symbol("Other", 6, 0, 10, 0);
        let symbol3 = create_test_symbol("Test", 11, 0, 15, 0);
        let symbols = vec![symbol1, symbol2, symbol3];

        let found = find_symbols_by_name(&symbols, "Test");
        assert_eq!(found.len(), 2);
        assert!(found.iter().all(|s| s.name == "Test"));
    }

    #[test]
    fn test_find_symbols_by_kind() {
        let class_symbol = create_test_symbol_with_kind("MyClass", SymbolKind::CLASS, 0, 0, 5, 0);
        let function_symbol =
            create_test_symbol_with_kind("myFunction", SymbolKind::FUNCTION, 6, 0, 8, 0);
        let symbols = vec![class_symbol, function_symbol];

        let classes = find_symbols_by_kind(&symbols, SymbolKind::CLASS);
        assert_eq!(classes.len(), 1);
        assert_eq!(classes[0].name, "MyClass");
    }

    #[test]
    fn test_count_total_symbols() {
        let mut parent = create_test_symbol("Parent", 0, 0, 10, 0);
        let child1 = create_test_symbol("Child1", 2, 4, 4, 0);
        let child2 = create_test_symbol("Child2", 6, 4, 8, 0);

        parent.children = Some(vec![child1, child2]);
        let symbols = vec![parent];

        // Should count parent + 2 children = 3 total
        assert_eq!(count_total_symbols(&symbols), 3);
    }

    #[test]
    fn test_count_symbols_by_kind() {
        let class1 = create_test_symbol_with_kind("Class1", SymbolKind::CLASS, 0, 0, 5, 0);
        let class2 = create_test_symbol_with_kind("Class2", SymbolKind::CLASS, 6, 0, 10, 0);
        let function = create_test_symbol_with_kind("func", SymbolKind::FUNCTION, 11, 0, 13, 0);
        let symbols = vec![class1, class2, function];

        assert_eq!(count_symbols_by_kind(&symbols, SymbolKind::CLASS), 2);
        assert_eq!(count_symbols_by_kind(&symbols, SymbolKind::FUNCTION), 1);
        assert_eq!(count_symbols_by_kind(&symbols, SymbolKind::VARIABLE), 0);
    }

    #[test]
    fn test_get_symbol_paths() {
        let mut parent = create_test_symbol("Namespace", 0, 0, 10, 0);
        let mut child_class = create_test_symbol("MyClass", 2, 0, 8, 0);
        let child_method = create_test_symbol("method", 4, 4, 6, 0);

        child_class.children = Some(vec![child_method]);
        parent.children = Some(vec![child_class]);
        let symbols = vec![parent];

        let paths = get_symbol_paths(&symbols);
        assert_eq!(paths.len(), 3);

        // Check paths
        assert!(paths.contains(&("Namespace".to_string(), "".to_string())));
        assert!(paths.contains(&("MyClass".to_string(), "Namespace".to_string())));
        assert!(paths.contains(&("method".to_string(), "Namespace::MyClass".to_string())));
    }

    #[test]
    fn test_fuzzy_matching_basic() {
        let factorial_symbol = create_test_symbol("factorial", 0, 0, 5, 0);
        let calculate_symbol = create_test_symbol("calculate", 6, 0, 10, 0);
        let math_symbol = create_test_symbol("Math", 11, 0, 15, 0);
        let symbols = vec![factorial_symbol, calculate_symbol, math_symbol];

        // Test exact match
        let found = SymbolSearchBuilder::new()
            .with_name("factorial")
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "factorial");

        // Test fuzzy match with typo
        let found = SymbolSearchBuilder::new()
            .with_name("factrl")
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "factorial");

        // Test partial match
        let found = SymbolSearchBuilder::new()
            .with_name("calc")
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "calculate");
    }

    #[test]
    fn test_fuzzy_matching_case_insensitive() {
        let string_utils_symbol = create_test_symbol("StringUtils", 0, 0, 5, 0);
        let symbols = vec![string_utils_symbol];

        // Test case variations
        let found = SymbolSearchBuilder::new()
            .with_name("strutil")
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "StringUtils");

        let found = SymbolSearchBuilder::new()
            .with_name("STRINGUTILS")
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "StringUtils");
    }

    #[test]
    fn test_fuzzy_matching_scoring_order() {
        let math_symbol = create_test_symbol("Math", 0, 0, 5, 0);
        let matrix_symbol = create_test_symbol("Matrix", 6, 0, 10, 0);
        let algorithm_symbol = create_test_symbol("Algorithm", 11, 0, 15, 0);
        let symbols = vec![math_symbol, matrix_symbol, algorithm_symbol];

        // Query "Mat" should prefer "Math" over "Matrix" (better score)
        let found = SymbolSearchBuilder::new()
            .with_name("Mat")
            .find_all(&symbols);

        assert!(!found.is_empty());
        // The first result should be the best match
        assert_eq!(found[0].name, "Math");
    }

    #[test]
    fn test_fuzzy_matching_no_matches() {
        let factorial_symbol = create_test_symbol("factorial", 0, 0, 5, 0);
        let symbols = vec![factorial_symbol];

        // Test query that shouldn't match
        let found = SymbolSearchBuilder::new()
            .with_name("xyz")
            .find_all(&symbols);
        assert_eq!(found.len(), 0);
    }

    #[test]
    fn test_fuzzy_matching_with_kind_filter() {
        let class_symbol = create_test_symbol_with_kind("Math", SymbolKind::CLASS, 0, 0, 5, 0);
        let function_symbol =
            create_test_symbol_with_kind("mathFunction", SymbolKind::FUNCTION, 6, 0, 8, 0);
        let symbols = vec![class_symbol, function_symbol];

        // Fuzzy search for "mat" with class filter should only return the class
        let found = SymbolSearchBuilder::new()
            .with_name("mat")
            .with_kind(SymbolKind::CLASS)
            .find_all(&symbols);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "Math");
        assert_eq!(found[0].kind, SymbolKind::CLASS);
    }

    #[test]
    fn test_fuzzy_matching_multiple_results_sorted() {
        let math_class = create_test_symbol("Math", 0, 0, 5, 0);
        let mathematics = create_test_symbol("Mathematics", 6, 0, 10, 0);
        let matrix = create_test_symbol("Matrix", 11, 0, 15, 0);
        let symbols = vec![math_class, mathematics, matrix];

        // Query "Math" should return all matches, sorted by score
        let found = SymbolSearchBuilder::new()
            .with_name("Math")
            .find_all(&symbols);

        assert!(found.len() >= 2); // Should find Math and Mathematics at least
        // First result should be exact match "Math"
        assert_eq!(found[0].name, "Math");
    }
}