reflex-search 1.0.3

A local-first, structure-aware code search engine for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
//! Dependency tracking and graph analysis
//!
//! This module provides functionality for tracking file dependencies (imports/includes)
//! and analyzing the dependency graph of a codebase.
//!
//! # Architecture
//!
//! The system uses a "depth-1 storage" approach:
//! - Only direct dependencies are stored in the database
//! - Deeper relationships are computed on-demand via graph traversal
//! - This provides O(n) storage while enabling any-depth queries
//!
//! # Example
//!
//! ```no_run
//! use reflex::dependency::DependencyIndex;
//! use reflex::cache::CacheManager;
//!
//! let cache = CacheManager::new(".");
//! let deps = DependencyIndex::new(cache);
//!
//! // Get direct dependencies of a file
//! let file_deps = deps.get_dependencies(42)?;
//!
//! // Get files that import this file (reverse lookup)
//! let dependents = deps.get_dependents(42)?;
//!
//! // Traverse dependency graph to depth 3
//! let transitive = deps.get_transitive_deps(42, 3)?;
//! # Ok::<(), anyhow::Error>(())
//! ```

use anyhow::{Context, Result};
use rusqlite::Connection;
use std::collections::{HashMap, HashSet, VecDeque};

use crate::cache::CacheManager;
use crate::models::{Dependency, DependencyInfo, ImportType};

/// Manages dependency storage and graph operations
pub struct DependencyIndex {
    cache: CacheManager,
}

impl DependencyIndex {
    /// Create a new dependency index for the given cache
    pub fn new(cache: CacheManager) -> Self {
        Self { cache }
    }

    /// Get a reference to the cache manager
    pub fn get_cache(&self) -> &CacheManager {
        &self.cache
    }

    /// Insert a dependency into the database
    ///
    /// # Arguments
    ///
    /// * `file_id` - Source file ID
    /// * `imported_path` - Import path as written in source
    /// * `resolved_file_id` - Resolved target file ID (None if external/stdlib)
    /// * `import_type` - Type of import (internal/external/stdlib)
    /// * `line_number` - Line where import appears
    /// * `imported_symbols` - Optional list of imported symbols
    pub fn insert_dependency(
        &self,
        file_id: i64,
        imported_path: String,
        resolved_file_id: Option<i64>,
        import_type: ImportType,
        line_number: usize,
        imported_symbols: Option<Vec<String>>,
    ) -> Result<()> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for dependency insert")?;

        let import_type_str = match import_type {
            ImportType::Internal => "internal",
            ImportType::External => "external",
            ImportType::Stdlib => "stdlib",
        };

        let symbols_json = imported_symbols
            .as_ref()
            .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));

        conn.execute(
            "INSERT INTO file_dependencies (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols)
             VALUES (?, ?, ?, ?, ?, ?)",
            rusqlite::params![
                file_id,
                imported_path,
                resolved_file_id,
                import_type_str,
                line_number as i64,
                symbols_json,
            ],
        )?;

        Ok(())
    }

    /// Insert an export into the database
    ///
    /// # Arguments
    ///
    /// * `file_id` - Source file ID containing the export statement
    /// * `exported_symbol` - Symbol name being exported (None for wildcard exports)
    /// * `source_path` - Path where the symbol is re-exported from
    /// * `resolved_source_id` - Resolved target file ID (None if unresolved)
    /// * `line_number` - Line where export appears
    pub fn insert_export(
        &self,
        file_id: i64,
        exported_symbol: Option<String>,
        source_path: String,
        resolved_source_id: Option<i64>,
        line_number: usize,
    ) -> Result<()> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for export insert")?;

        conn.execute(
            "INSERT INTO file_exports (file_id, exported_symbol, source_path, resolved_source_id, line_number)
             VALUES (?, ?, ?, ?, ?)",
            rusqlite::params![
                file_id,
                exported_symbol,
                source_path,
                resolved_source_id,
                line_number as i64,
            ],
        )?;

        Ok(())
    }

    /// Batch insert multiple dependencies in a single transaction
    ///
    /// More efficient than individual inserts for bulk operations.
    pub fn batch_insert_dependencies(&self, dependencies: &[Dependency]) -> Result<()> {
        if dependencies.is_empty() {
            return Ok(());
        }

        let db_path = self.cache.path().join("meta.db");
        let mut conn = Connection::open(&db_path)
            .context("Failed to open meta.db for batch dependency insert")?;

        let tx = conn.transaction()?;

        for dep in dependencies {
            let import_type_str = match dep.import_type {
                ImportType::Internal => "internal",
                ImportType::External => "external",
                ImportType::Stdlib => "stdlib",
            };

            let symbols_json = dep
                .imported_symbols
                .as_ref()
                .map(|syms| serde_json::to_string(syms).unwrap_or_else(|_| "[]".to_string()));

            tx.execute(
                "INSERT INTO file_dependencies (file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols)
                 VALUES (?, ?, ?, ?, ?, ?)",
                rusqlite::params![
                    dep.file_id,
                    dep.imported_path,
                    dep.resolved_file_id,
                    import_type_str,
                    dep.line_number as i64,
                    symbols_json,
                ],
            )?;
        }

        tx.commit()?;
        log::debug!("Batch inserted {} dependencies", dependencies.len());
        Ok(())
    }

    /// Get all direct dependencies for a file
    ///
    /// Returns a list of files/modules that this file imports.
    pub fn get_dependencies(&self, file_id: i64) -> Result<Vec<Dependency>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for dependency lookup")?;

        let mut stmt = conn.prepare(
            "SELECT file_id, imported_path, resolved_file_id, import_type, line_number, imported_symbols
             FROM file_dependencies
             WHERE file_id = ?
             ORDER BY line_number",
        )?;

        let deps = stmt
            .query_map([file_id], |row| {
                let import_type_str: String = row.get(3)?;
                let import_type = match import_type_str.as_str() {
                    "internal" => ImportType::Internal,
                    "external" => ImportType::External,
                    "stdlib" => ImportType::Stdlib,
                    _ => ImportType::External,
                };

                let symbols_json: Option<String> = row.get(5)?;
                let imported_symbols = symbols_json.and_then(|json| {
                    serde_json::from_str(&json).ok()
                });

                Ok(Dependency {
                    file_id: row.get(0)?,
                    imported_path: row.get(1)?,
                    resolved_file_id: row.get(2)?,
                    import_type,
                    line_number: row.get::<_, i64>(4)? as usize,
                    imported_symbols,
                })
            })?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(deps)
    }

    /// Get all files that depend on this file (reverse lookup)
    ///
    /// Returns a list of file IDs that import this file.
    /// Uses `resolved_file_id` column for instant SQL lookup (sub-10ms).
    pub fn get_dependents(&self, file_id: i64) -> Result<Vec<i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for reverse dependency lookup")?;

        // Pure SQL query on resolved_file_id (instant)
        let mut stmt = conn.prepare(
            "SELECT DISTINCT file_id
             FROM file_dependencies
             WHERE resolved_file_id = ?
             ORDER BY file_id"
        )?;

        let dependents: Vec<i64> = stmt
            .query_map([file_id], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(dependents)
    }

    /// Get dependencies as DependencyInfo (for API output)
    ///
    /// Converts internal Dependency records to simplified DependencyInfo
    /// suitable for JSON output.
    pub fn get_dependencies_info(&self, file_id: i64) -> Result<Vec<DependencyInfo>> {
        let deps = self.get_dependencies(file_id)?;

        let dep_infos = deps
            .into_iter()
            .map(|dep| {
                // Try to get the resolved path (all deps are internal now)
                let path = if let Some(resolved_id) = dep.resolved_file_id {
                    // Try to get the actual file path
                    self.get_file_path(resolved_id).unwrap_or(dep.imported_path)
                } else {
                    dep.imported_path
                };

                DependencyInfo {
                    path,
                    line: Some(dep.line_number),
                    symbols: dep.imported_symbols,
                }
            })
            .collect();

        Ok(dep_infos)
    }

    /// Get transitive dependencies up to a given depth
    ///
    /// Traverses the dependency graph using BFS to find all dependencies
    /// reachable within the specified depth.
    /// Uses `resolved_file_id` column for instant SQL lookup (sub-100ms).
    ///
    /// # Arguments
    ///
    /// * `file_id` - Starting file ID
    /// * `max_depth` - Maximum traversal depth (0 = only direct deps)
    ///
    /// # Returns
    ///
    /// HashMap mapping file_id to depth (distance from start file)
    pub fn get_transitive_deps(&self, file_id: i64, max_depth: usize) -> Result<HashMap<i64, usize>> {
        let mut visited = HashMap::new();
        let mut queue = VecDeque::new();

        // Start with the initial file at depth 0
        queue.push_back((file_id, 0));
        visited.insert(file_id, 0);

        while let Some((current_id, depth)) = queue.pop_front() {
            if depth >= max_depth {
                continue;
            }

            // Get direct dependencies using resolved_file_id (instant)
            let deps = self.get_dependencies(current_id)?;

            for dep in deps {
                // Use resolved_file_id directly (already populated during indexing)
                if let Some(resolved_id) = dep.resolved_file_id {
                    // Only visit if we haven't seen it or found a shorter path
                    if !visited.contains_key(&resolved_id) {
                        visited.insert(resolved_id, depth + 1);
                        queue.push_back((resolved_id, depth + 1));
                    }
                }
            }
        }

        Ok(visited)
    }

    /// Detect circular dependencies in the entire codebase
    ///
    /// Uses depth-first search to find cycles in the dependency graph.
    /// Uses `resolved_file_id` column for instant SQL lookup (sub-100ms).
    ///
    /// Returns a list of cycle paths, where each cycle is represented as
    /// a vector of file IDs forming the cycle.
    pub fn detect_circular_dependencies(&self) -> Result<Vec<Vec<i64>>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for circular dependency analysis")?;

        // Build in-memory dependency graph using resolved_file_id (instant)
        let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();

        let mut stmt = conn.prepare(
            "SELECT file_id, resolved_file_id
             FROM file_dependencies
             WHERE resolved_file_id IS NOT NULL"
        )?;

        let dependencies: Vec<(i64, i64)> = stmt
            .query_map([], |row| {
                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
            })?
            .collect::<Result<Vec<_>, _>>()?;

        // Build adjacency list directly from resolved IDs
        for (file_id, target_id) in dependencies {
            graph.entry(file_id).or_insert_with(Vec::new).push(target_id);
        }

        // Get all file IDs for traversal
        let all_files = self.get_all_file_ids()?;

        let mut visited = HashSet::new();
        let mut rec_stack = HashSet::new();
        let mut path = Vec::new();
        let mut cycles = Vec::new();

        for file_id in all_files {
            if !visited.contains(&file_id) {
                self.dfs_cycle_detect(
                    file_id,
                    &graph,
                    &mut visited,
                    &mut rec_stack,
                    &mut path,
                    &mut cycles,
                )?;
            }
        }

        Ok(cycles)
    }

    /// DFS helper for cycle detection using pre-built graph
    fn dfs_cycle_detect(
        &self,
        file_id: i64,
        graph: &HashMap<i64, Vec<i64>>,
        visited: &mut HashSet<i64>,
        rec_stack: &mut HashSet<i64>,
        path: &mut Vec<i64>,
        cycles: &mut Vec<Vec<i64>>,
    ) -> Result<()> {
        visited.insert(file_id);
        rec_stack.insert(file_id);
        path.push(file_id);

        // Get dependencies from the pre-built graph
        if let Some(dependencies) = graph.get(&file_id) {
            for &target_id in dependencies {
                if !visited.contains(&target_id) {
                    self.dfs_cycle_detect(target_id, graph, visited, rec_stack, path, cycles)?;
                } else if rec_stack.contains(&target_id) {
                    // Found a cycle! Extract it from path
                    if let Some(cycle_start) = path.iter().position(|&id| id == target_id) {
                        let cycle = path[cycle_start..].to_vec();
                        cycles.push(cycle);
                    }
                }
            }
        }

        path.pop();
        rec_stack.remove(&file_id);

        Ok(())
    }

    /// Get file paths for a list of file IDs
    ///
    /// Useful for converting file ID results to human-readable paths.
    pub fn get_file_paths(&self, file_ids: &[i64]) -> Result<HashMap<i64, String>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for file path lookup")?;

        let mut paths = HashMap::new();

        for &file_id in file_ids {
            if let Ok(path) = conn.query_row(
                "SELECT path FROM files WHERE id = ?",
                [file_id],
                |row| row.get::<_, String>(0),
            ) {
                paths.insert(file_id, path);
            }
        }

        Ok(paths)
    }

    /// Get file path for a single file ID
    fn get_file_path(&self, file_id: i64) -> Result<String> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for file path lookup")?;

        let path = conn.query_row(
            "SELECT path FROM files WHERE id = ?",
            [file_id],
            |row| row.get::<_, String>(0),
        )?;

        Ok(path)
    }

    /// Get all file IDs in the database
    fn get_all_file_ids(&self) -> Result<Vec<i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for file ID lookup")?;

        let mut stmt = conn.prepare("SELECT id FROM files")?;
        let file_ids = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(file_ids)
    }

    /// Find hotspots (most imported files)
    ///
    /// Returns a list of (file_id, count) tuples sorted by import count descending.
    ///
    /// Uses `resolved_file_id` column for instant SQL aggregation (sub-100ms).
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of hotspots to return (None = all)
    /// * `min_dependents` - Minimum number of imports required to be a hotspot (default: 2)
    pub fn find_hotspots(&self, limit: Option<usize>, min_dependents: usize) -> Result<Vec<(i64, usize)>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for hotspot analysis")?;

        // Pure SQL aggregation on resolved_file_id (instant)
        let mut stmt = conn.prepare(
            "SELECT resolved_file_id, COUNT(*) as count
             FROM file_dependencies
             WHERE resolved_file_id IS NOT NULL
             GROUP BY resolved_file_id
             ORDER BY count DESC"
        )?;

        // Get all hotspots and filter by minimum dependent count
        let mut hotspots: Vec<(i64, usize)> = stmt
            .query_map([], |row| {
                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)? as usize))
            })?
            .collect::<Result<Vec<_>, _>>()?
            .into_iter()
            .filter(|(_, count)| *count >= min_dependents)
            .collect();

        // Apply limit if specified
        if let Some(lim) = limit {
            hotspots.truncate(lim);
        }

        Ok(hotspots)
    }

    /// Find unused files (files with no incoming dependencies)
    ///
    /// Files that are never imported are potential candidates for deletion.
    /// Uses `resolved_file_id` column for instant SQL lookup (sub-10ms).
    ///
    /// **Barrel Export Resolution**: This function now follows barrel export chains
    /// to detect files that are indirectly imported via re-exports. For example:
    /// - `WithLabel.vue` exported by `packages/ui/components/index.ts`
    /// - App imports `@packages/ui/components` (resolves to index.ts)
    /// - This function follows the export chain and marks `WithLabel.vue` as used
    pub fn find_unused_files(&self) -> Result<Vec<i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for unused files analysis")?;

        // Build set of used files by following barrel export chains
        let mut used_files = HashSet::new();

        // Step 1: Get all files directly referenced in resolved_file_id
        let mut stmt = conn.prepare(
            "SELECT DISTINCT resolved_file_id
             FROM file_dependencies
             WHERE resolved_file_id IS NOT NULL"
        )?;

        let direct_imports: Vec<i64> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        used_files.extend(&direct_imports);

        // Step 2: For each direct import, follow barrel export chains
        for file_id in direct_imports {
            // Resolve through barrel exports to find all indirectly used files
            let barrel_chain = self.resolve_through_barrel_exports(file_id)?;
            used_files.extend(barrel_chain);
        }

        // Step 3: Get all files NOT in the used set
        let mut stmt = conn.prepare("SELECT id FROM files ORDER BY id")?;
        let all_files: Vec<i64> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        let unused: Vec<i64> = all_files
            .into_iter()
            .filter(|id| !used_files.contains(id))
            .collect();

        Ok(unused)
    }

    /// Resolve barrel export chains to find all files transitively exported from a given file
    ///
    /// Given a barrel file (e.g., `index.ts` that re-exports from other files), this function
    /// follows the export chain to find all source files that are transitively exported.
    ///
    /// # Example
    ///
    /// If `packages/ui/components/index.ts` contains:
    /// ```typescript
    /// export { default as WithLabel } from './WithLabel.vue';
    /// export { default as Button } from './Button.vue';
    /// ```
    ///
    /// Then calling this with the file_id of `index.ts` will return the file IDs of
    /// `WithLabel.vue` and `Button.vue`.
    ///
    /// # Arguments
    ///
    /// * `barrel_file_id` - File ID of the barrel file to start from
    ///
    /// # Returns
    ///
    /// Vec of file IDs that are transitively exported (includes the barrel file itself)
    pub fn resolve_through_barrel_exports(&self, barrel_file_id: i64) -> Result<Vec<i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for barrel export resolution")?;

        let mut resolved_files = Vec::new();
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();

        // Start with the barrel file itself
        queue.push_back(barrel_file_id);
        visited.insert(barrel_file_id);

        while let Some(current_id) = queue.pop_front() {
            resolved_files.push(current_id);

            // Get all exports from this file
            let mut stmt = conn.prepare(
                "SELECT resolved_source_id
                 FROM file_exports
                 WHERE file_id = ? AND resolved_source_id IS NOT NULL"
            )?;

            let exported_files: Vec<i64> = stmt
                .query_map([current_id], |row| row.get(0))?
                .collect::<Result<Vec<_>, _>>()?;

            // Follow each exported file
            for exported_id in exported_files {
                if !visited.contains(&exported_id) {
                    visited.insert(exported_id);
                    queue.push_back(exported_id);
                }
            }
        }

        Ok(resolved_files)
    }

    /// Find disconnected components (islands) in the dependency graph
    ///
    /// An "island" is a connected component - a group of files that depend on each
    /// other (directly or transitively) but have no dependencies to files outside
    /// the group.
    ///
    /// This is useful for identifying:
    /// - Independent subsystems that could be extracted as separate modules
    /// - Unreachable code clusters that might be dead code
    /// - Microservice boundaries in a monolith
    ///
    /// Returns a list of islands, where each island is a vector of file IDs.
    /// Islands are sorted by size (largest first).
    pub fn find_islands(&self) -> Result<Vec<Vec<i64>>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for island analysis")?;

        // Build undirected dependency graph (A imports B => edge A-B and B-A)
        let mut graph: HashMap<i64, Vec<i64>> = HashMap::new();

        let mut stmt = conn.prepare(
            "SELECT file_id, resolved_file_id
             FROM file_dependencies
             WHERE resolved_file_id IS NOT NULL"
        )?;

        let dependencies: Vec<(i64, i64)> = stmt
            .query_map([], |row| {
                Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?))
            })?
            .collect::<Result<Vec<_>, _>>()?;

        // Build adjacency list (undirected) directly from resolved IDs
        for (file_id, target_id) in dependencies {
            // Add edge in both directions for undirected graph
            graph.entry(file_id).or_insert_with(Vec::new).push(target_id);
            graph.entry(target_id).or_insert_with(Vec::new).push(file_id);
        }

        // Get all file IDs (including isolated files with no dependencies)
        let all_files = self.get_all_file_ids()?;

        // Ensure all files are in the graph (even if they have no edges)
        for file_id in &all_files {
            graph.entry(*file_id).or_insert_with(Vec::new);
        }

        // Find connected components using DFS
        let mut visited = HashSet::new();
        let mut islands = Vec::new();

        for &file_id in &all_files {
            if !visited.contains(&file_id) {
                let mut island = Vec::new();
                self.dfs_island(&file_id, &graph, &mut visited, &mut island);
                islands.push(island);
            }
        }

        // Sort islands by size (largest first)
        islands.sort_by(|a, b| b.len().cmp(&a.len()));

        log::info!("Found {} islands (connected components)", islands.len());

        Ok(islands)
    }

    /// DFS helper for finding connected components (islands)
    fn dfs_island(
        &self,
        file_id: &i64,
        graph: &HashMap<i64, Vec<i64>>,
        visited: &mut HashSet<i64>,
        island: &mut Vec<i64>,
    ) {
        visited.insert(*file_id);
        island.push(*file_id);

        if let Some(neighbors) = graph.get(file_id) {
            for &neighbor in neighbors {
                if !visited.contains(&neighbor) {
                    self.dfs_island(&neighbor, graph, visited, island);
                }
            }
        }
    }

    /// Build a cache of imported_path → file_id mappings for efficient lookup
    ///
    /// This method queries all unique imported_path values from the database
    /// and resolves each one to a file_id using fuzzy matching. The resulting
    /// cache enables O(1) lookups instead of repeated database queries.
    ///
    /// This is used internally by graph analysis operations (hotspots, circular
    /// dependencies, reverse lookups, etc.) to avoid O(N*M*K) query complexity.
    ///
    /// # Performance
    ///
    /// Building the cache requires O(N*M) queries where:
    /// - N = number of unique imported_path values (~1,000-5,000)
    /// - M = average number of path variants tried per path (~10)
    ///
    /// However, this is done ONCE upfront, enabling O(1) lookups for all
    /// subsequent operations. Without caching, each operation would make
    /// 10,000-100,000+ queries.
    ///
    /// # Returns
    ///
    /// HashMap mapping imported_path to resolved file_id (only includes
    /// successfully resolved paths; external/unresolved paths are omitted)
    fn build_resolution_cache(&self) -> Result<HashMap<String, i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for building resolution cache")?;

        // Get all unique imported_path values (single query)
        let mut stmt = conn.prepare(
            "SELECT DISTINCT imported_path FROM file_dependencies"
        )?;

        let imported_paths: Vec<String> = stmt
            .query_map([], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        let total_paths = imported_paths.len();
        log::info!("Building resolution cache for {} unique imported paths", total_paths);

        // Resolve each imported_path once
        let mut cache = HashMap::new();

        for imported_path in imported_paths {
            if let Ok(Some(file_id)) = self.resolve_imported_path_to_file_id(&imported_path) {
                cache.insert(imported_path, file_id);
            }
        }

        log::info!(
            "Resolution cache built: {} resolved, {} unresolved",
            cache.len(),
            total_paths - cache.len()
        );

        Ok(cache)
    }

    /// Clear all dependencies for a file (used during incremental reindexing)
    pub fn clear_dependencies(&self, file_id: i64) -> Result<()> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for dependency clearing")?;

        conn.execute(
            "DELETE FROM file_dependencies WHERE file_id = ?",
            [file_id],
        )?;

        Ok(())
    }

    /// Resolve an imported path to a file ID using fuzzy matching
    ///
    /// This method converts an import path (e.g., namespace, module path) to various
    /// file path variants and tries to find a matching file using fuzzy path matching.
    ///
    /// # Arguments
    ///
    /// * `imported_path` - The import path as stored in the database
    ///   (e.g., "Rcm\\Http\\Controllers\\Controller", "crate::models", etc.)
    ///
    /// # Returns
    ///
    /// `Some(file_id)` if exactly one matching file is found, `None` otherwise
    ///
    /// # Examples
    ///
    /// - `Rcm\\Http\\Controllers\\Controller` → finds `services/php/rcm-backend/app/Http/Controllers/Controller.php`
    /// - `crate::models` → finds `src/models.rs`
    pub fn resolve_imported_path_to_file_id(&self, imported_path: &str) -> Result<Option<i64>> {
        let path_variants = generate_path_variants(imported_path);

        for variant in &path_variants {
            if let Ok(Some(file_id)) = self.get_file_id_by_path(variant) {
                log::trace!("Resolved '{}' → '{}' (file_id: {})", imported_path, variant, file_id);
                return Ok(Some(file_id));
            }
        }

        Ok(None)
    }

    /// Get file ID by path with fuzzy matching support
    ///
    /// Supports various path formats:
    /// - Exact paths: `services/php/app/Http/Controllers/FooController.php`
    /// - Relative paths: `./services/php/app/Http/Controllers/FooController.php`
    /// - Path fragments: `Controllers/FooController.php` or `FooController.php`
    /// - Absolute paths: `/home/user/project/services/php/.../FooController.php`
    ///
    /// Returns None if no matches found.
    /// Returns error if multiple matches found (ambiguous path fragment).
    pub fn get_file_id_by_path(&self, path: &str) -> Result<Option<i64>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for file ID lookup")?;

        // Normalize path: strip ./ prefix, ../ prefix, and convert absolute to relative
        let normalized_path = normalize_path_for_lookup(path);

        // Try exact match first (fast path)
        match conn.query_row(
            "SELECT id FROM files WHERE path = ?",
            [&normalized_path],
            |row| row.get::<_, i64>(0),
        ) {
            Ok(id) => return Ok(Some(id)),
            Err(rusqlite::Error::QueryReturnedNoRows) => {
                // No exact match, try suffix match
            }
            Err(e) => return Err(e.into()),
        }

        // Try suffix match: find all files whose path ends with the normalized_path
        let mut stmt = conn.prepare(
            "SELECT id, path FROM files WHERE path LIKE '%' || ?"
        )?;

        let matches: Vec<(i64, String)> = stmt
            .query_map([&normalized_path], |row| {
                Ok((row.get(0)?, row.get(1)?))
            })?
            .collect::<Result<Vec<_>, _>>()?;

        match matches.len() {
            0 => Ok(None),
            1 => Ok(Some(matches[0].0)),
            _ => {
                // Multiple matches - return error with suggestions
                let paths: Vec<String> = matches.iter().map(|(_, p)| p.clone()).collect();
                anyhow::bail!(
                    "Ambiguous path '{}' matches multiple files:\n  {}\n\nPlease be more specific.",
                    path,
                    paths.join("\n  ")
                );
            }
        }
    }

    /// Get dependency resolution statistics grouped by language
    ///
    /// Returns statistics showing how many internal dependencies are resolved vs unresolved
    /// for each language in the project.
    ///
    /// # Returns
    ///
    /// A vector of tuples: (language, total_deps, resolved_deps, resolution_rate)
    pub fn get_resolution_stats(&self) -> Result<Vec<(String, usize, usize, f64)>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for resolution stats")?;

        let mut stmt = conn.prepare(
            "SELECT
                CASE
                    WHEN f.path LIKE '%.py' THEN 'Python'
                    WHEN f.path LIKE '%.go' THEN 'Go'
                    WHEN f.path LIKE '%.ts' THEN 'TypeScript'
                    WHEN f.path LIKE '%.rs' THEN 'Rust'
                    WHEN f.path LIKE '%.js' OR f.path LIKE '%.jsx' THEN 'JavaScript'
                    WHEN f.path LIKE '%.php' THEN 'PHP'
                    WHEN f.path LIKE '%.java' THEN 'Java'
                    WHEN f.path LIKE '%.kt' THEN 'Kotlin'
                    WHEN f.path LIKE '%.rb' THEN 'Ruby'
                    WHEN f.path LIKE '%.c' OR f.path LIKE '%.h' THEN 'C'
                    WHEN f.path LIKE '%.cpp' OR f.path LIKE '%.cc' OR f.path LIKE '%.hpp' THEN 'C++'
                    WHEN f.path LIKE '%.cs' THEN 'C#'
                    WHEN f.path LIKE '%.zig' THEN 'Zig'
                    ELSE 'Other'
                END as language,
                COUNT(*) as total,
                SUM(CASE WHEN d.resolved_file_id IS NOT NULL THEN 1 ELSE 0 END) as resolved
            FROM file_dependencies d
            JOIN files f ON d.file_id = f.id
            WHERE d.import_type = 'internal'
            GROUP BY language
            ORDER BY language",
        )?;

        let mut stats = Vec::new();

        let rows = stmt.query_map([], |row| {
            let language: String = row.get(0)?;
            let total: i64 = row.get(1)?;
            let resolved: i64 = row.get(2)?;
            let rate = if total > 0 {
                (resolved as f64 / total as f64) * 100.0
            } else {
                0.0
            };

            Ok((language, total as usize, resolved as usize, rate))
        })?;

        for row in rows {
            stats.push(row?);
        }

        Ok(stats)
    }

    /// Get all internal dependencies with their resolution status
    ///
    /// Returns detailed information about each internal dependency including source file,
    /// imported path, and whether it was successfully resolved.
    ///
    /// # Returns
    ///
    /// A vector of tuples: (source_file, imported_path, resolved_file_path)
    /// where resolved_file_path is None if the dependency couldn't be resolved.
    pub fn get_all_internal_dependencies(&self) -> Result<Vec<(String, String, Option<String>)>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for internal dependencies")?;

        let mut stmt = conn.prepare(
            "SELECT
                f.path,
                d.imported_path,
                f2.path as resolved_path
            FROM file_dependencies d
            JOIN files f ON d.file_id = f.id
            LEFT JOIN files f2 ON d.resolved_file_id = f2.id
            WHERE d.import_type = 'internal'
            ORDER BY f.path",
        )?;

        let mut deps = Vec::new();

        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, Option<String>>(2)?,
            ))
        })?;

        for row in rows {
            deps.push(row?);
        }

        Ok(deps)
    }

    /// Get total count of dependencies by type (for debugging)
    pub fn get_dependency_count_by_type(&self) -> Result<Vec<(String, usize)>> {
        let db_path = self.cache.path().join("meta.db");
        let conn = Connection::open(&db_path)
            .context("Failed to open meta.db for dependency count")?;

        let mut stmt = conn.prepare(
            "SELECT import_type, COUNT(*) as count
             FROM file_dependencies
             GROUP BY import_type
             ORDER BY import_type",
        )?;

        let mut counts = Vec::new();

        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, i64>(1)? as usize,
            ))
        })?;

        for row in rows {
            counts.push(row?);
        }

        Ok(counts)
    }
}

/// Generate path variants for an import path
///
/// Converts a namespace/import path to multiple file path variants for fuzzy matching.
/// Tries progressively shorter paths to handle custom PSR-4 mappings.
///
/// Examples:
/// - `Rcm\\Http\\Controllers\\Controller` →
///   - `Rcm/Http/Controllers/Controller.php`
///   - `Http/Controllers/Controller.php`
///   - `Controllers/Controller.php`
///   - `Controller.php`
fn generate_path_variants(import_path: &str) -> Vec<String> {
    // Convert namespace separators to path separators
    let path = import_path.replace('\\', "/").replace("::", "/");

    // Remove quotes if present (some languages quote import paths)
    let path = path.trim_matches('"').trim_matches('\'');

    // Split into components
    let components: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    if components.is_empty() {
        return vec![];
    }

    let mut variants = Vec::new();

    // Generate progressively shorter paths
    // E.g., for "Rcm/Http/Controllers/Controller":
    // 1. Rcm/Http/Controllers/Controller.php (full path)
    // 2. Http/Controllers/Controller.php (without first component)
    // 3. Controllers/Controller.php (without first two)
    // 4. Controller.php (just the class name)
    for start_idx in 0..components.len() {
        let suffix = components[start_idx..].join("/");

        // Try with .php extension (most common)
        if !suffix.ends_with(".php") {
            variants.push(format!("{}.php", suffix));
        } else {
            variants.push(suffix.clone());
        }

        // Also try without extension (for languages that don't use extensions in imports)
        if !suffix.contains('.') {
            // Try common extensions
            variants.push(format!("{}.rs", suffix));
            variants.push(format!("{}.ts", suffix));
            variants.push(format!("{}.js", suffix));
            variants.push(format!("{}.py", suffix));
        }
    }

    variants
}

/// Normalize a path for fuzzy lookup
///
/// Strips common prefixes that might differ between query and database:
/// - `./` and `../` prefixes
/// - Absolute paths (converts to relative by taking only the path component)
///
/// Examples:
/// - `./services/foo.php` → `services/foo.php`
/// - `/home/user/project/services/foo.php` → `services/foo.php` (just filename portion)
/// - `GetCaseByBatchNumberController.php` → `GetCaseByBatchNumberController.php`
fn normalize_path_for_lookup(path: &str) -> String {
    // Strip ./ and ../ prefixes
    let mut normalized = path.trim_start_matches("./").to_string();
    if normalized.starts_with("../") {
        normalized = normalized.trim_start_matches("../").to_string();
    }

    // If it's an absolute path, extract the relevant portion
    // This handles cases like `/home/user/Code/project/services/php/...`
    // We want to extract just `services/php/...` part
    if normalized.starts_with('/') || normalized.starts_with('\\') {
        // Common project markers (ordered by priority)
        let markers = ["services", "src", "app", "lib", "packages", "modules"];

        let mut found_marker = false;
        for marker in &markers {
            if let Some(idx) = normalized.find(marker) {
                normalized = normalized[idx..].to_string();
                found_marker = true;
                break;
            }
        }

        // If no marker found, just use the filename
        if !found_marker {
            use std::path::Path;
            let path_obj = Path::new(&normalized);
            if let Some(filename) = path_obj.file_name() {
                normalized = filename.to_string_lossy().to_string();
            }
        }
    }

    normalized
}

/// Resolve a Rust import path to an absolute file path
///
/// This function handles Rust-specific path resolution rules:
/// - `crate::` - Starts from crate root (src/lib.rs or src/main.rs)
/// - `super::` - Goes up one module level
/// - `self::` - Stays in current module
/// - `mod name` - Looks for name.rs or name/mod.rs
/// - External crates - Returns None
///
/// # Arguments
///
/// * `import_path` - The import path as written in source (e.g., "crate::models::Language")
/// * `current_file` - Path to the file containing the import (e.g., "src/query.rs")
/// * `project_root` - Root directory of the project
///
/// # Returns
///
/// `Some(path)` if the import resolves to a project file, `None` if it's external/stdlib
pub fn resolve_rust_import(
    import_path: &str,
    current_file: &str,
    project_root: &std::path::Path,
) -> Option<String> {
    use std::path::{Path, PathBuf};

    // External crates and stdlib - don't resolve
    if !import_path.starts_with("crate::")
        && !import_path.starts_with("super::")
        && !import_path.starts_with("self::")
    {
        return None;
    }

    let current_path = Path::new(current_file);
    let mut resolved_path: Option<PathBuf> = None;

    if import_path.starts_with("crate::") {
        // Start from crate root (src/lib.rs or src/main.rs)
        let crate_root = if project_root.join("src/lib.rs").exists() {
            project_root.join("src")
        } else if project_root.join("src/main.rs").exists() {
            project_root.join("src")
        } else {
            // Fallback to src/ directory
            project_root.join("src")
        };

        let path_parts: Vec<&str> = import_path
            .strip_prefix("crate::")
            .unwrap()
            .split("::")
            .collect();

        resolved_path = resolve_module_path(&crate_root, &path_parts);
    } else if import_path.starts_with("super::") {
        // Go up one directory from current file's parent (the current module's parent)
        if let Some(current_dir) = current_path.parent() {
            if let Some(parent_dir) = current_dir.parent() {
                let path_parts: Vec<&str> = import_path
                    .strip_prefix("super::")
                    .unwrap()
                    .split("::")
                    .collect();

                resolved_path = resolve_module_path(parent_dir, &path_parts);
            }
        }
    } else if import_path.starts_with("self::") {
        // Stay in current directory
        if let Some(current_dir) = current_path.parent() {
            let path_parts: Vec<&str> = import_path
                .strip_prefix("self::")
                .unwrap()
                .split("::")
                .collect();

            resolved_path = resolve_module_path(current_dir, &path_parts);
        }
    }

    // Convert to string and make relative to project root
    resolved_path.and_then(|p| {
        p.strip_prefix(project_root)
            .ok()
            .map(|rel| rel.to_string_lossy().to_string())
    })
}

/// Resolve a module path given a starting directory and path components
///
/// Handles Rust's module system rules:
/// - `foo` → check foo.rs or foo/mod.rs
/// - `foo::bar` → check foo/bar.rs or foo/bar/mod.rs
fn resolve_module_path(start_dir: &std::path::Path, components: &[&str]) -> Option<std::path::PathBuf> {

    if components.is_empty() {
        return None;
    }

    let mut current = start_dir.to_path_buf();

    // For all components except the last, they must be directories
    for &component in &components[..components.len() - 1] {
        // Try as a directory with mod.rs
        let dir_path = current.join(component);
        let mod_file = dir_path.join("mod.rs");

        if mod_file.exists() {
            current = dir_path;
        } else {
            // Component must be a directory for nested paths
            return None;
        }
    }

    // For the last component, try both file.rs and file/mod.rs
    let last_component = components.last().unwrap();

    // Try as a single file
    let file_path = current.join(format!("{}.rs", last_component));
    if file_path.exists() {
        return Some(file_path);
    }

    // Try as a directory with mod.rs
    let dir_path = current.join(last_component);
    let mod_file = dir_path.join("mod.rs");
    if mod_file.exists() {
        return Some(mod_file);
    }

    None
}

/// Resolve a `mod` declaration to a file path
///
/// For `mod parser;`, this checks for:
/// - `parser.rs` (sibling file)
/// - `parser/mod.rs` (directory module)
pub fn resolve_rust_mod_declaration(
    mod_name: &str,
    current_file: &str,
    _project_root: &std::path::Path,
) -> Option<String> {
    use std::path::Path;

    let current_path = Path::new(current_file);
    let current_dir = current_path.parent()?;

    // Try sibling file
    let sibling = current_dir.join(format!("{}.rs", mod_name));
    if sibling.exists() {
        return Some(sibling.to_string_lossy().to_string());
    }

    // Try directory module
    let dir_mod = current_dir.join(mod_name).join("mod.rs");
    if dir_mod.exists() {
        return Some(dir_mod.to_string_lossy().to_string());
    }

    None
}

/// Resolve a PHP import path to a file path
///
/// This function handles PHP-specific namespace-to-file mapping:
/// - Converts backslash-separated namespaces to forward-slash paths
/// - Handles PSR-4 autoloading conventions
/// - Filters out external vendor namespaces (returns None for non-project code)
///
/// # Arguments
///
/// * `import_path` - PHP namespace path (e.g., "App\\Http\\Controllers\\UserController")
/// * `current_file` - Not used for PHP (PHP uses absolute namespaces)
/// * `project_root` - Root directory of the project
///
/// # Returns
///
/// `Some(path)` if the import resolves to a project file, `None` if it's external/stdlib
///
/// # Examples
///
/// - `App\\Http\\Controllers\\FooController` → `app/Http/Controllers/FooController.php`
/// - `App\\Models\\User` → `app/Models/User.php`
/// - `Illuminate\\Database\\Migration` → `None` (external vendor namespace)
pub fn resolve_php_import(
    import_path: &str,
    _current_file: &str,
    project_root: &std::path::Path,
) -> Option<String> {
    // External vendor namespaces (Laravel, Symfony, etc.) - don't resolve
    const VENDOR_NAMESPACES: &[&str] = &[
        "Illuminate\\", "Symfony\\", "Laravel\\", "Psr\\",
        "Doctrine\\", "Monolog\\", "PHPUnit\\", "Carbon\\",
        "GuzzleHttp\\", "Composer\\", "Predis\\", "League\\"
    ];

    // Check if this is a vendor namespace
    for vendor_ns in VENDOR_NAMESPACES {
        if import_path.starts_with(vendor_ns) {
            return None;
        }
    }

    // Convert namespace to file path
    // PHP namespaces use backslashes: App\Http\Controllers\FooController
    // Files use forward slashes: app/Http/Controllers/FooController.php
    let file_path = import_path.replace('\\', "/");

    // Try common PSR-4 mappings (lowercase first component)
    // App\... → app/...
    // Database\... → database/...
    let path_candidates = vec![
        // Try with lowercase first component (PSR-4 standard)
        {
            let parts: Vec<&str> = file_path.split('/').collect();
            if let Some(first) = parts.first() {
                let mut result = vec![first.to_lowercase()];
                result.extend(parts[1..].iter().map(|s| s.to_string()));
                result.join("/") + ".php"
            } else {
                file_path.clone() + ".php"
            }
        },
        // Try exact path (some projects use exact case)
        file_path.clone() + ".php",
        // Try all lowercase (legacy projects)
        file_path.to_lowercase() + ".php",
    ];

    // Check each candidate path
    for candidate in &path_candidates {
        let full_path = project_root.join(candidate);
        if full_path.exists() {
            // Return relative path
            return Some(candidate.clone());
        }
    }

    // If no file found, return None (likely external or not yet created)
    None
}

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

    fn setup_test_cache() -> (TempDir, CacheManager) {
        let temp = TempDir::new().unwrap();
        let cache = CacheManager::new(temp.path());
        cache.init().unwrap();

        // Add some test files
        cache.update_file("src/main.rs", "rust", 100).unwrap();
        cache.update_file("src/lib.rs", "rust", 50).unwrap();
        cache.update_file("src/utils.rs", "rust", 30).unwrap();

        (temp, cache)
    }

    #[test]
    fn test_insert_and_get_dependencies() {
        let (_temp, cache) = setup_test_cache();
        let deps_index = DependencyIndex::new(cache);

        // Get file IDs
        let main_id = 1i64;
        let lib_id = 2i64;

        // Insert a dependency: main.rs imports lib.rs
        deps_index
            .insert_dependency(
                main_id,
                "crate::lib".to_string(),
                Some(lib_id),
                ImportType::Internal,
                5,
                None,
            )
            .unwrap();

        // Retrieve dependencies
        let deps = deps_index.get_dependencies(main_id).unwrap();
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].imported_path, "crate::lib");
        assert_eq!(deps[0].resolved_file_id, Some(lib_id));
        assert_eq!(deps[0].import_type, ImportType::Internal);
    }

    #[test]
    fn test_reverse_lookup() {
        let (_temp, cache) = setup_test_cache();
        let deps_index = DependencyIndex::new(cache);

        let main_id = 1i64;
        let lib_id = 2i64;
        let utils_id = 3i64;

        // main.rs imports lib.rs
        deps_index
            .insert_dependency(
                main_id,
                "crate::lib".to_string(),
                Some(lib_id),
                ImportType::Internal,
                5,
                None,
            )
            .unwrap();

        // utils.rs also imports lib.rs
        deps_index
            .insert_dependency(
                utils_id,
                "crate::lib".to_string(),
                Some(lib_id),
                ImportType::Internal,
                3,
                None,
            )
            .unwrap();

        // Get files that import lib.rs
        let dependents = deps_index.get_dependents(lib_id).unwrap();
        assert_eq!(dependents.len(), 2);
        assert!(dependents.contains(&main_id));
        assert!(dependents.contains(&utils_id));
    }

    #[test]
    fn test_transitive_dependencies() {
        let (_temp, cache) = setup_test_cache();
        let deps_index = DependencyIndex::new(cache);

        let file1 = 1i64;
        let file2 = 2i64;
        let file3 = 3i64;

        // file1 → file2 → file3
        deps_index
            .insert_dependency(
                file1,
                "file2".to_string(),
                Some(file2),
                ImportType::Internal,
                1,
                None,
            )
            .unwrap();

        deps_index
            .insert_dependency(
                file2,
                "file3".to_string(),
                Some(file3),
                ImportType::Internal,
                1,
                None,
            )
            .unwrap();

        // Get transitive deps at depth 2
        let transitive = deps_index.get_transitive_deps(file1, 2).unwrap();

        // Should include file1 (depth 0), file2 (depth 1), file3 (depth 2)
        assert_eq!(transitive.len(), 3);
        assert_eq!(transitive.get(&file1), Some(&0));
        assert_eq!(transitive.get(&file2), Some(&1));
        assert_eq!(transitive.get(&file3), Some(&2));
    }

    #[test]
    fn test_batch_insert() {
        let (_temp, cache) = setup_test_cache();
        let deps_index = DependencyIndex::new(cache);

        let deps = vec![
            Dependency {
                file_id: 1,
                imported_path: "std::collections".to_string(),
                resolved_file_id: None,
                import_type: ImportType::Stdlib,
                line_number: 1,
                imported_symbols: Some(vec!["HashMap".to_string()]),
            },
            Dependency {
                file_id: 1,
                imported_path: "crate::lib".to_string(),
                resolved_file_id: Some(2),
                import_type: ImportType::Internal,
                line_number: 2,
                imported_symbols: None,
            },
        ];

        deps_index.batch_insert_dependencies(&deps).unwrap();

        let retrieved = deps_index.get_dependencies(1).unwrap();
        assert_eq!(retrieved.len(), 2);
    }

    #[test]
    fn test_clear_dependencies() {
        let (_temp, cache) = setup_test_cache();
        let deps_index = DependencyIndex::new(cache);

        // Insert dependencies
        deps_index
            .insert_dependency(
                1,
                "crate::lib".to_string(),
                Some(2),
                ImportType::Internal,
                1,
                None,
            )
            .unwrap();

        // Verify they exist
        assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 1);

        // Clear them
        deps_index.clear_dependencies(1).unwrap();

        // Verify they're gone
        assert_eq!(deps_index.get_dependencies(1).unwrap().len(), 0);
    }

    #[test]
    fn test_resolve_rust_import_crate() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_root = temp.path();

        // Create directory structure
        fs::create_dir_all(project_root.join("src")).unwrap();
        fs::write(project_root.join("src/lib.rs"), "").unwrap();
        fs::write(project_root.join("src/models.rs"), "").unwrap();

        // Test crate:: resolution
        let resolved = resolve_rust_import(
            "crate::models",
            "src/query.rs",
            project_root,
        );

        assert_eq!(resolved, Some("src/models.rs".to_string()));
    }

    #[test]
    fn test_resolve_rust_import_super() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_root = temp.path();

        // Create directory structure: src/parsers/rust.rs needs to import src/models.rs
        fs::create_dir_all(project_root.join("src/parsers")).unwrap();
        fs::write(project_root.join("src/models.rs"), "").unwrap();
        fs::write(project_root.join("src/parsers/rust.rs"), "").unwrap();

        // Test super:: resolution from parsers/rust.rs
        // Use absolute path for current_file
        let current_file = project_root.join("src/parsers/rust.rs");
        let resolved = resolve_rust_import(
            "super::models",
            &current_file.to_string_lossy(),
            project_root,
        );

        assert_eq!(resolved, Some("src/models.rs".to_string()));
    }

    #[test]
    fn test_resolve_rust_import_external() {
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_root = temp.path();

        // External crates should return None
        let resolved = resolve_rust_import(
            "serde::Serialize",
            "src/models.rs",
            project_root,
        );

        assert_eq!(resolved, None);

        // Stdlib should return None
        let resolved = resolve_rust_import(
            "std::collections::HashMap",
            "src/models.rs",
            project_root,
        );

        assert_eq!(resolved, None);
    }

    #[test]
    fn test_resolve_rust_mod_declaration() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_root = temp.path();

        // Create directory structure
        fs::create_dir_all(project_root.join("src")).unwrap();
        fs::write(project_root.join("src/lib.rs"), "").unwrap();
        fs::write(project_root.join("src/parser.rs"), "").unwrap();

        // Test mod declaration resolution
        let resolved = resolve_rust_mod_declaration(
            "parser",
            &project_root.join("src/lib.rs").to_string_lossy(),
            project_root,
        );

        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("src/parser.rs"));
    }

    #[test]
    fn test_resolve_rust_import_nested() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let project_root = temp.path();

        // Create directory structure: src/models/language.rs
        fs::create_dir_all(project_root.join("src/models")).unwrap();
        fs::write(project_root.join("src/models/mod.rs"), "").unwrap();
        fs::write(project_root.join("src/models/language.rs"), "").unwrap();

        // Test nested module resolution
        let resolved = resolve_rust_import(
            "crate::models::language",
            "src/query.rs",
            project_root,
        );

        assert_eq!(resolved, Some("src/models/language.rs".to_string()));
    }
}