leindex 1.6.0

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
// Global symbol table for cross-project resolution
//
// This module provides the data structures and operations for managing
// symbols across multiple projects, enabling cross-project symbol resolution.

use crate::storage::schema::Storage;
use rusqlite::{params, OptionalExtension};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Global symbol identifier (BLAKE3 hash)
pub type GlobalSymbolId = String;

/// Global symbol record
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GlobalSymbol {
    /// Unique identifier for the symbol
    pub symbol_id: GlobalSymbolId,
    /// ID of the project containing the symbol
    pub project_id: String,
    /// Name of the symbol
    pub symbol_name: String,
    /// Type of the symbol (function, class, etc.)
    pub symbol_type: SymbolType,
    /// Code signature or declaration
    pub signature: Option<String>,
    /// Path to the file containing the symbol
    pub file_path: String,
    /// Byte range in the source file
    pub byte_range: (usize, usize),
    /// Complexity score of the symbol
    pub complexity: u32,
    /// Whether the symbol is publicly accessible
    pub is_public: bool,
}

/// Symbol type classification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SymbolType {
    /// A function definition
    Function,
    /// A class definition
    Class,
    /// A method definition
    Method,
    /// A variable definition
    Variable,
    /// A module or file
    Module,
    /// A struct definition
    Struct,
    /// An enum definition
    Enum,
    /// A trait or interface definition
    Trait,
}

impl SymbolType {
    /// Return the string representation of the symbol type.
    pub fn as_str(&self) -> &'static str {
        match self {
            SymbolType::Function => "function",
            SymbolType::Class => "class",
            SymbolType::Method => "method",
            SymbolType::Variable => "variable",
            SymbolType::Module => "module",
            SymbolType::Struct => "struct",
            SymbolType::Enum => "enum",
            SymbolType::Trait => "trait",
        }
    }

    /// Create a symbol type from its string representation.
    pub fn from_str_name(s: &str) -> Option<Self> {
        match s {
            "function" => Some(SymbolType::Function),
            "class" => Some(SymbolType::Class),
            "method" => Some(SymbolType::Method),
            "variable" => Some(SymbolType::Variable),
            "module" => Some(SymbolType::Module),
            "struct" => Some(SymbolType::Struct),
            "enum" => Some(SymbolType::Enum),
            "trait" => Some(SymbolType::Trait),
            _ => None,
        }
    }
}

/// External reference between symbols
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExternalRef {
    /// Unique identifier for the reference
    pub ref_id: String,
    /// ID of the project containing the source symbol
    pub source_project_id: String,
    /// ID of the source symbol
    pub source_symbol_id: GlobalSymbolId,
    /// ID of the project containing the target symbol
    pub target_project_id: String,
    /// ID of the target symbol
    pub target_symbol_id: GlobalSymbolId,
    /// Type of the reference (call, inheritance, etc.)
    pub ref_type: RefType,
}

/// Reference type between symbols
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RefType {
    /// Function or method call
    Call,
    /// Class or interface inheritance
    Inheritance,
    /// Module or file import
    Import,
    /// General usage reference
    Use,
    /// Data dependency
    DataDependency,
}

impl RefType {
    /// Return the string representation of the reference type.
    pub fn as_str(&self) -> &'static str {
        match self {
            RefType::Call => "call",
            RefType::Inheritance => "inheritance",
            RefType::Import => "import",
            RefType::Use => "use",
            RefType::DataDependency => "data_dependency",
        }
    }

    /// Create a reference type from its string representation.
    pub fn from_str_name(s: &str) -> Option<Self> {
        match s {
            "call" => Some(RefType::Call),
            "inheritance" => Some(RefType::Inheritance),
            "import" => Some(RefType::Import),
            "use" => Some(RefType::Use),
            "data_dependency" => Some(RefType::DataDependency),
            _ => None,
        }
    }
}

/// Project dependency
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProjectDep {
    /// Unique identifier for the dependency
    pub dep_id: String,
    /// ID of the project that has the dependency
    pub project_id: String,
    /// ID of the project that is depended upon
    pub depends_on_project_id: String,
    /// Type of the dependency (direct, dev, etc.)
    pub dependency_type: DepType,
}

/// Dependency type between projects
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DepType {
    /// Direct production dependency
    Direct,
    /// Transitive dependency (dependency of a dependency)
    Transitive,
    /// Development-only dependency
    Dev,
    /// Build-time dependency
    Build,
}

impl DepType {
    /// Return the string representation of the dependency type.
    pub fn as_str(&self) -> &'static str {
        match self {
            DepType::Direct => "direct",
            DepType::Transitive => "transitive",
            DepType::Dev => "dev",
            DepType::Build => "build",
        }
    }

    /// Create a dependency type from its string representation.
    pub fn from_str_name(s: &str) -> Option<Self> {
        match s {
            "direct" => Some(DepType::Direct),
            "transitive" => Some(DepType::Transitive),
            "dev" => Some(DepType::Dev),
            "build" => Some(DepType::Build),
            _ => None,
        }
    }
}

/// Global symbol table operations
pub struct GlobalSymbolTable<'a> {
    db: &'a Storage,
}

impl<'a> GlobalSymbolTable<'a> {
    /// Create new global symbol table
    pub fn new(db: &'a Storage) -> Self {
        Self { db }
    }

    /// Get the underlying storage
    pub fn storage(&self) -> &Storage {
        self.db
    }

    /// Generate a unique symbol ID using BLAKE3 hash
    pub fn generate_symbol_id(
        project_id: &str,
        symbol_name: &str,
        signature: Option<&str>,
    ) -> GlobalSymbolId {
        use blake3::Hasher;
        let mut hasher = Hasher::new();
        hasher.update(project_id.as_bytes());
        hasher.update(b"::");
        hasher.update(symbol_name.as_bytes());
        if let Some(sig) = signature {
            hasher.update(sig.as_bytes());
        }
        hasher.finalize().to_hex().to_string()
    }

    /// Insert or update a global symbol
    pub fn upsert_symbol(&self, symbol: &GlobalSymbol) -> Result<(), GlobalSymbolError> {
        let byte_start = symbol.byte_range.0 as i64;
        let byte_end = symbol.byte_range.1 as i64;
        let is_public = if symbol.is_public { 1 } else { 0 };

        self.db
            .conn()
            .execute(
                "INSERT INTO global_symbols (
                symbol_id, project_id, symbol_name, symbol_type,
                signature, file_path, byte_range_start, byte_range_end,
                complexity, is_public
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
            ON CONFLICT(project_id, symbol_name, signature) DO UPDATE SET
                file_path = excluded.file_path,
                byte_range_start = excluded.byte_range_start,
                byte_range_end = excluded.byte_range_end,
                complexity = excluded.complexity,
                is_public = excluded.is_public",
                params![
                    &symbol.symbol_id,
                    &symbol.project_id,
                    &symbol.symbol_name,
                    symbol.symbol_type.as_str(),
                    &symbol.signature,
                    &symbol.file_path,
                    byte_start,
                    byte_end,
                    symbol.complexity as i64,
                    is_public,
                ],
            )
            .map_err(GlobalSymbolError::from)?;

        Ok(())
    }

    /// Batch insert symbols
    pub fn upsert_symbols_batch(&self, symbols: &[GlobalSymbol]) -> Result<(), GlobalSymbolError> {
        // Use rusqlite's transaction method which can be called on &Connection
        self.db.conn().execute("BEGIN IMMEDIATE TRANSACTION", [])?;

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            for symbol in symbols {
                let byte_start = symbol.byte_range.0 as i64;
                let byte_end = symbol.byte_range.1 as i64;
                let is_public = if symbol.is_public { 1 } else { 0 };

                if let Err(e) = self.db.conn().execute(
                    "INSERT INTO global_symbols (
                        symbol_id, project_id, symbol_name, symbol_type,
                        signature, file_path, byte_range_start, byte_range_end,
                        complexity, is_public
                    ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
                    ON CONFLICT(project_id, symbol_name, signature) DO UPDATE SET
                        file_path = excluded.file_path,
                        byte_range_start = excluded.byte_range_start,
                        byte_range_end = excluded.byte_range_end,
                        complexity = excluded.complexity,
                        is_public = excluded.is_public",
                    params![
                        &symbol.symbol_id,
                        &symbol.project_id,
                        &symbol.symbol_name,
                        symbol.symbol_type.as_str(),
                        &symbol.signature,
                        &symbol.file_path,
                        byte_start,
                        byte_end,
                        symbol.complexity as i64,
                        is_public,
                    ],
                ) {
                    self.db.conn().execute("ROLLBACK", []).ok();
                    return Err::<(), rusqlite::Error>(e);
                }
            }
            Result::<(), rusqlite::Error>::Ok(())
        }));

        match result {
            Ok(inner) => inner.map_err(GlobalSymbolError::from),
            Err(_) => {
                self.db.conn().execute("ROLLBACK", []).ok();
                Err(GlobalSymbolError::Sqlite(
                    rusqlite::Error::ExecuteReturnedResults,
                ))
            }
        }?;

        self.db
            .conn()
            .execute("COMMIT", [])
            .map_err(GlobalSymbolError::from)?;
        Ok(())
    }

    /// Resolve symbol by name (returns all matches across projects)
    pub fn resolve_by_name(&self, name: &str) -> Result<Vec<GlobalSymbol>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT symbol_id, project_id, symbol_name, symbol_type, signature,
                    file_path, byte_range_start, byte_range_end, complexity, is_public
             FROM global_symbols
             WHERE symbol_name = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let symbols = stmt
            .query_map(params![name], |row| {
                Ok(GlobalSymbol {
                    symbol_id: row.get(0)?,
                    project_id: row.get(1)?,
                    symbol_name: row.get(2)?,
                    symbol_type: SymbolType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(SymbolType::Function),
                    signature: row.get(4)?,
                    file_path: row.get(5)?,
                    byte_range: (
                        row.get::<_, i64>(6)? as usize,
                        row.get::<_, i64>(7)? as usize,
                    ),
                    complexity: row.get::<_, i64>(8)? as u32,
                    is_public: row.get::<_, i64>(9)? == 1,
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(symbols)
    }

    /// Resolve symbol by name and type
    pub fn resolve_by_name_and_type(
        &self,
        name: &str,
        symbol_type: SymbolType,
    ) -> Result<Vec<GlobalSymbol>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT symbol_id, project_id, symbol_name, symbol_type, signature,
                    file_path, byte_range_start, byte_range_end, complexity, is_public
             FROM global_symbols
             WHERE symbol_name = ?1 AND symbol_type = ?2",
            )
            .map_err(GlobalSymbolError::from)?;

        let symbols = stmt
            .query_map(params![name, symbol_type.as_str()], |row| {
                Ok(GlobalSymbol {
                    symbol_id: row.get(0)?,
                    project_id: row.get(1)?,
                    symbol_name: row.get(2)?,
                    symbol_type: SymbolType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(SymbolType::Function),
                    signature: row.get(4)?,
                    file_path: row.get(5)?,
                    byte_range: (
                        row.get::<_, i64>(6)? as usize,
                        row.get::<_, i64>(7)? as usize,
                    ),
                    complexity: row.get::<_, i64>(8)? as u32,
                    is_public: row.get::<_, i64>(9)? == 1,
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(symbols)
    }

    /// Get symbol by ID
    pub fn get_symbol(
        &self,
        symbol_id: &GlobalSymbolId,
    ) -> Result<Option<GlobalSymbol>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT symbol_id, project_id, symbol_name, symbol_type, signature,
                    file_path, byte_range_start, byte_range_end, complexity, is_public
             FROM global_symbols
             WHERE symbol_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let result = stmt
            .query_row(params![symbol_id], |row| {
                Ok(GlobalSymbol {
                    symbol_id: row.get(0)?,
                    project_id: row.get(1)?,
                    symbol_name: row.get(2)?,
                    symbol_type: SymbolType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(SymbolType::Function),
                    signature: row.get(4)?,
                    file_path: row.get(5)?,
                    byte_range: (
                        row.get::<_, i64>(6)? as usize,
                        row.get::<_, i64>(7)? as usize,
                    ),
                    complexity: row.get::<_, i64>(8)? as u32,
                    is_public: row.get::<_, i64>(9)? == 1,
                })
            })
            .optional()
            .map_err(GlobalSymbolError::from)?;

        Ok(result)
    }

    /// Get all symbols for a project
    pub fn get_project_symbols(
        &self,
        project_id: &str,
    ) -> Result<Vec<GlobalSymbol>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT symbol_id, project_id, symbol_name, symbol_type, signature,
                    file_path, byte_range_start, byte_range_end, complexity, is_public
             FROM global_symbols
             WHERE project_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let symbols = stmt
            .query_map(params![project_id], |row| {
                Ok(GlobalSymbol {
                    symbol_id: row.get(0)?,
                    project_id: row.get(1)?,
                    symbol_name: row.get(2)?,
                    symbol_type: SymbolType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(SymbolType::Function),
                    signature: row.get(4)?,
                    file_path: row.get(5)?,
                    byte_range: (
                        row.get::<_, i64>(6)? as usize,
                        row.get::<_, i64>(7)? as usize,
                    ),
                    complexity: row.get::<_, i64>(8)? as u32,
                    is_public: row.get::<_, i64>(9)? == 1,
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(symbols)
    }

    /// Add external reference
    pub fn add_external_ref(&self, reference: &ExternalRef) -> Result<(), GlobalSymbolError> {
        self.db
            .conn()
            .execute(
                "INSERT INTO external_refs (
                ref_id, source_project_id, source_symbol_id,
                target_project_id, target_symbol_id, ref_type
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    &reference.ref_id,
                    &reference.source_project_id,
                    &reference.source_symbol_id,
                    &reference.target_project_id,
                    &reference.target_symbol_id,
                    reference.ref_type.as_str(),
                ],
            )
            .map_err(GlobalSymbolError::from)?;

        Ok(())
    }

    /// Get all outgoing references from a symbol
    pub fn get_outgoing_refs(
        &self,
        symbol_id: &GlobalSymbolId,
    ) -> Result<Vec<ExternalRef>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT ref_id, source_project_id, source_symbol_id,
                    target_project_id, target_symbol_id, ref_type
             FROM external_refs
             WHERE source_symbol_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let refs = stmt
            .query_map(params![symbol_id], |row| {
                Ok(ExternalRef {
                    ref_id: row.get(0)?,
                    source_project_id: row.get(1)?,
                    source_symbol_id: row.get(2)?,
                    target_project_id: row.get(3)?,
                    target_symbol_id: row.get(4)?,
                    ref_type: RefType::from_str_name(row.get::<_, String>(5)?.as_str())
                        .unwrap_or(RefType::Call),
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(refs)
    }

    /// Get all incoming references to a symbol
    pub fn get_incoming_refs(
        &self,
        symbol_id: &GlobalSymbolId,
    ) -> Result<Vec<ExternalRef>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT ref_id, source_project_id, source_symbol_id,
                    target_project_id, target_symbol_id, ref_type
             FROM external_refs
             WHERE target_symbol_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let refs = stmt
            .query_map(params![symbol_id], |row| {
                Ok(ExternalRef {
                    ref_id: row.get(0)?,
                    source_project_id: row.get(1)?,
                    source_symbol_id: row.get(2)?,
                    target_project_id: row.get(3)?,
                    target_symbol_id: row.get(4)?,
                    ref_type: RefType::from_str_name(row.get::<_, String>(5)?.as_str())
                        .unwrap_or(RefType::Call),
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(refs)
    }

    /// Add project dependency
    pub fn add_project_dep(&self, dep: &ProjectDep) -> Result<(), GlobalSymbolError> {
        self.db.conn().execute(
            "INSERT INTO project_deps (dep_id, project_id, depends_on_project_id, dependency_type)
             VALUES (?1, ?2, ?3, ?4)",
            params![
                &dep.dep_id,
                &dep.project_id,
                &dep.depends_on_project_id,
                dep.dependency_type.as_str(),
            ],
        ).map_err(GlobalSymbolError::from)?;

        Ok(())
    }

    /// Get all dependencies for a project
    pub fn get_project_deps(&self, project_id: &str) -> Result<Vec<ProjectDep>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT dep_id, project_id, depends_on_project_id, dependency_type
             FROM project_deps
             WHERE project_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let deps = stmt
            .query_map(params![project_id], |row| {
                Ok(ProjectDep {
                    dep_id: row.get(0)?,
                    project_id: row.get(1)?,
                    depends_on_project_id: row.get(2)?,
                    dependency_type: DepType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(DepType::Direct),
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(deps)
    }

    /// Get all projects that depend on the given project (reverse dependencies)
    ///
    /// This is used for change propagation - when a project changes,
    /// we need to find all projects that depend on it.
    pub fn get_reverse_project_deps(
        &self,
        depends_on_project_id: &str,
    ) -> Result<Vec<ProjectDep>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT dep_id, project_id, depends_on_project_id, dependency_type
             FROM project_deps
             WHERE depends_on_project_id = ?1",
            )
            .map_err(GlobalSymbolError::from)?;

        let deps = stmt
            .query_map(params![depends_on_project_id], |row| {
                Ok(ProjectDep {
                    dep_id: row.get(0)?,
                    project_id: row.get(1)?,
                    depends_on_project_id: row.get(2)?,
                    dependency_type: DepType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(DepType::Direct),
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(deps)
    }

    /// Find public symbols (exported API)
    pub fn find_public_symbols(
        &self,
        project_id: &str,
    ) -> Result<Vec<GlobalSymbol>, GlobalSymbolError> {
        let mut stmt = self
            .db
            .conn()
            .prepare(
                "SELECT symbol_id, project_id, symbol_name, symbol_type, signature,
                    file_path, byte_range_start, byte_range_end, complexity, is_public
             FROM global_symbols
             WHERE project_id = ?1 AND is_public = 1",
            )
            .map_err(GlobalSymbolError::from)?;

        let symbols = stmt
            .query_map(params![project_id], |row| {
                Ok(GlobalSymbol {
                    symbol_id: row.get(0)?,
                    project_id: row.get(1)?,
                    symbol_name: row.get(2)?,
                    symbol_type: SymbolType::from_str_name(row.get::<_, String>(3)?.as_str())
                        .unwrap_or(SymbolType::Function),
                    signature: row.get(4)?,
                    file_path: row.get(5)?,
                    byte_range: (
                        row.get::<_, i64>(6)? as usize,
                        row.get::<_, i64>(7)? as usize,
                    ),
                    complexity: row.get::<_, i64>(8)? as u32,
                    is_public: row.get::<_, i64>(9)? == 1,
                })
            })
            .map_err(GlobalSymbolError::from)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(GlobalSymbolError::from)?;

        Ok(symbols)
    }

    /// Detect symbol name conflicts
    pub fn detect_conflicts(
        &self,
        symbol_name: &str,
    ) -> Result<Vec<GlobalSymbol>, GlobalSymbolError> {
        // This returns all symbols with the given name across all projects
        // If there are multiple, we have a potential conflict
        self.resolve_by_name(symbol_name)
    }
}

/// Errors for global symbol operations
#[derive(Debug, Error)]
pub enum GlobalSymbolError {
    /// Error originating from the underlying SQLite database
    #[error("SQLite error: {0}")]
    Sqlite(#[from] rusqlite::Error),

    /// The specified symbol ID was not found
    #[error("Symbol not found: {0}")]
    SymbolNotFound(String),

    /// Multiple symbols match the name across different projects
    #[error("Ambiguous symbol: {0} found in {1} projects")]
    AmbiguousSymbol(String, usize),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::schema::Storage;
    use tempfile::NamedTempFile;

    #[test]
    fn test_upsert_and_get_symbol() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let symbol = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("test_project", "foo", Some("fn()")),
            project_id: "test_project".to_string(),
            symbol_name: "foo".to_string(),
            symbol_type: SymbolType::Function,
            signature: Some("fn()".to_string()),
            file_path: "src/test.rs".to_string(),
            byte_range: (0, 100),
            complexity: 5,
            is_public: true,
        };

        table.upsert_symbol(&symbol).unwrap();

        let retrieved = table.get_symbol(&symbol.symbol_id).unwrap();
        assert!(retrieved.is_some());
        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved.symbol_name, "foo");
        assert_eq!(retrieved.project_id, "test_project");
    }

    #[test]
    fn test_batch_insert() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let symbols = vec![
            GlobalSymbol {
                symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "foo", None),
                project_id: "proj_a".to_string(),
                symbol_name: "foo".to_string(),
                symbol_type: SymbolType::Function,
                signature: None,
                file_path: "src/a.rs".to_string(),
                byte_range: (0, 50),
                complexity: 1,
                is_public: false,
            },
            GlobalSymbol {
                symbol_id: GlobalSymbolTable::generate_symbol_id("proj_b", "bar", None),
                project_id: "proj_b".to_string(),
                symbol_name: "bar".to_string(),
                symbol_type: SymbolType::Function,
                signature: None,
                file_path: "src/b.rs".to_string(),
                byte_range: (0, 50),
                complexity: 1,
                is_public: false,
            },
        ];

        table.upsert_symbols_batch(&symbols).unwrap();

        let proj_a_symbols = table.get_project_symbols("proj_a").unwrap();
        assert_eq!(proj_a_symbols.len(), 1);
        assert_eq!(proj_a_symbols[0].symbol_name, "foo");
    }

    #[test]
    fn test_resolve_by_name() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let symbol1 = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "util", None),
            project_id: "proj_a".to_string(),
            symbol_name: "util".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/a.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        let symbol2 = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_b", "util", None),
            project_id: "proj_b".to_string(),
            symbol_name: "util".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/b.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        table.upsert_symbol(&symbol1).unwrap();
        table.upsert_symbol(&symbol2).unwrap();

        let results = table.resolve_by_name("util").unwrap();
        assert_eq!(results.len(), 2); // Found in both projects
    }

    #[test]
    fn test_detect_conflicts() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let symbol1 = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "util", None),
            project_id: "proj_a".to_string(),
            symbol_name: "util".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/a.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        let symbol2 = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_b", "util", None),
            project_id: "proj_b".to_string(),
            symbol_name: "util".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/b.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        table.upsert_symbol(&symbol1).unwrap();
        table.upsert_symbol(&symbol2).unwrap();

        let conflicts = table.detect_conflicts("util").unwrap();
        assert_eq!(conflicts.len(), 2); // Conflict detected
    }

    #[test]
    fn test_external_refs() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        // Create source and target symbols
        let source = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "caller", None),
            project_id: "proj_a".to_string(),
            symbol_name: "caller".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/a.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        let target = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_b", "callee", None),
            project_id: "proj_b".to_string(),
            symbol_name: "callee".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/b.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: true,
        };

        table.upsert_symbol(&source).unwrap();
        table.upsert_symbol(&target).unwrap();

        // Add external reference
        let ext_ref = ExternalRef {
            ref_id: "ref_123".to_string(),
            source_project_id: "proj_a".to_string(),
            source_symbol_id: source.symbol_id.clone(),
            target_project_id: "proj_b".to_string(),
            target_symbol_id: target.symbol_id.clone(),
            ref_type: RefType::Call,
        };

        table.add_external_ref(&ext_ref).unwrap();

        // Verify we can retrieve the reference
        let outgoing = table.get_outgoing_refs(&source.symbol_id).unwrap();
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].target_symbol_id, target.symbol_id);

        let incoming = table.get_incoming_refs(&target.symbol_id).unwrap();
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].source_symbol_id, source.symbol_id);
    }

    #[test]
    fn test_project_deps() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let dep = ProjectDep {
            dep_id: "dep_1".to_string(),
            project_id: "proj_a".to_string(),
            depends_on_project_id: "proj_b".to_string(),
            dependency_type: DepType::Direct,
        };

        table.add_project_dep(&dep).unwrap();

        let deps = table.get_project_deps("proj_a").unwrap();
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].depends_on_project_id, "proj_b");
    }

    #[test]
    fn test_find_public_symbols() {
        let temp_file = NamedTempFile::new().unwrap();
        let db = Storage::open(temp_file.path()).unwrap();
        let table = GlobalSymbolTable::new(&db);

        let public_symbol = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "public_fn", None),
            project_id: "proj_a".to_string(),
            symbol_name: "public_fn".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/lib.rs".to_string(),
            byte_range: (0, 100),
            complexity: 5,
            is_public: true,
        };

        let private_symbol = GlobalSymbol {
            symbol_id: GlobalSymbolTable::generate_symbol_id("proj_a", "private_fn", None),
            project_id: "proj_a".to_string(),
            symbol_name: "private_fn".to_string(),
            symbol_type: SymbolType::Function,
            signature: None,
            file_path: "src/internal.rs".to_string(),
            byte_range: (0, 50),
            complexity: 1,
            is_public: false,
        };

        table.upsert_symbol(&public_symbol).unwrap();
        table.upsert_symbol(&private_symbol).unwrap();

        let public_symbols = table.find_public_symbols("proj_a").unwrap();
        assert_eq!(public_symbols.len(), 1);
        assert_eq!(public_symbols[0].symbol_name, "public_fn");
    }
}