tldr-core 0.1.2

Core analysis engine for TLDR code analysis tool
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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
//! Module Index for bidirectional module path <-> file path mapping.
//!
//! This module provides the `ModuleIndex` struct which maintains a mapping between
//! Python module paths (e.g., "myapp.utils") and their corresponding file paths
//! (e.g., "src/myapp/utils.py").
//!
//! # Overview
//!
//! The `ModuleIndex` is designed for:
//! - O(1) lookup of file paths from module names
//! - O(1) reverse lookup of module names from file paths
//! - Proper handling of Python packages (`__init__.py`)
//! - Support for namespace packages (PEP 420)
//! - Symlink resolution to canonical paths
//! - Platform-specific case sensitivity handling
//!
//! # Example
//!
//! ```rust,ignore
//! use tldr_core::callgraph::module_index::ModuleIndex;
//! use std::path::Path;
//!
//! let index = ModuleIndex::build(Path::new("src"), "python")?;
//!
//! // Forward lookup: module -> file
//! assert!(index.lookup("myapp.utils").is_some());
//!
//! // Reverse lookup: file -> module
//! assert_eq!(index.reverse_lookup(Path::new("src/myapp/utils.py")), Some("myapp.utils"));
//!
//! // Check if module is in project
//! assert!(index.is_project_module("myapp.utils"));
//! assert!(!index.is_project_module("os"));  // stdlib, not in project
//! ```
//!
//! # Spec Reference
//!
//! See `migration/spec/callgraph-spec.md` Section 4 for the full behavioral specification.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use ignore::WalkBuilder;
use lazy_static::lazy_static;
use regex::Regex;
use serde_json::Value as JsonValue;
use thiserror::Error;

/// Errors that can occur during module indexing.
#[derive(Debug, Error)]
pub enum ModuleIndexError {
    /// IO error during directory traversal
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    /// Path is outside project root (security check)
    #[error("Path outside project root: {0}")]
    PathOutsideRoot(PathBuf),

    /// Invalid UTF-8 in path
    #[error("Invalid UTF-8 in path: {0}")]
    InvalidUtf8(PathBuf),
}

/// Module Index for bidirectional module path <-> file path mapping.
///
/// This struct maintains two HashMaps for O(1) lookups in both directions:
/// - `module_to_file`: module path -> file path
/// - `file_to_module`: file path -> module path
///
/// It also tracks namespace packages (directories with Python files but no `__init__.py`).
#[derive(Debug, Default)]
pub struct ModuleIndex {
    /// Project root directory (canonical path)
    project_root: PathBuf,
    /// Module name to file path mapping
    module_to_file: HashMap<String, PathBuf>,
    /// File path to module name mapping
    file_to_module: HashMap<PathBuf, String>,
    /// Set of namespace packages (PEP 420)
    namespace_packages: HashSet<String>,
    /// Language being indexed (affects module naming)
    language: String,
    /// Detected build metadata for improved module resolution
    metadata: ModuleIndexMetadata,
}

/// Build metadata used to refine module naming/aliasing.
#[derive(Debug, Default, Clone)]
struct ModuleIndexMetadata {
    python_src_root: Option<PathBuf>,
    ts_base_url: Option<PathBuf>,
    ts_paths: Vec<TsPathMapping>,
    js_package_name: Option<String>,
    go_module_path: Option<String>,
    rust_crate_name: Option<String>,
    php_psr4: Vec<(String, PathBuf)>,
}

#[derive(Debug, Clone, Default)]
struct TsPathMapping {
    alias_pattern: String,
    target_patterns: Vec<String>,
}

impl ModuleIndex {
    /// Creates a new empty ModuleIndex.
    pub fn new(project_root: PathBuf, language: &str) -> Self {
        let metadata = ModuleIndexMetadata::detect(&project_root, language);
        Self {
            project_root,
            module_to_file: HashMap::new(),
            file_to_module: HashMap::new(),
            namespace_packages: HashSet::new(),
            language: language.to_lowercase(),
            metadata,
        }
    }

    /// Build index from project root for given language.
    ///
    /// Walks the directory tree, skipping common non-source directories
    /// (`__pycache__`, `.git`, `venv`, `node_modules`, etc.).
    ///
    /// # Arguments
    ///
    /// * `root` - Project root directory to scan
    /// * `language` - Programming language ("python", "typescript", "rust", "go")
    ///
    /// # Returns
    ///
    /// A populated `ModuleIndex` or an error.
    ///
    /// # Errors
    ///
    /// Returns `ModuleIndexError::Io` if the root directory cannot be accessed.
    pub fn build(root: &Path, language: &str) -> Result<Self, ModuleIndexError> {
        Self::build_with_ignore(root, language, true)
    }

    /// Build index with configurable gitignore handling.
    ///
    /// # Arguments
    ///
    /// * `root` - Project root directory to scan
    /// * `language` - Programming language
    /// * `respect_ignore` - Whether to respect `.gitignore` patterns
    pub fn build_with_ignore(
        root: &Path,
        language: &str,
        respect_ignore: bool,
    ) -> Result<Self, ModuleIndexError> {
        // Resolve to canonical path for symlink handling
        let canonical_root = resolve_path(root, root)?;

        let mut index = Self::new(canonical_root.clone(), language);

        // Track directories that contain Python files (for namespace package detection)
        let mut dirs_with_py_files: HashSet<PathBuf> = HashSet::new();
        // Track directories with __init__.py (regular packages)
        let mut dirs_with_init: HashSet<PathBuf> = HashSet::new();

        // Get language-specific file extension
        let extensions = get_language_extensions(language);

        // Build the walker with common exclusions
        let walker = WalkBuilder::new(&canonical_root)
            .hidden(true) // Skip hidden files/dirs
            .git_ignore(respect_ignore)
            .git_global(respect_ignore)
            .git_exclude(respect_ignore)
            .filter_entry(|entry| {
                // Skip common non-source directories
                let file_name = entry.file_name().to_string_lossy();
                !should_skip_directory(&file_name)
            })
            .build();

        // First pass: collect all relevant files
        let mut files: Vec<PathBuf> = Vec::new();

        for entry in walker.flatten() {
            let path = entry.path();

            // Skip if not a file
            if !path.is_file() {
                continue;
            }

            // Check extension
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .map(|e| e.to_lowercase());

            let is_relevant = ext
                .as_ref()
                .map(|e| extensions.contains(&e.as_str()))
                .unwrap_or(false);

            if !is_relevant {
                continue;
            }

            // Resolve symlinks
            let canonical = match resolve_path(path, &canonical_root) {
                Ok(p) => p,
                Err(_) => continue, // Skip invalid paths
            };

            // Track directory for namespace package detection (Python)
            if language == "python" {
                if let Some(parent) = canonical.parent() {
                    dirs_with_py_files.insert(parent.to_path_buf());

                    // Check if this is an __init__.py
                    let file_name = canonical.file_name().and_then(|n| n.to_str()).unwrap_or("");
                    if file_name == "__init__.py" {
                        dirs_with_init.insert(parent.to_path_buf());
                    }
                }
            }

            files.push(canonical);
        }

        // Detect namespace packages (dirs with .py files but no __init__.py)
        if language == "python" {
            for dir in &dirs_with_py_files {
                if !dirs_with_init.contains(dir) {
                    let module = index.path_to_module(dir);
                    if !module.is_empty() {
                        index.namespace_packages.insert(module);
                    }
                }
            }
        }

        // Second pass: index files
        // Process packages (__init__.py) first, then modules
        // This ensures package wins over module when both exist
        let mut init_files: Vec<PathBuf> = Vec::new();
        let mut other_files: Vec<PathBuf> = Vec::new();

        for path in files {
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

            if language == "python" && file_name == "__init__.py" {
                init_files.push(path);
            } else {
                other_files.push(path);
            }
        }

        // Index packages first
        for path in init_files {
            index.index_file(&path)?;
        }

        // Then index modules (skipping if package already exists)
        for path in other_files {
            let module = index.compute_module_name(&path);

            // Check for package/module conflict
            // If a package with same name exists, skip the standalone module
            if language == "python" && !module.is_empty() {
                // For pkg.py when pkg/__init__.py exists, skip pkg.py
                if index.module_to_file.contains_key(&module) {
                    continue;
                }
            }

            index.index_file(&path)?;
        }

        Ok(index)
    }

    /// Index a single file.
    fn index_file(&mut self, path: &Path) -> Result<(), ModuleIndexError> {
        let module = self.compute_module_name(path);

        if module.is_empty() {
            return Ok(());
        }

        let normalized_module = normalize_module_key(&module);

        // Store mapping in both directions
        self.module_to_file
            .insert(normalized_module.clone(), path.to_path_buf());
        self.file_to_module
            .insert(path.to_path_buf(), normalized_module.clone());

        // Index alias keys for language-specific resolution (CROSSFILE parity)
        let mut aliases = self.compute_module_aliases(&module, path);
        if let Some(declared) = self.declared_package_alias(path) {
            aliases.push(declared);
        }

        for alias in aliases {
            let normalized_alias = normalize_module_key(&alias);
            self.module_to_file
                .entry(normalized_alias)
                .or_insert_with(|| path.to_path_buf());
        }

        Ok(())
    }

    /// Compute module name from file path.
    fn compute_module_name(&self, path: &Path) -> String {
        match self.language.as_str() {
            "python" => self.compute_python_module_name(path),
            "typescript" | "javascript" => self.compute_typescript_module_name(path),
            "rust" => self.compute_rust_module_name(path),
            "go" => self.compute_go_module_name(path),
            "java" => self.compute_java_module_name(path),
            "kotlin" => self.compute_kotlin_module_name(path),
            "scala" => self.compute_scala_module_name(path),
            "csharp" | "c#" => self.compute_csharp_module_name(path),
            "php" => self.compute_php_module_name(path),
            "ruby" => self.compute_ruby_module_name(path),
            "lua" => self.compute_lua_module_name(path),
            "luau" => self.compute_lua_module_name(path),
            "elixir" => self.compute_elixir_module_name(path),
            "swift" => self.compute_swift_module_name(path),
            "c" => self.compute_c_module_name(path),
            "cpp" | "c++" => self.compute_cpp_module_name(path),
            "ocaml" => self.compute_ocaml_module_name(path),
            _ => self.compute_python_module_name(path), // Fallback
        }
    }

    /// Compute alias module keys for language-specific resolution.
    fn compute_module_aliases(&self, module: &str, path: &Path) -> Vec<String> {
        let mut aliases = Vec::new();

        // Generic "simple name" alias (last segment)
        let simple = simple_module_name(module);
        if simple != module {
            aliases.push(simple.to_string());
        }

        match self.language.as_str() {
            "typescript" | "javascript" => {
                let module_no_dot = module.strip_prefix("./").unwrap_or(module);
                aliases.push(module_no_dot.to_string());

                let mut stripped_by_base_url: Option<String> = None;
                if let Some(base_url) = &self.metadata.ts_base_url {
                    if let Ok(rel) = base_url.strip_prefix(&self.project_root) {
                        let base = normalize_relative_str(rel);
                        let normalized = module.replace('\\', "/");
                        let candidates = [
                            format!("./{}/", base),
                            format!("{}/", base),
                            format!("./{}", base),
                            base.clone(),
                        ];
                        for prefix in candidates {
                            if normalized.starts_with(&prefix) {
                                let stripped = normalized[prefix.len()..].trim_start_matches('/');
                                if !stripped.is_empty() {
                                    aliases.push(stripped.to_string());
                                    stripped_by_base_url = Some(stripped.to_string());
                                }
                            }
                        }
                    }
                }
                if let Some(pkg) = &self.metadata.js_package_name {
                    let base = stripped_by_base_url
                        .as_deref()
                        .unwrap_or(module_no_dot)
                        .trim_start_matches('/');
                    if base.is_empty() {
                        aliases.push(pkg.to_string());
                    } else {
                        aliases.push(format!("{}/{}", pkg, base));
                    }
                }
                if is_ts_index_file(path) {
                    aliases.push(format!("{}/index", module));
                    if module_no_dot != module {
                        aliases.push(format!("{}/index", module_no_dot));
                    }
                }
                aliases.extend(ts_path_aliases_for_file(
                    path,
                    &self.project_root,
                    self.metadata.ts_base_url.as_ref(),
                    &self.metadata.ts_paths,
                ));
            }
            "rust" => {
                if let Some(stripped) = module.strip_prefix("crate::") {
                    aliases.push(stripped.to_string());
                }
                if let Some(crate_name) = &self.metadata.rust_crate_name {
                    if module == "crate" {
                        aliases.push(crate_name.to_string());
                    } else if let Some(stripped) = module.strip_prefix("crate::") {
                        aliases.push(format!("{}::{}", crate_name, stripped));
                    }
                }
            }
            "go" => {
                if let Some(prefix) = &self.metadata.go_module_path {
                    let base = module.trim_start_matches("./").trim_start_matches('/');
                    if base.is_empty() {
                        aliases.push(prefix.to_string());
                    } else {
                        aliases.push(format!("{}/{}", prefix.trim_end_matches('/'), base));
                    }
                }
            }
            "php" => {
                if module.contains('\\') {
                    aliases.push(module.replace('\\', "/"));
                }
                if module.contains('/') {
                    aliases.push(module.replace('/', "\\"));
                }
                if !module.starts_with('\\') {
                    aliases.push(format!("\\{}", module));
                }
                if !self.metadata.php_psr4.is_empty() {
                    for (prefix, dir) in &self.metadata.php_psr4 {
                        if let Ok(rel) = path.strip_prefix(dir) {
                            let rel_str = normalize_relative_str(rel);
                            let rel_str = strip_extension_any(&rel_str, &[".php"]);
                            if rel_str.is_empty() {
                                continue;
                            }
                            let ns_suffix = rel_str.replace('/', "\\");
                            let mut ns_prefix = prefix.clone();
                            if !ns_prefix.ends_with('\\') {
                                ns_prefix.push('\\');
                            }
                            aliases.push(format!("{}{}", ns_prefix, ns_suffix));
                        }
                    }
                }
            }
            "ruby" => {
                if let Some(camel) = ruby_module_alias_from_path(path, &self.project_root) {
                    aliases.push(camel);
                }
            }
            "lua" | "luau" => {
                if module.contains('.') {
                    aliases.push(module.replace('.', "/"));
                }
                if module.contains('/') {
                    aliases.push(module.replace('/', "."));
                }
            }
            "c" | "cpp" => {
                if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
                    aliases.push(file_name.to_string());
                }
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    aliases.push(stem.to_string());
                }
                if let Ok(rel) = path.strip_prefix(&self.project_root) {
                    let rel_str = normalize_relative_str(rel);
                    aliases.push(rel_str.clone());
                    let rel_no_ext = strip_extension_any(
                        &rel_str,
                        &[".c", ".h", ".cpp", ".cc", ".cxx", ".hpp", ".hh", ".hxx"],
                    );
                    if rel_no_ext != rel_str {
                        aliases.push(rel_no_ext.to_string());
                    }
                }
            }
            "swift" => {
                if let Some(root) = swift_module_root(path, &self.project_root) {
                    aliases.push(root);
                }
            }
            "elixir" => {
                if !module.starts_with("Elixir.") {
                    aliases.push(format!("Elixir.{}", module));
                }
            }
            _ => {}
        }

        aliases
    }

    fn declared_package_alias(&self, path: &Path) -> Option<String> {
        match self.language.as_str() {
            "java" | "kotlin" | "scala" => parse_java_like_package(path),
            "csharp" | "c#" => parse_csharp_namespace(path),
            _ => None,
        }
    }

    /// Compute Python module name from file path.
    ///
    /// Examples:
    /// - `src/myapp/__init__.py` -> `myapp`
    /// - `src/myapp/utils.py` -> `myapp.utils`
    /// - `src/myapp/subpkg/__init__.py` -> `myapp.subpkg`
    fn compute_python_module_name(&self, path: &Path) -> String {
        let relative = if let Some(src_root) = &self.metadata.python_src_root {
            if let Ok(r) = path.strip_prefix(src_root) {
                r
            } else {
                match path.strip_prefix(&self.project_root) {
                    Ok(r) => r,
                    Err(_) => return String::new(),
                }
            }
        } else {
            match path.strip_prefix(&self.project_root) {
                Ok(r) => r,
                Err(_) => return String::new(),
            }
        };

        let file_name = relative.file_name().and_then(|n| n.to_str()).unwrap_or("");

        // Handle __init__.py -> package name (parent directory)
        if file_name == "__init__.py" {
            let parent = relative.parent().unwrap_or(Path::new(""));
            let parts: Vec<&str> = parent
                .iter()
                .filter_map(|s| s.to_str())
                .filter(|s| !s.is_empty())
                .collect();
            return parts.join(".");
        }

        // Regular module: strip extension
        let stem = relative.with_extension("");
        let parts: Vec<&str> = stem
            .iter()
            .filter_map(|s| s.to_str())
            .filter(|s| !s.is_empty())
            .collect();

        parts.join(".")
    }

    /// Compute TypeScript/JavaScript module name from file path.
    ///
    /// Examples:
    /// - `src/utils/index.ts` -> `./utils`
    /// - `src/helpers.ts` -> `./helpers`
    fn compute_typescript_module_name(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };

        let file_name = relative.file_name().and_then(|n| n.to_str()).unwrap_or("");

        // Handle index.ts/index.tsx -> parent directory
        if file_name == "index.ts" || file_name == "index.tsx" || file_name == "index.js" {
            let parent = relative.parent().unwrap_or(Path::new(""));
            return format!("./{}", parent.display());
        }

        // Regular module: strip extension
        let stem = relative.with_extension("");
        format!("./{}", stem.display())
    }

    /// Compute Rust module name from file path.
    ///
    /// Examples:
    /// - `src/lib.rs` -> `crate`
    /// - `src/utils/mod.rs` -> `crate::utils`
    /// - `src/utils/helpers.rs` -> `crate::utils::helpers`
    fn compute_rust_module_name(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };

        let file_name = relative.file_name().and_then(|n| n.to_str()).unwrap_or("");

        // Handle lib.rs/main.rs -> crate root
        if file_name == "lib.rs" || file_name == "main.rs" {
            return "crate".to_string();
        }

        // Handle mod.rs -> parent module
        if file_name == "mod.rs" {
            let parent = relative.parent().unwrap_or(Path::new(""));
            // Skip 'src' prefix if present
            let parts: Vec<&str> = parent
                .iter()
                .filter_map(|s| s.to_str())
                .filter(|s| *s != "src" && !s.is_empty())
                .collect();

            if parts.is_empty() {
                return "crate".to_string();
            }
            return format!("crate::{}", parts.join("::"));
        }

        // Regular module
        let stem = relative.with_extension("");
        let parts: Vec<&str> = stem
            .iter()
            .filter_map(|s| s.to_str())
            .filter(|s| *s != "src" && !s.is_empty())
            .collect();

        if parts.is_empty() {
            return "crate".to_string();
        }
        format!("crate::{}", parts.join("::"))
    }

    /// Compute Go module name from file path.
    ///
    /// In Go, the directory path is the package path.
    fn compute_go_module_name(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };

        // Go uses directory as package
        relative
            .parent()
            .map(|p| p.to_string_lossy().replace('\\', "/"))
            .unwrap_or_default()
    }

    /// Compute Java module name from file path (dot-separated package path).
    fn compute_java_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &JAVA_PREFIXES, &[".java"])
    }

    /// Compute Kotlin module name from file path (dot-separated package path).
    fn compute_kotlin_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &KOTLIN_PREFIXES, &[".kt", ".kts"])
    }

    /// Compute Scala module name from file path (dot-separated package path).
    fn compute_scala_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &SCALA_PREFIXES, &[".scala"])
    }

    /// Compute C# namespace module name from file path (dot-separated).
    fn compute_csharp_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &CSHARP_PREFIXES, &[".cs"])
    }

    /// Compute PHP module name from file path (backslash-separated namespace).
    fn compute_php_module_name(&self, path: &Path) -> String {
        compute_separator_module_name(path, &self.project_root, &PHP_PREFIXES, &[".php"], '\\')
    }

    /// Compute Ruby module name from file path (slash-separated require path).
    fn compute_ruby_module_name(&self, path: &Path) -> String {
        compute_separator_module_name(path, &self.project_root, &RUBY_PREFIXES, &[".rb"], '/')
    }

    /// Compute Lua/Luau module name from file path (dot-separated).
    fn compute_lua_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &LUA_PREFIXES, &[".lua", ".luau"])
    }

    /// Compute Elixir module name from file path (CamelCase segments).
    fn compute_elixir_module_name(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };
        let mut rel_str = normalize_relative_str(relative);

        let mut module_parts: Vec<String> = Vec::new();

        // Umbrella apps: apps/<app>/lib/<rest>
        if let Some(rest) = rel_str.strip_prefix("apps/") {
            let mut parts = rest.splitn(2, '/');
            if let Some(app) = parts.next() {
                if let Some(after_app) = parts.next() {
                    if let Some(after_lib) = after_app.strip_prefix("lib/") {
                        module_parts.push(snake_to_camel(app));
                        rel_str = after_lib.to_string();
                    }
                }
            }
        }

        // Standard: lib/<rest>
        if module_parts.is_empty() {
            if let Some(after_lib) = rel_str.strip_prefix("lib/") {
                rel_str = after_lib.to_string();
            }
        }

        let rel_str = strip_extension_any(&rel_str, &[".ex", ".exs"]);
        for segment in rel_str.split('/') {
            if segment.is_empty() {
                continue;
            }
            module_parts.push(snake_to_camel(segment));
        }

        module_parts.join(".")
    }

    /// Compute Swift module name from file path (SwiftPM-aware).
    fn compute_swift_module_name(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };
        let rel_str = normalize_relative_str(relative);

        if let Some(rest) = rel_str.strip_prefix("Sources/") {
            return swift_module_from_sources(rest);
        }
        if let Some(rest) = rel_str.strip_prefix("Tests/") {
            return swift_module_from_sources(rest);
        }

        // Fallback to dot path
        compute_dot_module_name(path, &self.project_root, &SWIFT_PREFIXES, &[".swift"])
    }

    /// Compute C module name from file path (relative path with extension).
    fn compute_c_module_name(&self, path: &Path) -> String {
        compute_path_module_name(path, &self.project_root)
    }

    /// Compute C++ module name from file path (relative path with extension).
    fn compute_cpp_module_name(&self, path: &Path) -> String {
        compute_path_module_name(path, &self.project_root)
    }

    /// Compute OCaml module name from file path (dot-separated).
    fn compute_ocaml_module_name(&self, path: &Path) -> String {
        compute_dot_module_name(path, &self.project_root, &OCAML_PREFIXES, &[".ml", ".mli"])
    }

    /// Convert a file path to module name (for reverse lookup building).
    fn path_to_module(&self, path: &Path) -> String {
        let relative = match path.strip_prefix(&self.project_root) {
            Ok(r) => r,
            Err(_) => return String::new(),
        };

        let parts: Vec<&str> = relative
            .iter()
            .filter_map(|s| s.to_str())
            .filter(|s| !s.is_empty())
            .collect();

        parts.join(".")
    }

    /// Look up file path for a module name.
    ///
    /// # Arguments
    ///
    /// * `module` - Dotted module path (e.g., "myapp.utils")
    ///
    /// # Returns
    ///
    /// The file path if found, or `None` if the module is not in the index.
    ///
    /// # Complexity
    ///
    /// O(1) hash lookup.
    pub fn lookup(&self, module: &str) -> Option<&Path> {
        let normalized = normalize_module_key(module);
        self.module_to_file.get(&normalized).map(|p| p.as_path())
    }

    /// Reverse lookup: file path to module name.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to source file
    ///
    /// # Returns
    ///
    /// The module name if found, or `None` if the file is not in the index.
    ///
    /// # Complexity
    ///
    /// O(1) hash lookup. Symlinks are resolved before lookup.
    pub fn reverse_lookup(&self, path: &Path) -> Option<&str> {
        // Resolve symlinks before lookup
        let canonical = match resolve_path(path, &self.project_root) {
            Ok(p) => p,
            Err(_) => path.to_path_buf(),
        };

        self.file_to_module.get(&canonical).map(|s| s.as_str())
    }

    /// Check if module is part of this project (vs external/stdlib).
    ///
    /// # Arguments
    ///
    /// * `module` - Dotted module path
    ///
    /// # Returns
    ///
    /// `true` if the module is indexed in this project, `false` otherwise.
    pub fn is_project_module(&self, module: &str) -> bool {
        let normalized = normalize_module_key(module);

        // Direct lookup
        if self.module_to_file.contains_key(&normalized) {
            return true;
        }

        // Check if parent is a namespace package
        if let Some(dot_pos) = normalized.rfind('.') {
            let parent = &normalized[..dot_pos];
            if self.namespace_packages.contains(parent) {
                return true;
            }
        }

        // Check if this is a namespace package itself
        self.namespace_packages.contains(&normalized)
    }

    /// Check if a module is a namespace package.
    ///
    /// Namespace packages (PEP 420) are directories containing Python files
    /// but no `__init__.py`.
    pub fn is_namespace_package(&self, module: &str) -> bool {
        let normalized = normalize_module_key(module);
        self.namespace_packages.contains(&normalized)
    }

    /// Get all module names in the index.
    pub fn modules(&self) -> impl Iterator<Item = &str> {
        self.module_to_file.keys().map(|s| s.as_str())
    }

    /// Get the number of indexed modules.
    pub fn len(&self) -> usize {
        self.module_to_file.len()
    }

    /// Check if the index is empty.
    pub fn is_empty(&self) -> bool {
        self.module_to_file.is_empty()
    }

    /// Get project root path.
    pub fn project_root(&self) -> &Path {
        &self.project_root
    }

    /// Get the language this index was built for.
    pub fn language(&self) -> &str {
        &self.language
    }

    /// Iterate over all (module, path) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Path)> {
        self.module_to_file
            .iter()
            .map(|(m, p)| (m.as_str(), p.as_path()))
    }
}

/// Resolve a path to its canonical form, ensuring it stays within the project root.
///
/// # Security
///
/// This function ensures the resolved path is within the project root,
/// preventing directory traversal attacks via symlinks.
fn resolve_path(path: &Path, root: &Path) -> Result<PathBuf, ModuleIndexError> {
    // Use dunce to get canonical path without UNC prefix on Windows
    let canonical = dunce::canonicalize(path).map_err(ModuleIndexError::Io)?;

    // Security check: ensure path is under root
    // Skip this check if we're resolving the root itself
    if path != root {
        let canonical_root = dunce::canonicalize(root).map_err(ModuleIndexError::Io)?;
        if !canonical.starts_with(&canonical_root) {
            return Err(ModuleIndexError::PathOutsideRoot(canonical));
        }
    }

    Ok(canonical)
}

/// Normalize module key for case sensitivity.
///
/// On macOS and Windows, module lookups should be case-insensitive
/// to match the filesystem behavior.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn normalize_module_key(key: &str) -> String {
    key.to_lowercase()
}

/// Normalize module key for case sensitivity.
///
/// On Linux and other Unix systems, module lookups are case-sensitive.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn normalize_module_key(key: &str) -> String {
    key.to_string()
}

impl ModuleIndexMetadata {
    fn detect(root: &Path, language: &str) -> Self {
        let lang = language.to_lowercase();
        let mut meta = ModuleIndexMetadata::default();

        if lang == "python" {
            meta.python_src_root = detect_python_src_root(root);
        }

        if lang == "typescript" || lang == "javascript" {
            meta.ts_base_url = detect_ts_base_url(root);
            meta.ts_paths = detect_ts_paths(root);
            meta.js_package_name = detect_js_package_name(root);
        }

        if lang == "go" {
            meta.go_module_path = detect_go_module_path(root);
        }

        if lang == "rust" {
            meta.rust_crate_name = detect_rust_crate_name(root);
        }

        if lang == "php" {
            meta.php_psr4 = detect_php_psr4(root);
        }

        meta
    }
}

// =============================================================================
// Build metadata detection helpers
// =============================================================================

fn detect_python_src_root(root: &Path) -> Option<PathBuf> {
    let candidate = root.join("src");
    if !candidate.is_dir() {
        return None;
    }
    // Look for at least one .py file under src/ to confirm layout.
    let walker = WalkBuilder::new(&candidate)
        .hidden(true)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .max_depth(Some(6))
        .build();
    for entry in walker.flatten() {
        let path = entry.path();
        if path.is_file() {
            if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                if ext.eq_ignore_ascii_case("py") {
                    return Some(candidate);
                }
            }
        }
    }
    None
}

fn detect_go_module_path(root: &Path) -> Option<String> {
    let path = root.join("go.mod");
    let content = std::fs::read_to_string(path).ok()?;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("module ") {
            let module = trimmed.trim_start_matches("module ").trim();
            if !module.is_empty() {
                return Some(module.to_string());
            }
        }
    }
    None
}

fn detect_rust_crate_name(root: &Path) -> Option<String> {
    let path = root.join("Cargo.toml");
    let content = std::fs::read_to_string(path).ok()?;
    let mut in_package = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            in_package = trimmed == "[package]";
            continue;
        }
        if !in_package {
            continue;
        }
        if trimmed.starts_with("name") {
            if let Some((_, value)) = trimmed.split_once('=') {
                let name = value.trim().trim_matches('"').trim_matches('\'');
                if !name.is_empty() {
                    return Some(name.to_string());
                }
            }
        }
    }
    None
}

fn detect_js_package_name(root: &Path) -> Option<String> {
    let json = read_json_file(root.join("package.json"))?;
    json.get("name")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

fn detect_ts_base_url(root: &Path) -> Option<PathBuf> {
    let configs = load_tsconfig_chain(root.join("tsconfig.json"));
    for config in configs.iter().rev() {
        let compiler = config.json.get("compilerOptions")?;
        let base_url = compiler.get("baseUrl")?.as_str()?;
        let base_url = base_url.trim();
        if base_url.is_empty() {
            continue;
        }
        let base_dir = config.path.parent().unwrap_or(root);
        return Some(base_dir.join(base_url));
    }
    None
}

fn detect_ts_paths(root: &Path) -> Vec<TsPathMapping> {
    let configs = load_tsconfig_chain(root.join("tsconfig.json"));
    let mut merged: HashMap<String, Vec<String>> = HashMap::new();
    for config in configs {
        if let Some(compiler) = config.json.get("compilerOptions") {
            if let Some(paths) = compiler.get("paths") {
                extract_ts_paths(paths, &mut merged);
            }
        }
    }
    let mut mappings: Vec<TsPathMapping> = merged
        .into_iter()
        .map(|(alias, targets)| TsPathMapping {
            alias_pattern: alias,
            target_patterns: targets,
        })
        .collect();
    mappings.sort_by(|a, b| a.alias_pattern.cmp(&b.alias_pattern));
    mappings
}

#[derive(Debug, Clone)]
struct TsConfig {
    path: PathBuf,
    json: JsonValue,
}

fn load_tsconfig_chain(path: PathBuf) -> Vec<TsConfig> {
    let mut visited = HashSet::new();
    load_tsconfig_chain_inner(path, 0, &mut visited)
}

fn load_tsconfig_chain_inner(
    path: PathBuf,
    depth: usize,
    visited: &mut HashSet<PathBuf>,
) -> Vec<TsConfig> {
    if depth > 5 {
        return Vec::new();
    }
    let canonical = dunce::canonicalize(&path).unwrap_or(path);
    if !visited.insert(canonical.clone()) {
        return Vec::new();
    }
    let json = match read_json_with_comments(canonical.clone()) {
        Some(j) => j,
        None => return Vec::new(),
    };

    let mut out = Vec::new();
    if let Some(extends) = json.get("extends").and_then(|v| v.as_str()) {
        if let Some(ext_path) = resolve_tsconfig_extends(&canonical, extends) {
            out.extend(load_tsconfig_chain_inner(ext_path, depth + 1, visited));
        }
    }
    out.push(TsConfig {
        path: canonical,
        json,
    });
    out
}

fn resolve_tsconfig_extends(base: &Path, extends: &str) -> Option<PathBuf> {
    let ext = extends.trim();
    if ext.is_empty() {
        return None;
    }
    if !(ext.starts_with('.') || ext.starts_with('/')) {
        // Package-based extends (e.g., @org/tsconfig) are out of scope.
        return None;
    }
    let base_dir = base.parent().unwrap_or(Path::new("."));
    let mut path = if ext.starts_with('/') {
        PathBuf::from(ext)
    } else {
        base_dir.join(ext)
    };
    if path.extension().is_none() {
        path.set_extension("json");
    }
    Some(path)
}

fn extract_ts_paths(value: &JsonValue, out: &mut HashMap<String, Vec<String>>) {
    let map = match value.as_object() {
        Some(m) => m,
        None => return,
    };
    for (alias, targets) in map {
        let mut patterns = Vec::new();
        if let Some(path) = targets.as_str() {
            patterns.push(path.to_string());
        } else if let Some(list) = targets.as_array() {
            for item in list {
                if let Some(path) = item.as_str() {
                    patterns.push(path.to_string());
                }
            }
        }
        if !patterns.is_empty() {
            out.insert(alias.to_string(), patterns);
        }
    }
}

fn detect_php_psr4(root: &Path) -> Vec<(String, PathBuf)> {
    let mut mappings = Vec::new();
    let json = match read_json_file(root.join("composer.json")) {
        Some(j) => j,
        None => return mappings,
    };
    for key in ["autoload", "autoload-dev"] {
        if let Some(section) = json.get(key) {
            if let Some(psr4) = section.get("psr-4") {
                extract_psr4_mappings(root, psr4, &mut mappings);
            }
        }
    }
    mappings
}

fn extract_psr4_mappings(root: &Path, value: &JsonValue, out: &mut Vec<(String, PathBuf)>) {
    let map = match value.as_object() {
        Some(m) => m,
        None => return,
    };
    for (prefix, paths) in map {
        if let Some(path) = paths.as_str() {
            out.push((prefix.to_string(), root.join(path)));
        } else if let Some(list) = paths.as_array() {
            for item in list {
                if let Some(path) = item.as_str() {
                    out.push((prefix.to_string(), root.join(path)));
                }
            }
        }
    }
}

fn read_json_file(path: PathBuf) -> Option<JsonValue> {
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

fn read_json_with_comments(path: PathBuf) -> Option<JsonValue> {
    let content = std::fs::read_to_string(path).ok()?;
    let stripped = strip_json_comments(&content);
    serde_json::from_str(&stripped).ok()
}

fn strip_json_comments(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut in_string = false;
    let mut chars = input.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '"' {
            out.push(ch);
            in_string = !in_string;
            continue;
        }
        if !in_string && ch == '/' {
            if let Some('/') = chars.peek().copied() {
                // line comment
                chars.next();
                for c in chars.by_ref() {
                    if c == '\n' {
                        out.push('\n');
                        break;
                    }
                }
                continue;
            }
            if let Some('*') = chars.peek().copied() {
                // block comment
                chars.next();
                while let Some(c) = chars.next() {
                    if c == '*' {
                        if let Some('/') = chars.peek().copied() {
                            chars.next();
                            break;
                        }
                    }
                }
                continue;
            }
        }
        out.push(ch);
    }
    out
}

// =============================================================================
// Language-specific module naming helpers
// =============================================================================

const JAVA_PREFIXES: [&str; 5] = ["src/main/java/", "src/test/java/", "src/", "lib/", "app/"];
const KOTLIN_PREFIXES: [&str; 5] = [
    "src/main/kotlin/",
    "src/test/kotlin/",
    "src/",
    "lib/",
    "app/",
];
const SCALA_PREFIXES: [&str; 5] = ["src/main/scala/", "src/test/scala/", "src/", "lib/", "app/"];
const CSHARP_PREFIXES: [&str; 3] = ["src/", "lib/", "app/"];
const PHP_PREFIXES: [&str; 5] = ["src/", "lib/", "app/", "public/", "includes/"];
const RUBY_PREFIXES: [&str; 3] = ["lib/", "src/", "app/"];
const LUA_PREFIXES: [&str; 3] = ["src/", "lib/", "scripts/"];
const SWIFT_PREFIXES: [&str; 2] = ["src/", "lib/"];
const OCAML_PREFIXES: [&str; 3] = ["src/", "lib/", "app/"];
const TS_EXTENSIONS: [&str; 6] = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];

fn normalize_relative_str(path: &Path) -> String {
    let mut rel = path.to_string_lossy().replace('\\', "/");
    if let Some(stripped) = rel.strip_prefix("./") {
        rel = stripped.to_string();
    }
    rel.trim_start_matches('/').to_string()
}

fn is_ts_index_file(path: &Path) -> bool {
    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    matches!(
        file_name,
        "index.ts" | "index.tsx" | "index.js" | "index.jsx" | "index.mjs" | "index.cjs"
    )
}

fn ts_path_aliases_for_file(
    path: &Path,
    root: &Path,
    base_url: Option<&PathBuf>,
    mappings: &[TsPathMapping],
) -> Vec<String> {
    if mappings.is_empty() {
        return Vec::new();
    }
    let relative = match path.strip_prefix(root) {
        Ok(r) => r,
        Err(_) => return Vec::new(),
    };
    let rel_str = normalize_relative_str(relative);
    let rel_no_ext = strip_extension_any(&rel_str, &TS_EXTENSIONS);
    let mut candidates = Vec::new();
    if !rel_no_ext.is_empty() {
        candidates.push(rel_no_ext.to_string());
    }
    if is_ts_index_file(path) {
        if let Some(parent) = Path::new(rel_no_ext).parent() {
            let parent_str = parent.to_string_lossy().to_string();
            if !parent_str.is_empty() {
                candidates.push(parent_str);
            }
        }
    }

    let base_prefix = base_url
        .and_then(|p| p.strip_prefix(root).ok())
        .map(normalize_relative_str)
        .filter(|s| !s.is_empty());

    let mut aliases = Vec::new();
    for candidate in candidates {
        for mapping in mappings {
            for target_pattern in &mapping.target_patterns {
                if let Some(alias) = ts_alias_for_pattern(
                    &candidate,
                    target_pattern,
                    base_prefix.as_deref(),
                    &mapping.alias_pattern,
                ) {
                    aliases.push(alias);
                }
            }
        }
    }
    aliases
}

fn ts_alias_for_pattern(
    candidate: &str,
    target_pattern: &str,
    base_prefix: Option<&str>,
    alias_pattern: &str,
) -> Option<String> {
    let mut pattern = target_pattern.trim().replace('\\', "/");
    if let Some(stripped) = pattern.strip_prefix("./") {
        pattern = stripped.to_string();
    }
    if let Some(base) = base_prefix {
        if !pattern.starts_with("../") && !pattern.starts_with('/') {
            let base = base.trim_end_matches('/');
            if !base.is_empty() {
                pattern = format!("{}/{}", base, pattern);
            }
        }
    }
    let pattern = strip_extension_any(&pattern, &TS_EXTENSIONS);

    let capture = match_ts_path_pattern(candidate, pattern)?;
    let mut alias = alias_pattern.replace('*', &capture);
    if alias.ends_with('/') {
        alias = alias.trim_end_matches('/').to_string();
    }
    if alias.is_empty() {
        None
    } else {
        Some(alias)
    }
}

fn match_ts_path_pattern(candidate: &str, pattern: &str) -> Option<String> {
    if let Some(star_pos) = pattern.find('*') {
        let (prefix, rest) = pattern.split_at(star_pos);
        let suffix = &rest[1..];
        if candidate.starts_with(prefix) && candidate.ends_with(suffix) {
            let mid_end = candidate.len().saturating_sub(suffix.len());
            let mid = &candidate[prefix.len()..mid_end];
            return Some(mid.to_string());
        }
        return None;
    }
    if candidate == pattern {
        return Some(String::new());
    }
    None
}

fn strip_known_prefixes<'a>(path: &'a str, prefixes: &[&str]) -> &'a str {
    let mut best_end: Option<usize> = None;
    let mut best_prefix_len: usize = 0;
    for prefix in prefixes {
        if let Some(pos) = path.find(prefix) {
            // Only match at start of path or after a '/' boundary
            if (pos == 0 || path.as_bytes()[pos - 1] == b'/')
                && prefix.len() > best_prefix_len {
                    best_prefix_len = prefix.len();
                    best_end = Some(pos + prefix.len());
        }
    }
}
if let Some(end) = best_end {
    &path[end..]
} else {
    path
}
}

fn strip_extension_any<'a>(path: &'a str, extensions: &[&str]) -> &'a str {
    for ext in extensions {
        if let Some(stripped) = path.strip_suffix(ext) {
            return stripped;
        }
    }
    path
}

fn compute_dot_module_name(
    path: &Path,
    root: &Path,
    prefixes: &[&str],
    extensions: &[&str],
) -> String {
    let relative = match path.strip_prefix(root) {
        Ok(r) => r,
        Err(_) => return String::new(),
    };
    let rel_str = normalize_relative_str(relative);
    let rel_str = strip_known_prefixes(&rel_str, prefixes);
    let rel_str = strip_extension_any(rel_str, extensions);
    if rel_str.is_empty() {
        return String::new();
    }
    rel_str
        .split('/')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join(".")
}

fn compute_separator_module_name(
    path: &Path,
    root: &Path,
    prefixes: &[&str],
    extensions: &[&str],
    separator: char,
) -> String {
    let relative = match path.strip_prefix(root) {
        Ok(r) => r,
        Err(_) => return String::new(),
    };
    let rel_str = normalize_relative_str(relative);
    let rel_str = strip_known_prefixes(&rel_str, prefixes);
    let rel_str = strip_extension_any(rel_str, extensions);
    if rel_str.is_empty() {
        return String::new();
    }
    if separator == '/' {
        rel_str.to_string()
    } else {
        rel_str.replace('/', &separator.to_string())
    }
}

fn compute_path_module_name(path: &Path, root: &Path) -> String {
    let relative = match path.strip_prefix(root) {
        Ok(r) => r,
        Err(_) => return String::new(),
    };
    normalize_relative_str(relative)
}

fn snake_to_camel(segment: &str) -> String {
    segment
        .split(['_', '-'])
        .filter(|s| !s.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => {
                    let mut out = String::new();
                    out.push(first.to_ascii_uppercase());
                    out.push_str(chars.as_str());
                    out
                }
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join("")
}

fn swift_module_from_sources(rest: &str) -> String {
    let rest = strip_extension_any(rest, &[".swift"]);
    let mut parts = rest.split('/').filter(|s| !s.is_empty());
    let module = parts.next().unwrap_or("");
    if module.is_empty() {
        return String::new();
    }
    let remainder: Vec<&str> = parts.collect();
    if remainder.is_empty() {
        module.to_string()
    } else {
        format!("{}.{}", module, remainder.join("."))
    }
}

fn swift_module_root(path: &Path, root: &Path) -> Option<String> {
    let relative = path.strip_prefix(root).ok()?;
    let rel_str = normalize_relative_str(relative);
    if let Some(rest) = rel_str.strip_prefix("Sources/") {
        return rest.split('/').next().map(|s| s.to_string());
    }
    if let Some(rest) = rel_str.strip_prefix("Tests/") {
        return rest.split('/').next().map(|s| s.to_string());
    }
    None
}

fn ruby_module_alias_from_path(path: &Path, root: &Path) -> Option<String> {
    let relative = path.strip_prefix(root).ok()?;
    let rel_str = normalize_relative_str(relative);
    let rel_str = strip_known_prefixes(&rel_str, &RUBY_PREFIXES);
    let rel_str = strip_extension_any(rel_str, &[".rb"]);
    if rel_str.is_empty() {
        return None;
    }
    let parts: Vec<String> = rel_str
        .split('/')
        .filter(|s| !s.is_empty())
        .map(snake_to_camel)
        .collect();
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("::"))
    }
}

fn parse_java_like_package(path: &Path) -> Option<String> {
    let source = fs::read_to_string(path).ok()?;
    lazy_static! {
        static ref RE_PACKAGE: Regex =
            Regex::new(r"(?m)^\\s*package\\s+([A-Za-z_][\\w\\.]*)\\s*;?").unwrap();
    }
    RE_PACKAGE.captures(&source).map(|caps| caps[1].to_string())
}

fn parse_csharp_namespace(path: &Path) -> Option<String> {
    let source = fs::read_to_string(path).ok()?;
    lazy_static! {
        static ref RE_NAMESPACE: Regex =
            Regex::new(r"(?m)^\\s*namespace\\s+([A-Za-z_][\\w\\.]*)").unwrap();
    }
    RE_NAMESPACE
        .captures(&source)
        .map(|caps| caps[1].to_string())
}

fn simple_module_name(module: &str) -> &str {
    module
        .rsplit(['.', '/', '\\'])
        .next()
        .unwrap_or(module)
}

/// Check if a directory should be skipped during traversal.
fn should_skip_directory(name: &str) -> bool {
    matches!(
        name,
        "__pycache__"
            | ".git"
            | ".svn"
            | ".hg"
            | "node_modules"
            | "venv"
            | ".venv"
            | "env"
            | ".env"
            | ".tox"
            | ".pytest_cache"
            | ".mypy_cache"
            | ".ruff_cache"
            | "__pypackages__"
            | "target"
            | "build"
            | "dist"
            | ".idea"
            | ".vscode"
    )
}

/// Get file extensions for a language.
fn get_language_extensions(language: &str) -> Vec<&'static str> {
    match language.to_lowercase().as_str() {
        "python" => vec!["py"],
        "typescript" => vec!["ts", "tsx"],
        "javascript" => vec!["js", "jsx", "mjs", "cjs"],
        "rust" => vec!["rs"],
        "go" => vec!["go"],
        "java" => vec!["java"],
        "c" => vec!["c", "h"],
        "cpp" | "c++" => vec!["cpp", "cc", "cxx", "hpp", "hh", "hxx", "h"],
        "ruby" => vec!["rb"],
        "php" => vec!["php"],
        "kotlin" => vec!["kt", "kts"],
        "scala" => vec!["scala"],
        "swift" => vec!["swift"],
        "csharp" | "c#" => vec!["cs"],
        "lua" => vec!["lua"],
        "luau" => vec!["lua", "luau"],
        "elixir" => vec!["ex", "exs"],
        "ocaml" => vec!["ml", "mli"],
        _ => vec!["py"], // Default to Python
    }
}

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

    // =============================================================================
    // build() tests
    // =============================================================================

    #[test]
    fn test_build_simple_package() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/core.py"), "def foo(): pass").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.lookup("pkg").is_some());
        assert!(index.lookup("pkg.core").is_some());
    }

    #[test]
    fn test_build_indexes_init_as_package() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        let pkg_path = index.lookup("pkg");
        assert!(pkg_path.is_some());
        assert!(pkg_path.unwrap().ends_with("__init__.py"));
    }

    #[test]
    fn test_build_package_wins_over_module() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "# package").unwrap();
        fs::write(dir.path().join("pkg.py"), "# module").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        let pkg_path = index.lookup("pkg");
        assert!(pkg_path.is_some());
        // Package wins - should point to __init__.py
        assert!(pkg_path.unwrap().ends_with("__init__.py"));
    }

    #[test]
    fn test_build_namespace_package() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/module.py"), "").unwrap();
        // No __init__.py - namespace package

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.is_namespace_package("pkg"));
        assert!(index.lookup("pkg.module").is_some());
    }

    #[test]
    fn test_build_skips_pycache() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("__pycache__")).unwrap();
        fs::write(dir.path().join("__pycache__/module.cpython-311.pyc"), "").unwrap();
        fs::write(dir.path().join("module.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.lookup("module").is_some());
        // No __pycache__ entries
        for (module, _) in index.iter() {
            assert!(!module.contains("__pycache__"));
        }
    }

    #[test]
    fn test_build_deeply_nested_package() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("a/b/c/d/e")).unwrap();
        for pkg in ["a", "a/b", "a/b/c", "a/b/c/d", "a/b/c/d/e"] {
            fs::write(dir.path().join(format!("{}/__init__.py", pkg)), "").unwrap();
        }
        fs::write(dir.path().join("a/b/c/d/e/f.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.lookup("a.b.c.d.e.f").is_some());
        assert!(index.lookup("a.b.c").is_some());
    }

    // =============================================================================
    // lookup() tests
    // =============================================================================

    #[test]
    fn test_lookup_returns_file_path() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/core.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        let path = index.lookup("pkg.core");
        assert!(path.is_some());
        assert!(path.unwrap().ends_with("core.py"));
    }

    #[test]
    fn test_lookup_returns_none_for_nonexistent() {
        let dir = tempdir().unwrap();
        let index = ModuleIndex::build(dir.path(), "python").unwrap();
        assert!(index.lookup("nonexistent.module").is_none());
    }

    // =============================================================================
    // reverse_lookup() tests
    // =============================================================================

    #[test]
    fn test_reverse_lookup_returns_module_path() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/core.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        let module = index.reverse_lookup(&dir.path().join("pkg/core.py"));
        assert_eq!(module, Some("pkg.core"));
    }

    #[test]
    fn test_reverse_lookup_returns_none_for_unknown() {
        let dir = tempdir().unwrap();
        let index = ModuleIndex::build(dir.path(), "python").unwrap();
        assert!(index
            .reverse_lookup(Path::new("/unknown/path.py"))
            .is_none());
    }

    // =============================================================================
    // is_project_module() tests
    // =============================================================================

    #[test]
    fn test_is_project_module_returns_true_for_indexed() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/core.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.is_project_module("pkg"));
        assert!(index.is_project_module("pkg.core"));
    }

    #[test]
    fn test_is_project_module_returns_false_for_stdlib() {
        let dir = tempdir().unwrap();
        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(!index.is_project_module("os"));
        assert!(!index.is_project_module("sys"));
        assert!(!index.is_project_module("json.decoder"));
    }

    // =============================================================================
    // Edge cases
    // =============================================================================

    #[test]
    fn test_empty_directory() {
        let dir = tempdir().unwrap();
        let index = ModuleIndex::build(dir.path(), "python").unwrap();
        assert_eq!(index.len(), 0);
    }

    #[test]
    fn test_single_file_no_package() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("script.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();
        assert!(index.lookup("script").is_some());
    }

    #[test]
    fn test_mixed_extensions() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("module.py"), "").unwrap();
        fs::write(dir.path().join("config.json"), "").unwrap();
        fs::write(dir.path().join("README.md"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.lookup("module").is_some());
        assert_eq!(index.len(), 1); // Only .py file
    }

    #[test]
    fn test_dunder_names() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/__main__.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        assert!(index.lookup("pkg.__main__").is_some());
    }

    #[test]
    fn test_private_modules() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg/_internal")).unwrap();
        fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
        fs::write(dir.path().join("pkg/_private.py"), "").unwrap();
        fs::write(dir.path().join("pkg/_internal/__init__.py"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "python").unwrap();

        // Private modules should still be indexed
        assert!(index.lookup("pkg._private").is_some());
        assert!(index.lookup("pkg._internal").is_some());
    }

    // =============================================================================
    // TypeScript tests
    // =============================================================================

    #[test]
    fn test_typescript_index_file() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("utils")).unwrap();
        fs::write(dir.path().join("utils/index.ts"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "typescript").unwrap();

        assert!(index.lookup("./utils").is_some());
    }

    // =============================================================================
    // Rust tests
    // =============================================================================

    #[test]
    fn test_rust_lib_rs() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src/lib.rs"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "rust").unwrap();

        assert!(index.lookup("crate").is_some());
    }

    #[test]
    fn test_rust_mod_rs() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("src/utils")).unwrap();
        fs::write(dir.path().join("src/lib.rs"), "").unwrap();
        fs::write(dir.path().join("src/utils/mod.rs"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "rust").unwrap();

        assert!(index.lookup("crate::utils").is_some());
    }

    // =============================================================================
    // Go tests
    // =============================================================================

    #[test]
    fn test_go_package() {
        let dir = tempdir().unwrap();
        fs::create_dir_all(dir.path().join("pkg/utils")).unwrap();
        fs::write(dir.path().join("pkg/utils/helpers.go"), "").unwrap();

        let index = ModuleIndex::build(dir.path(), "go").unwrap();

        assert!(index.lookup("pkg/utils").is_some());
    }
}