codenexus 0.3.4

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! Import resolution (resolve/imports.rs).
//!
//! Provides [`ImportResolver`] for resolving `import`/`include`/`use` statements
//! to `IMPORTS` edges (DDD §7.2: `File ||--o{ File : "IMPORTS"`).
//!
//! The resolver walks each [`ExtractResult`]'s `imports` field, resolves the
//! `ImportInfo::source_file` to a target File node in the graph, and creates a
//! `File → File` IMPORTS edge when both endpoints are found. Unresolved imports
//! (external modules, missing files) are logged at `warn` level and skipped —
//! they do not panic (Rule 12: failures must be explicit, not silent).
//!
//! # Resolution strategy (deterministic — Rule 5)
//!
//! 1. **Direct match**: `source_file` exactly matches a File node's `file_path`
//!    or `name` (e.g. `"b.rs"`, `"./utils.rs"`).
//! 2. **Rust module paths** (`crate::`, `self::`, `super::`): resolve to
//!    `src/{path}.rs` or `src/{path}/mod.rs`, stripping a trailing symbol
//!    name component if the full path doesn't match (e.g.
//!    `crate::model::Node` → `src/model.rs`).
//! 3. **Relative path with extension probing**: for paths starting with `.` or
//!    `/`, resolve relative to the importing file's directory and try common
//!    extensions (`.ts`, `.tsx`, `.js`, `.rs`, `.go`, `.py`, …) plus
//!    `index.{ext}` for barrel imports.
//! 4. **External modules** (no `.`/`/` prefix, e.g. `"react"`, `"std::io"`):
//!    no local File node exists → skip with `warn`.

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

use tracing::warn;

use crate::ir::ExtractResult;
use crate::model::{ConfidenceTier, Edge, EdgeType, Graph, Language, NodeLabel};

/// Confidence for an IMPORTS edge (structural, explicit in syntax).
/// Matches the lower bound of `EdgeType::Imports::confidence_range()` = (0.95, 1.0).
const CONFIDENCE_IMPORTS: f32 = 0.95;

/// Extensions tried when resolving extensionless relative imports.
/// Ordered by approximate frequency in polyglot projects.
const EXTENSION_PROBES: &[&str] = &[
    "ts", "tsx", "js", "jsx", "rs", "go", "py", "java", "c", "h", "cpp", "cc",
];

/// Resolves `import`/`include`/`use` statements to `IMPORTS` edges.
///
/// Constructed with the project name. Call [`resolve_imports`] to walk
/// [`ExtractResult`]s and add `File → File` IMPORTS edges to the graph.
///
/// [`resolve_imports`]: ImportResolver::resolve_imports
pub struct ImportResolver<'a> {
    project: &'a str,
}

impl<'a> ImportResolver<'a> {
    /// Creates a new `ImportResolver` for the given project.
    #[must_use]
    pub fn new(project: &'a str) -> Self {
        Self { project }
    }

    /// Resolves all imports from [`ExtractResult`]s and adds `IMPORTS` edges to
    /// the graph.
    ///
    /// For each `ImportInfo` in each result, resolves the `source_file` to a
    /// target File node id. If both the importing file's File node and the
    /// target File node exist in the graph, an `IMPORTS` edge is created.
    /// Duplicate `(source, target)` pairs are collapsed to a single edge
    /// (matching `CallResolver`'s dedup behaviour).
    ///
    /// # Arguments
    ///
    /// * `results` - The extraction results containing import information.
    /// * `graph` - The graph to add resolved IMPORTS edges to. Must already
    ///   contain File nodes (created by the scope phase).
    ///
    /// # Returns
    ///
    /// A vector of all resolved IMPORTS edges (also added to `graph`).
    pub fn resolve_imports(&self, results: &[ExtractResult], graph: &mut Graph) -> Vec<Edge> {
        let file_index = build_file_index(graph);

        let mut edges = Vec::new();
        // Deduplicate by (source_file_id, target_file_id) — one IMPORTS edge
        // per file pair, regardless of how many symbols are imported.
        let mut seen_pairs: HashSet<(String, String)> = HashSet::new();

        for result in results {
            // Scheme C (v0.3.0): C++ #include edges are handled by ResolvePhase
            // as EdgeType::Includes (scope-aware). Skip C++ here to avoid
            // duplicate IMPORTS edges — see phases.rs ResolvePhase::run.
            #[cfg(feature = "lang-cpp")]
            if result.language == Language::Cpp {
                continue;
            }
            // result.file_path is absolute in production (e.g.
            // /home/dev/.../src/lib.rs) but file_index keys are relative
            // (e.g. `src/lib.rs`). find_file_in_index handles this mismatch.
            let (source_file_id, importer_rel_path) = match find_file_in_index(
                &file_index,
                &result.file_path,
            ) {
                Some((id, rel)) => (id, rel),
                None => {
                    // Single-line for coverage: tarpaulin attribute continuation
                    warn!(file = %result.file_path, "IMPORTS source File node not found in graph; skipping imports for this file");
                    continue;
                }
            };

            for import in &result.imports {
                // Single-line for coverage: tarpaulin attribute continuation
                if import.source_file.is_empty() {
                    continue;
                }
                // Single-line for coverage: tarpaulin attribute continuation
                let target_file_id = match resolve_import_target(
                    &import.source_file,
                    &importer_rel_path,
                    &file_index,
                ) {
                    Some(id) => id,
                    None => {
                        // Single-line for coverage: tarpaulin attribute continuation
                        warn!(import = %import.source_file, importer = %result.file_path, line = import.line, "IMPORTS target unresolved (external module or missing file); skipping");
                        continue;
                    }
                };

                let pair_key = (source_file_id.clone(), target_file_id.clone());
                // Single-line for coverage: tarpaulin attribute continuation
                if !seen_pairs.insert(pair_key) {
                    continue;
                }

                // Single-line for coverage: tarpaulin attribute continuation
                let edge = Edge::builder(
                    source_file_id.clone(),
                    target_file_id,
                    EdgeType::Imports,
                    self.project,
                )
                .confidence(CONFIDENCE_IMPORTS)
                .confidence_tier(ConfidenceTier::ImportScoped)
                .start_line(import.line)
                .build();
                graph.add_edge(edge.clone());
                edges.push(edge);
            }
        }

        edges
    }
}

/// Builds a lookup map from file path AND file name → File node id.
///
/// Both `file_path` (e.g. `"src/utils.ts"`) and `name` (often the relative
/// path) are indexed so that `ImportInfo::source_file` can match either form.
fn build_file_index(graph: &Graph) -> HashMap<String, String> {
    let mut index = HashMap::new();
    for node in graph.nodes_by_label(NodeLabel::File) {
        if let Some(fp) = &node.file_path {
            index.entry(fp.clone()).or_insert_with(|| node.id.clone());
        }
        index
            .entry(node.name.clone())
            .or_insert_with(|| node.id.clone());
    }
    index
}

/// Finds a File node id and its relative path in the index.
///
/// `result.file_path` is absolute in production (e.g.
/// `/home/dev/projects/CodeNexus/src/lib.rs`) but `file_index` keys are
/// relative paths normalized by the scope phase (e.g. `src/lib.rs`). This
/// function tries direct match first, then suffix match with path boundary
/// check to bridge the absolute/relative gap.
///
/// Returns `(file_node_id, relative_path)` on success. The relative_path is
/// used as `importer_path` in [`resolve_import_target`] so that
/// `normalise_relative` works correctly (it expects relative paths).
fn find_file_in_index(
    file_index: &HashMap<String, String>,
    path: &str,
) -> Option<(String, String)> {
    // Direct match (handles relative paths and test cases).
    if let Some(id) = file_index.get(path) {
        return Some((id.clone(), path.to_string()));
    }
    // Suffix match: path may be absolute while file_index uses relative paths.
    // e.g. path = "/home/dev/projects/CodeNexus/src/lib.rs"
    //      file_index key = "src/lib.rs"
    //
    // Pick the LONGEST suffix match (most specific) for determinism (Rule 5):
    // HashMap iteration order is non-deterministic, so returning the first
    // match would produce different results across runs when multiple keys
    // suffix-match the same path (e.g. "index.ts" and "src/index.ts" both
    // match "/proj/src/index.ts").
    // Boundary check accepts both `/` and `\` for cross-platform support.
    let path_norm = path.replace('\\', "/");
    let mut best: Option<(&String, &String)> = None;
    for (rel, id) in file_index {
        let rel_norm = rel.replace('\\', "/");
        if path_norm.ends_with(rel_norm.as_str()) {
            let prefix_len = path_norm.len() - rel_norm.len();
            if (prefix_len == 0 || path_norm.as_bytes()[prefix_len - 1] == b'/')
                && best.as_ref().is_none_or(|(r, _)| rel.len() > r.len())
            {
                best = Some((rel, id));
            }
        }
    }
    best.map(|(rel, id)| (id.clone(), rel.clone()))
}

/// Resolves an `ImportInfo::source_file` to a target File node id.
///
/// Deterministic resolution (Rule 5) — no LLM, no fuzzy matching:
///
/// 1. Direct match against the file index (handles `"b.rs"`, `"./utils.ts"`).
/// 2. Rust module paths (`crate::`, `self::`, `super::`) resolve to
///    `src/{path}.rs` or `src/{path}/mod.rs`, stripping a trailing symbol
///    name component if the full path doesn't match.
/// 3. For relative paths (starting with `.` or `/`), normalise against the
///    importer's directory and probe common extensions + `index.{ext}`.
/// 4. External bare specifiers (`"react"`, `"std::io"`) return `None`.
fn resolve_import_target(
    source_file: &str,
    importer_path: &str,
    file_index: &HashMap<String, String>,
) -> Option<String> {
    // Strategy 1: direct match.
    if let Some(id) = file_index.get(source_file) {
        return Some(id.clone());
    }

    // Strategy 2: Rust module path resolution (crate::, self::, super::).
    // Rust `use crate::model::Node` produces source_file = "crate::model::Node",
    // which needs module-path-aware resolution to find src/model.rs.
    if let Some(id) = resolve_rust_module_path(source_file, importer_path, file_index) {
        return Some(id);
    }

    // Strategy 3: relative path resolution + extension probing.
    // Only attempt path resolution for relative specifiers (TS/JS `./`, `../`,
    // or absolute `/`). Bare specifiers like "react" or "std::io" are external.
    let is_relative = source_file.starts_with('.') || source_file.starts_with('/');
    if !is_relative {
        // Strategy 4: C/C++ #include suffix matching.
        // Bare filenames like "format.h" or partial paths like "fmt/format.h"
        // that look like file paths (contain a dot) are matched as suffixes of
        // file_index keys, with path boundary check. Prefers same-directory
        // matches (standard #include "..." behavior).
        if source_file.contains('.') {
            if let Some(id) = resolve_include_suffix(source_file, importer_path, file_index) {
                return Some(id);
            }
        }
        // Strategy 5: Java class import resolution.
        // Java imports like "com.google.gson.Gson" are dotted package paths
        // that map to file paths by replacing '.' with '/' and appending
        // '.java'. Returns None for external deps (JDK, Maven artifacts) that
        // have no matching local file.
        if let Some(id) = resolve_java_class_import(source_file, importer_path, file_index) {
            return Some(id);
        }
        return None;
    }

    let normalised = normalise_relative(source_file, importer_path);
    // TS ESM (NodeNext / moduleResolution=bundler) requires `.js`/`.jsx`/`.mjs`/`.cjs`
    // extensions in specifiers even when the source file is `.ts`/`.tsx`. Strip these
    // before probing so `./types/api.js` resolves to `types/api.ts`.
    let normalised = strip_js_style_extension(&normalised);
    if let Some(id) = file_index.get(&normalised) {
        return Some(id.clone());
    }

    // Probe extensions (e.g. "./utils" → "src/utils.ts").
    for ext in EXTENSION_PROBES {
        let candidate = format!("{normalised}.{ext}");
        if let Some(id) = file_index.get(&candidate) {
            return Some(id.clone());
        }
    }

    // Probe barrel imports (e.g. "./utils" → "src/utils/index.ts").
    for ext in EXTENSION_PROBES {
        let candidate = format!("{normalised}/index.{ext}");
        if let Some(id) = file_index.get(&candidate) {
            return Some(id.clone());
        }
    }

    None
}

/// Resolves a C/C++ `#include` path by suffix-matching against file_index keys.
///
/// Bare filenames (`"format.h"`) and partial paths (`"fmt/format.h"`) are
/// matched as suffixes of file paths in the index, with a path boundary check
/// (so `"format.h"` matches `"include/fmt/format.h"` but not `"xformat.h"`).
///
/// When multiple files match, the standard C++ `#include "..."` behavior is
/// followed: prefer files in the same directory as the importer, then fall
/// back to the shortest matching path (closest to project root).
fn resolve_include_suffix(
    include_path: &str,
    importer_path: &str,
    file_index: &HashMap<String, String>,
) -> Option<String> {
    let path_norm = include_path.replace('\\', "/");
    let importer_dir = importer_path
        .rsplit_once('/')
        .map(|(dir, _)| dir)
        .unwrap_or("");

    let mut same_dir: Option<(&String, &String)> = None;
    let mut other: Option<(&String, &String)> = None;

    for (rel, id) in file_index {
        let rel_norm = rel.replace('\\', "/");
        if rel_norm.ends_with(path_norm.as_str()) {
            let prefix_len = rel_norm.len() - path_norm.len();
            if prefix_len == 0 || rel_norm.as_bytes()[prefix_len - 1] == b'/' {
                let match_dir = rel_norm.rsplit_once('/').map(|(dir, _)| dir).unwrap_or("");
                if match_dir == importer_dir {
                    // Same directory — pick shortest path for determinism.
                    if same_dir.as_ref().is_none_or(|(r, _)| r.len() > rel.len()) {
                        same_dir = Some((rel, id));
                    }
                } else {
                    // Other directory — pick shortest path (closest to root).
                    if other.as_ref().is_none_or(|(r, _)| r.len() > rel.len()) {
                        other = Some((rel, id));
                    }
                }
            }
        }
    }

    same_dir.or(other).map(|(_, id)| id.clone())
}

/// Resolves a Java class import by mapping the dotted package path to a file
/// path and suffix-matching against `file_index`.
///
/// Java imports like `com.google.gson.Gson` map to file path
/// `com/google/gson/Gson.java` (replace `.` with `/`, append `.java`). The
/// mapped path is then suffix-matched against file_index keys (which may have
/// a `src/main/java/` prefix in Maven layouts).
///
/// For static imports (`com.google.gson.Gson.fromJson`) where the last
/// component is a member name rather than a class, the parent path is also
/// tried (`com/google/gson/Gson.java`).
///
/// Returns `None` for external dependencies (JDK classes like `java.util.List`,
/// Maven artifacts) that have no matching local file.
fn resolve_java_class_import(
    source_file: &str,
    importer_path: &str,
    file_index: &HashMap<String, String>,
) -> Option<String> {
    // Java imports are dotted package paths: "com.google.gson.Gson".
    // A '/' indicates a file path (handled by strategies 3/4), not a package.
    if source_file.contains('/') || !source_file.contains('.') {
        return None;
    }

    // Full path: com.google.gson.Gson → com/google/gson/Gson.java
    let mapped = format!("{}.java", source_file.replace('.', "/"));
    if let Some(id) = resolve_include_suffix(&mapped, importer_path, file_index) {
        return Some(id);
    }

    // Strip last component (static import member or symbol name):
    // com.google.gson.Gson.fromJson → com/google/gson/Gson.java
    if let Some((parent, _)) = source_file.rsplit_once('.') {
        let mapped = format!("{}.java", parent.replace('.', "/"));
        if let Some(id) = resolve_include_suffix(&mapped, importer_path, file_index) {
            return Some(id);
        }
    }

    None
}

/// Strips `.js`/`.jsx`/`.mjs`/`.cjs` extensions from a normalised path.
///
/// TS ESM (NodeNext / moduleResolution=bundler) requires `.js` extensions in
/// import specifiers even when the source file is `.ts`. This strips the
/// extension so downstream extension probing can find the `.ts`/`.tsx` file.
/// Non-JS extensions (`.ts`, `.tsx`, `.rs`, …) are preserved.
fn strip_js_style_extension(path: &str) -> String {
    for ext in [".js", ".jsx", ".mjs", ".cjs"] {
        if let Some(stripped) = path.strip_suffix(ext) {
            return stripped.to_string();
        }
    }
    path.to_string()
}

/// Normalises a relative `source_file` against the importer's directory.
///
/// `./utils` imported from `src/a.ts` → `src/utils`.
/// `../helpers/b` imported from `src/sub/c.ts` → `src/helpers/b`.
/// Leading `./` and `../` are resolved; backslashes are converted to `/`.
fn normalise_relative(source_file: &str, importer_path: &str) -> String {
    // Convert backslashes to forward slashes BEFORE path parsing so that
    // Windows-style specifiers are handled correctly on Unix (where `\` is
    // not a path separator and `Path::parent` would mis-parse it).
    let specifier = source_file.replace('\\', "/");
    let importer_normalised = importer_path.replace('\\', "/");
    let importer_dir = Path::new(&importer_normalised)
        .parent()
        .and_then(|p| p.to_str())
        .unwrap_or("");

    let combined = if importer_dir.is_empty() {
        specifier
    } else {
        format!("{importer_dir}/{specifier}")
    };

    // Resolve `.` and `..` segments.
    let mut segments: Vec<&str> = Vec::new();
    for seg in combined.split('/') {
        match seg {
            "" | "." => continue,
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }
    segments.join("/")
}

/// Resolves a Rust module path (`crate::`, `self::`, `super::` prefix) to a
/// target File node id.
///
/// Rust `use crate::model::Node` produces `source_file = "crate::model::Node"`.
/// The last component (`Node`) is typically a symbol name, not a module, so we
/// try both the full path and the parent path (stripping the last component).
///
/// # Candidates (tried in order)
///
/// For `crate::a::b`:
/// 1. `src/a/b.rs`, `src/a/b/mod.rs` (full path as module)
/// 2. `src/a.rs`, `src/a/mod.rs` (last component is symbol name)
///
/// For `self::b` / `super::b`, the same logic applies but the path is
/// normalised relative to the importer's directory first.
fn resolve_rust_module_path(
    source_file: &str,
    importer_path: &str,
    file_index: &HashMap<String, String>,
) -> Option<String> {
    // Detect Rust module path prefixes. Return None for non-Rust specifiers
    // (e.g. "react", "./b.ts") so Strategy 3 (relative path) can handle them.
    if let Some(module_path) = source_file.strip_prefix("crate::") {
        let path = module_path.replace("::", "/");
        return try_candidates(&rust_crate_candidates(&path), file_index);
    }

    if let Some(module_path) = source_file.strip_prefix("self::") {
        let path = module_path.replace("::", "/");
        let relative = format!("./{path}");
        let normalised = normalise_relative(&relative, importer_path);
        return try_candidates(&rust_relative_candidates(&normalised), file_index);
    }

    if let Some(module_path) = source_file.strip_prefix("super::") {
        let path = module_path.replace("::", "/");
        let relative = format!("../{path}");
        let normalised = normalise_relative(&relative, importer_path);
        return try_candidates(&rust_relative_candidates(&normalised), file_index);
    }

    None
}

/// Returns the first match from a list of candidate file paths.
fn try_candidates(candidates: &[String], file_index: &HashMap<String, String>) -> Option<String> {
    for candidate in candidates {
        if let Some(id) = file_index.get(candidate) {
            return Some(id.clone());
        }
    }
    None
}

/// Generates candidate file paths for `crate::` prefixed module paths.
///
/// `crate::a::b` (path = "a/b") tries:
/// - `src/a/b.rs`, `src/a/b/mod.rs` (full path as module)
/// - `src/a.rs`, `src/a/mod.rs` (last component is symbol name)
fn rust_crate_candidates(path: &str) -> Vec<String> {
    let mut candidates = Vec::new();
    // Full path: the entire path is a module file.
    candidates.push(format!("src/{path}.rs"));
    candidates.push(format!("src/{path}/mod.rs"));
    // Parent path: last component is a symbol name (e.g. `Node` in `model::Node`).
    if let Some((parent, _)) = path.rsplit_once('/') {
        candidates.push(format!("src/{parent}.rs"));
        candidates.push(format!("src/{parent}/mod.rs"));
    }
    candidates
}

/// Generates candidate file paths for `self::`/`super::` prefixed module paths.
///
/// `self::b` (normalised = "src/b") tries:
/// - `src/b.rs`, `src/b/mod.rs` (full path as module)
/// - `src.rs`, `src/mod.rs` — unlikely but covered for single-component parents
///
/// `self::a::b` (normalised = "src/a/b") tries:
/// - `src/a/b.rs`, `src/a/b/mod.rs` (full path as module)
/// - `src/a.rs`, `src/a/mod.rs` (last component is symbol name)
fn rust_relative_candidates(normalised: &str) -> Vec<String> {
    let mut candidates = Vec::new();
    // Full path: the entire normalised path is a module file.
    candidates.push(format!("{normalised}.rs"));
    candidates.push(format!("{normalised}/mod.rs"));
    // Parent path: last component is a symbol name.
    if let Some((parent, _)) = normalised.rsplit_once('/') {
        candidates.push(format!("{parent}.rs"));
        candidates.push(format!("{parent}/mod.rs"));
    }
    candidates
}

#[cfg(all(test, feature = "lang-cpp", feature = "lang-typescript"))]
mod tests {
    use super::*;
    use crate::model::{Language, Node, NodeLabel};

    /// Builds a File node with the given relative path as id, name, and
    /// file_path (mirrors what `build_file_nodes` produces in the scope phase,
    /// but uses the path as id for simpler test assertions).
    fn make_file_node(path: &str, project: &str) -> Node {
        Node::builder(NodeLabel::File, path, path)
            .id(path)
            .project(project)
            .file_path(path)
            .language(Language::TypeScript)
            .build()
    }

    /// Creates an `ExtractResult` for the given file.
    fn make_result(file_path: &str) -> ExtractResult {
        ExtractResult::new(file_path, Language::TypeScript)
    }

    /// Creates a C++ `ExtractResult` for the given file.
    fn make_result_cpp(file_path: &str) -> ExtractResult {
        ExtractResult::new(file_path, Language::Cpp)
    }

    // --- resolve_imports: explicit import ---

    #[test]
    fn resolve_imports_creates_edge_for_explicit_import() {
        // File a.ts imports from b.ts → IMPORTS edge a.ts → b.ts.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec!["foo".to_string()],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "should create 1 IMPORTS edge");
        let edge = &edges[0];
        assert_eq!(edge.edge_type, EdgeType::Imports);
        assert_eq!(edge.source, "a.ts");
        assert_eq!(edge.target, "b.ts");
        assert!((edge.confidence - 0.95).abs() < 1e-6);
        assert_eq!(edge.confidence_tier, ConfidenceTier::ImportScoped);
        assert_eq!(edge.start_line, Some(1));
        assert_eq!(graph.edge_count(), 1);
    }

    // --- resolve_imports: empty imports ---

    #[test]
    fn resolve_imports_handles_empty_imports() {
        let result = make_result("a.ts");
        let results = vec![result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(edges.is_empty(), "no imports → no edges");
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn resolve_imports_empty_results_returns_empty() {
        let mut graph = Graph::new();
        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&[], &mut graph);
        assert!(edges.is_empty());
    }

    // --- resolve_imports: skips unresolved ---

    #[test]
    fn resolve_imports_skips_unresolved_imports() {
        // a.ts imports "react" (external) — no File node, should skip without panic.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "react".to_string(),
            imported_names: vec!["useState".to_string()],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        // No "react" File node in graph.

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(edges.is_empty(), "unresolved import → no edge");
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn resolve_imports_skips_when_source_file_node_missing() {
        // No File node for the importing file → skip without panic.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        // Only b.ts exists; a.ts File node is missing.
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);
        assert!(edges.is_empty());
    }

    #[test]
    fn resolve_imports_skips_empty_source_file() {
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: String::new(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);
        assert!(edges.is_empty());
    }

    // --- resolve_imports: deduplication ---

    #[test]
    fn resolve_imports_deduplicates_edges() {
        // a.ts imports foo and bar from b.ts — one IMPORTS edge a.ts → b.ts.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec!["foo".to_string()],
            line: 1,
        });
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec!["bar".to_string()],
            line: 2,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "duplicate (source, target) → 1 edge");
        assert_eq!(graph.edge_count(), 1);
    }

    // --- resolve_imports: extension probing ---

    #[test]
    fn resolve_imports_resolves_extensionless_relative_import() {
        // a.ts imports "./utils" — should resolve to utils.ts via extension probe.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./utils".to_string(),
            imported_names: vec!["helper".to_string()],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("utils.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "extensionless import should resolve");
        assert_eq!(edges[0].target, "utils.ts");
    }

    #[test]
    fn resolve_imports_resolves_subdirectory_relative_import() {
        // src/a.ts imports "./helpers/b" → src/helpers/b.ts.
        let mut a_result = make_result("src/a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./helpers/b".to_string(),
            imported_names: vec!["foo".to_string()],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/a.ts", "proj"));
        graph.add_node(make_file_node("src/helpers/b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].source, "src/a.ts");
        assert_eq!(edges[0].target, "src/helpers/b.ts");
    }

    #[test]
    fn resolve_imports_resolves_parent_directory_import() {
        // src/sub/a.ts imports "../b" → src/b.ts.
        let mut a_result = make_result("src/sub/a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "../b".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/sub/a.ts", "proj"));
        graph.add_node(make_file_node("src/b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].target, "src/b.ts");
    }

    #[test]
    fn resolve_imports_resolves_barrel_import() {
        // a.ts imports "./utils" → utils/index.ts (barrel).
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./utils".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("utils/index.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "barrel import should resolve");
        assert_eq!(edges[0].target, "utils/index.ts");
    }

    // --- resolve_imports: multiple files ---

    #[test]
    fn resolve_imports_handles_multiple_files() {
        // a.ts imports b.ts; c.ts imports d.ts — 2 edges.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let mut c_result = make_result("c.ts");
        c_result.imports.push(crate::ir::ImportInfo {
            source_file: "./d.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result, c_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("b.ts", "proj"));
        graph.add_node(make_file_node("c.ts", "proj"));
        graph.add_node(make_file_node("d.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 2);
        assert_eq!(graph.edge_count(), 2);
    }

    // --- resolve_imports: adds edges to graph (neighbour traversal) ---

    #[test]
    fn resolve_imports_adds_edges_to_graph_for_traversal() {
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        resolver.resolve_imports(&results, &mut graph);

        // Verify neighbour traversal works.
        let neighbors = graph.neighbors(&"a.ts".to_string(), Some(EdgeType::Imports));
        assert_eq!(neighbors.len(), 1);
        assert_eq!(neighbors[0].id, "b.ts");
    }

    // --- normalise_relative helper ---

    #[test]
    fn normalise_relative_dot_slash() {
        let n = normalise_relative("./b", "src/a.ts");
        assert_eq!(n, "src/b");
    }

    #[test]
    fn normalise_relative_dot_dot_slash() {
        let n = normalise_relative("../b", "src/sub/a.ts");
        assert_eq!(n, "src/b");
    }

    #[test]
    fn normalise_relative_strips_leading_dot() {
        let n = normalise_relative("./utils", "a.ts");
        assert_eq!(n, "utils");
    }

    #[test]
    fn normalise_relative_handles_backslashes() {
        let n = normalise_relative(".\\b", "src\\a.ts");
        assert_eq!(n, "src/b");
    }

    // --- resolve_import_target: Strategy 1 (direct match) ---

    #[test]
    fn resolve_imports_resolves_direct_match_strategy() {
        // Import with source_file exactly matching a file_path in the index
        // (not a relative specifier) → Strategy 1 direct match.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "b.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "direct match should resolve");
        assert_eq!(edges[0].target, "b.ts");
    }

    // --- resolve_import_target: final None fallback ---

    #[test]
    fn resolve_imports_relative_unresolvable_returns_none() {
        // Relative import "./nonexistent" where no matching file exists
        // → exhausts all strategies → final None fallback → skip.
        let mut a_result = make_result("a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./nonexistent".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("a.ts", "proj"));
        // No "nonexistent" file in graph.

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(edges.is_empty(), "unresolvable relative import → no edge");
    }

    // --- resolve_imports: source File node missing from graph ---

    #[test]
    fn resolve_imports_skips_when_source_file_not_in_graph() {
        // ExtractResult references a file_path that has no File node in the
        // graph → file_index.get returns None → skip with warn (line 92).
        let mut orphan_result = make_result("orphan.ts");
        orphan_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![orphan_result];

        let mut graph = Graph::new();
        // Only "b.ts" is in the graph; "orphan.ts" is not.
        graph.add_node(make_file_node("b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(edges.is_empty(), "source file not in graph → no edges");
    }

    // --- resolve_imports: Rust module path resolution (crate::) ---

    #[test]
    fn resolve_imports_resolves_rust_crate_prefix_to_src_file() {
        // src/lib.rs imports `crate::model` → src/model.rs
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "crate::model".to_string(),
            imported_names: vec!["Node".to_string()],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "crate:: prefix should resolve to src/model.rs"
        );
        assert_eq!(edges[0].source, "src/lib.rs");
        assert_eq!(edges[0].target, "src/model.rs");
    }

    #[test]
    fn resolve_imports_resolves_rust_crate_prefix_with_symbol_name() {
        // src/lib.rs imports `crate::model::Node` → src/model.rs (Node is a symbol)
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "crate::model::Node".to_string(),
            imported_names: vec!["Node".to_string()],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "symbol name should be stripped, resolving to src/model.rs"
        );
        assert_eq!(edges[0].target, "src/model.rs");
    }

    #[test]
    fn resolve_imports_resolves_rust_crate_prefix_to_mod_file() {
        // src/lib.rs imports `crate::model` → src/model/mod.rs
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "crate::model".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/model/mod.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "crate:: prefix should resolve to src/model/mod.rs"
        );
        assert_eq!(edges[0].target, "src/model/mod.rs");
    }

    #[test]
    fn resolve_imports_resolves_rust_crate_nested_module() {
        // src/lib.rs imports `crate::parse::parser` → src/parse/parser.rs
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "crate::parse::parser".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/parse/parser.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "nested crate:: path should resolve");
        assert_eq!(edges[0].target, "src/parse/parser.rs");
    }

    // --- resolve_imports: Rust module path resolution (self::, super::) ---

    #[test]
    fn resolve_imports_resolves_rust_self_prefix() {
        // src/lib.rs imports `self::model` → src/model.rs
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "self::model".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "self:: prefix should resolve");
        assert_eq!(edges[0].target, "src/model.rs");
    }

    #[test]
    fn resolve_imports_resolves_rust_super_prefix() {
        // src/sub/mod.rs imports `super::model` → src/model.rs
        let mut sub_result = make_result("src/sub/mod.rs");
        sub_result.imports.push(crate::ir::ImportInfo {
            source_file: "super::model".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![sub_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/sub/mod.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(edges.len(), 1, "super:: prefix should resolve");
        assert_eq!(edges[0].target, "src/model.rs");
    }

    #[test]
    fn resolve_imports_resolves_rust_super_prefix_with_symbol() {
        // src/sub/mod.rs imports `super::model::Node` → src/model.rs
        let mut sub_result = make_result("src/sub/mod.rs");
        sub_result.imports.push(crate::ir::ImportInfo {
            source_file: "super::model::Node".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![sub_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/sub/mod.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "super:: with symbol should strip last component"
        );
        assert_eq!(edges[0].target, "src/model.rs");
    }

    // --- resolve_imports: Rust external crate skipped ---

    #[test]
    fn resolve_imports_skips_rust_external_crate() {
        // src/lib.rs imports `std::io` (external crate) — no File node, skip.
        let mut lib_result = make_result("src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "std::io".to_string(),
            imported_names: vec!["Read".to_string()],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/lib.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(edges.is_empty(), "external crate (std::io) → no edge");
    }

    // --- resolve_rust_module_path helper (direct unit tests) ---

    #[test]
    fn resolve_rust_module_path_crate_prefix_resolves_src_file() {
        let mut index = HashMap::new();
        index.insert("src/model.rs".to_string(), "id-model".to_string());

        let result = resolve_rust_module_path("crate::model", "src/lib.rs", &index);
        assert_eq!(result, Some("id-model".to_string()));
    }

    #[test]
    fn resolve_rust_module_path_crate_prefix_with_symbol_strips_last() {
        let mut index = HashMap::new();
        index.insert("src/model.rs".to_string(), "id-model".to_string());

        let result = resolve_rust_module_path("crate::model::Node", "src/lib.rs", &index);
        assert_eq!(result, Some("id-model".to_string()));
    }

    #[test]
    fn resolve_rust_module_path_crate_prefix_resolves_mod_file() {
        let mut index = HashMap::new();
        index.insert("src/model/mod.rs".to_string(), "id-model-mod".to_string());

        let result = resolve_rust_module_path("crate::model", "src/lib.rs", &index);
        assert_eq!(result, Some("id-model-mod".to_string()));
    }

    #[test]
    fn resolve_rust_module_path_external_returns_none() {
        let mut index = HashMap::new();
        index.insert("src/model.rs".to_string(), "id-model".to_string());

        let result = resolve_rust_module_path("std::io", "src/lib.rs", &index);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_rust_module_path_non_rust_returns_none() {
        let index = HashMap::new();

        let result = resolve_rust_module_path("react", "src/lib.ts", &index);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_rust_module_path_no_match_returns_none() {
        let mut index = HashMap::new();
        index.insert("src/other.rs".to_string(), "id-other".to_string());

        let result = resolve_rust_module_path("crate::nonexistent", "src/lib.rs", &index);
        assert_eq!(result, None);
    }

    #[test]
    fn resolve_rust_module_path_self_prefix_resolves() {
        let mut index = HashMap::new();
        index.insert("src/model.rs".to_string(), "id-model".to_string());

        let result = resolve_rust_module_path("self::model", "src/lib.rs", &index);
        assert_eq!(result, Some("id-model".to_string()));
    }

    #[test]
    fn resolve_rust_module_path_super_prefix_resolves() {
        let mut index = HashMap::new();
        index.insert("src/model.rs".to_string(), "id-model".to_string());

        let result = resolve_rust_module_path("super::model", "src/sub/mod.rs", &index);
        assert_eq!(result, Some("id-model".to_string()));
    }

    // --- find_file_in_index: absolute vs relative path mismatch ---

    #[test]
    fn find_file_in_index_direct_match_relative() {
        let mut index = HashMap::new();
        index.insert("src/lib.rs".to_string(), "id-lib".to_string());

        let result = find_file_in_index(&index, "src/lib.rs");
        assert_eq!(
            result,
            Some(("id-lib".to_string(), "src/lib.rs".to_string()))
        );
    }

    #[test]
    fn find_file_in_index_absolute_path_suffix_match() {
        // result.file_path is absolute, file_index keys are relative.
        let mut index = HashMap::new();
        index.insert("src/lib.rs".to_string(), "id-lib".to_string());

        let result = find_file_in_index(&index, "/home/dev/projects/CodeNexus/src/lib.rs");
        assert_eq!(
            result,
            Some(("id-lib".to_string(), "src/lib.rs".to_string()))
        );
    }

    #[test]
    fn find_file_in_index_suffix_boundary_check() {
        // Ensure "xsrc/lib.rs" does NOT match "/path/to/src/lib.rs"
        let mut index = HashMap::new();
        index.insert("xsrc/lib.rs".to_string(), "id-xlib".to_string());

        let result = find_file_in_index(&index, "/home/dev/projects/CodeNexus/src/lib.rs");
        assert_eq!(
            result, None,
            "xsrc/lib.rs should not suffix-match src/lib.rs"
        );
    }

    #[test]
    fn find_file_in_index_no_match_returns_none() {
        let mut index = HashMap::new();
        index.insert("src/other.rs".to_string(), "id-other".to_string());

        let result = find_file_in_index(&index, "/home/dev/projects/CodeNexus/src/lib.rs");
        assert_eq!(result, None);
    }

    #[test]
    fn find_file_in_index_multiple_suffix_matches_picks_longest() {
        // Determinism (Rule 5): when multiple keys suffix-match the same path,
        // pick the longest (most specific) to avoid HashMap order non-determinism.
        let mut index = HashMap::new();
        index.insert("index.ts".to_string(), "id-root".to_string());
        index.insert("src/index.ts".to_string(), "id-src".to_string());

        let result = find_file_in_index(&index, "/home/dev/proj/src/index.ts");
        assert_eq!(
            result,
            Some(("id-src".to_string(), "src/index.ts".to_string())),
            "longest suffix match should win for determinism"
        );
    }

    #[test]
    fn find_file_in_index_windows_backslash_boundary() {
        // Windows paths use `\` as separator; boundary check must accept it.
        let mut index = HashMap::new();
        index.insert("src/lib.rs".to_string(), "id-lib".to_string());

        let result = find_file_in_index(&index, r"C:\Users\dev\proj\src\lib.rs");
        assert_eq!(
            result,
            Some(("id-lib".to_string(), "src/lib.rs".to_string())),
            "Windows backslash separator should be accepted in boundary check"
        );
    }

    // --- resolve_imports: absolute importer path (production scenario) ---

    #[test]
    fn resolve_imports_handles_absolute_importer_path() {
        // Production scenario: result.file_path is absolute, but File nodes
        // in graph use relative paths. IMPORTS edge should still be created.
        let mut lib_result = make_result("/home/dev/projects/CodeNexus/src/lib.rs");
        lib_result.imports.push(crate::ir::ImportInfo {
            source_file: "crate::model".to_string(),
            imported_names: vec!["Node".to_string()],
            line: 1,
        });
        let results = vec![lib_result];

        let mut graph = Graph::new();
        // File nodes use relative paths (as normalized by scope phase).
        graph.add_node(make_file_node("src/lib.rs", "proj"));
        graph.add_node(make_file_node("src/model.rs", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "absolute importer path should resolve via suffix match"
        );
        assert_eq!(edges[0].target, "src/model.rs");
    }

    #[test]
    fn resolve_imports_absolute_path_with_relative_ts_import() {
        // TS import with absolute importer path: ./b.ts should still resolve.
        let mut a_result = make_result("/home/dev/projects/subno.ts/src/a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./b.ts".to_string(),
            imported_names: vec!["foo".to_string()],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/a.ts", "proj"));
        graph.add_node(make_file_node("src/b.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "absolute importer + relative TS import should resolve"
        );
        assert_eq!(edges[0].source, "src/a.ts");
        assert_eq!(edges[0].target, "src/b.ts");
    }

    // --- TS ESM .js/.jsx extension stripping (NodeNext / bundler resolution) ---

    #[test]
    fn resolve_imports_strips_js_extension_for_ts_esm() {
        // TS NodeNext ESM requires `.js` in specifiers even for `.ts` files.
        // sdk/typescript/src/client.ts imports "./types/api.js" → types/api.ts
        let mut client_result = make_result("sdk/typescript/src/client.ts");
        client_result.imports.push(crate::ir::ImportInfo {
            source_file: "./types/api.js".to_string(),
            imported_names: vec!["ClientOptions".to_string()],
            line: 1,
        });
        let results = vec![client_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("sdk/typescript/src/client.ts", "proj"));
        graph.add_node(make_file_node("sdk/typescript/src/types/api.ts", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            ".js extension should be stripped, resolving to .ts file"
        );
        assert_eq!(edges[0].target, "sdk/typescript/src/types/api.ts");
    }

    #[test]
    fn resolve_imports_strips_jsx_extension() {
        // React JSX: ./Button.jsx → Button.tsx
        let mut app_result = make_result("src/app.tsx");
        app_result.imports.push(crate::ir::ImportInfo {
            source_file: "./Button.jsx".to_string(),
            imported_names: vec!["Button".to_string()],
            line: 1,
        });
        let results = vec![app_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/app.tsx", "proj"));
        graph.add_node(make_file_node("src/Button.tsx", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            ".jsx extension should be stripped, resolving to .tsx file"
        );
        assert_eq!(edges[0].target, "src/Button.tsx");
    }

    #[test]
    fn resolve_imports_strips_mjs_cjs_extensions() {
        // .mjs / .cjs specifiers → .js target (common in Node ESM projects).
        let mut a_result = make_result("src/a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./config.mjs".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/a.ts", "proj"));
        graph.add_node(make_file_node("src/config.js", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            ".mjs extension should be stripped, resolving to .js file"
        );
        assert_eq!(edges[0].target, "src/config.js");
    }

    #[test]
    fn resolve_imports_strips_cjs_extension() {
        let mut a_result = make_result("src/a.ts");
        a_result.imports.push(crate::ir::ImportInfo {
            source_file: "./config.cjs".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![a_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/a.ts", "proj"));
        graph.add_node(make_file_node("src/config.js", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            ".cjs extension should be stripped, resolving to .js file"
        );
        assert_eq!(edges[0].target, "src/config.js");
    }

    // --- C++ #include: skipped by ImportResolver (scheme C, v0.3.0) ---
    // C++ #include is handled by ResolvePhase as EdgeType::Includes edges.
    // ImportResolver skips Language::Cpp results entirely — these tests
    // verify that NO IMPORTS edges are created for C++ #include directives,
    // regardless of whether a matching file exists.

    #[test]
    fn resolve_imports_skips_cpp_include_by_basename() {
        // C++ #include "format.h" — previously resolved via suffix matching
        // to IMPORTS edge. Scheme C: skipped entirely (INCLUDES edge built
        // by ResolvePhase instead).
        let mut std_result = make_result_cpp("include/fmt/std.h");
        std_result.imports.push(crate::ir::ImportInfo {
            source_file: "format.h".to_string(),
            imported_names: vec![],
            line: 11,
        });
        let results = vec![std_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("include/fmt/std.h", "proj"));
        graph.add_node(make_file_node("include/fmt/format.h", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(
            edges.is_empty(),
            "C++ #include should NOT produce IMPORTS edges (scheme C: handled by ResolvePhase)"
        );
    }

    #[test]
    fn resolve_imports_skips_cpp_include_by_partial_path() {
        // C++ #include "fmt/format.h" — previously resolved via partial path
        // suffix matching. Scheme C: skipped entirely.
        let mut top_result = make_result_cpp("src/main.cpp");
        top_result.imports.push(crate::ir::ImportInfo {
            source_file: "fmt/format.h".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![top_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj"));
        graph.add_node(make_file_node("include/fmt/format.h", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(
            edges.is_empty(),
            "C++ partial-path #include should NOT produce IMPORTS edges (scheme C)"
        );
    }

    #[test]
    fn resolve_imports_skips_cpp_system_include() {
        // C++ #include <iostream> — system header, no matching File node.
        // Scheme C: C++ is skipped entirely, so no IMPORTS edge regardless.
        let mut main_result = make_result_cpp("src/main.cpp");
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "iostream".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![main_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(
            edges.is_empty(),
            "C++ system header #include should NOT produce IMPORTS edges (scheme C)"
        );
    }

    #[test]
    fn resolve_imports_skips_cpp_include_even_when_target_exists() {
        // Scheme C regression guard: even when a matching file exists,
        // C++ #include must NOT produce an IMPORTS edge. The INCLUDES edge
        // is built separately by ResolvePhase::build_includes_edges.
        let mut main_result = make_result_cpp("src/main.cpp");
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "foo.h".to_string(),
            imported_names: vec![],
            line: 1,
        });
        let results = vec![main_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj"));
        graph.add_node(make_file_node("src/foo.h", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(
            edges.is_empty(),
            "C++ #include must NOT produce IMPORTS edges even when target file exists (scheme C)"
        );
    }

    // --- Java class import resolution (dotted package path) ---

    #[test]
    fn resolve_imports_resolves_java_class_import() {
        // Java import "com.google.gson.Gson" → com/google/gson/Gson.java
        // Dotted package path is mapped to a file path by replacing '.' with
        // '/' and appending '.java', then suffix-matched against file_index.
        let mut importer_result = make_result("src/com/google/gson/GsonBuilder.java");
        importer_result.imports.push(crate::ir::ImportInfo {
            source_file: "com.google.gson.Gson".to_string(),
            imported_names: vec!["Gson".to_string()],
            line: 3,
        });
        let results = vec![importer_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node(
            "src/com/google/gson/GsonBuilder.java",
            "proj",
        ));
        graph.add_node(make_file_node("src/com/google/gson/Gson.java", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "Java class import should resolve via dotted-path mapping"
        );
        assert_eq!(edges[0].source, "src/com/google/gson/GsonBuilder.java");
        assert_eq!(edges[0].target, "src/com/google/gson/Gson.java");
    }

    #[test]
    fn resolve_imports_resolves_java_class_in_maven_layout() {
        // Maven standard layout: src/main/java/com/google/gson/Gson.java
        // The Java-mapped path "com/google/gson/Gson.java" suffix-matches.
        let mut importer_result = make_result("gson/src/main/java/com/google/gson/Gson.java");
        importer_result.imports.push(crate::ir::ImportInfo {
            source_file: "com.google.gson.JsonElement".to_string(),
            imported_names: vec!["JsonElement".to_string()],
            line: 1,
        });
        let results = vec![importer_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node(
            "gson/src/main/java/com/google/gson/Gson.java",
            "proj",
        ));
        graph.add_node(make_file_node(
            "gson/src/main/java/com/google/gson/JsonElement.java",
            "proj",
        ));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "Java class import should resolve in Maven standard layout"
        );
        assert_eq!(
            edges[0].target,
            "gson/src/main/java/com/google/gson/JsonElement.java"
        );
    }

    #[test]
    fn resolve_imports_skips_java_stdlib_import() {
        // java.util.List — JDK class, no matching File node in the project.
        let mut importer_result = make_result("src/Main.java");
        importer_result.imports.push(crate::ir::ImportInfo {
            source_file: "java.util.List".to_string(),
            imported_names: vec!["List".to_string()],
            line: 1,
        });
        let results = vec![importer_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/Main.java", "proj"));
        // No java/util/List.java in the project.

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert!(
            edges.is_empty(),
            "JDK import (java.util.List) should not resolve to a local file"
        );
    }

    #[test]
    fn resolve_imports_resolves_java_static_import() {
        // import static com.google.gson.Gson.fromJson;
        // source_file = "com.google.gson.Gson.fromJson" — the last component
        // is a static member name, not a class. Strip it and map the parent.
        let mut importer_result = make_result("src/Test.java");
        importer_result.imports.push(crate::ir::ImportInfo {
            source_file: "com.google.gson.Gson.fromJson".to_string(),
            imported_names: vec!["fromJson".to_string()],
            line: 1,
        });
        let results = vec![importer_result];

        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/Test.java", "proj"));
        graph.add_node(make_file_node("src/com/google/gson/Gson.java", "proj"));

        let resolver = ImportResolver::new("proj");
        let edges = resolver.resolve_imports(&results, &mut graph);

        assert_eq!(
            edges.len(),
            1,
            "Java static import should resolve by stripping the member name"
        );
        assert_eq!(edges[0].target, "src/com/google/gson/Gson.java");
    }

    // --- Coverage gap tests: build_file_index, strip_js_style_extension, resolve_java_class_import ---

    #[test]
    fn build_file_index_handles_node_without_file_path() {
        // File node with no file_path → only name is indexed (line 166 None branch).
        let mut graph = Graph::new();
        let node = Node::builder(NodeLabel::File, "name_only.ts", "name_only.ts")
            .id("name_only.ts")
            .project("proj")
            .language(Language::TypeScript)
            .build();
        graph.add_node(node);

        let index = build_file_index(&graph);
        assert_eq!(index.get("name_only.ts"), Some(&"name_only.ts".to_string()));
    }

    #[test]
    fn strip_js_style_extension_preserves_non_js_extensions() {
        assert_eq!(strip_js_style_extension("src/a.ts"), "src/a.ts");
        assert_eq!(strip_js_style_extension("src/a.rs"), "src/a.rs");
        assert_eq!(strip_js_style_extension("src/a.go"), "src/a.go");
    }

    #[test]
    fn resolve_java_class_import_with_slash_returns_none() {
        // Source with '/' is a file path, not a Java package → early None.
        let index = HashMap::new();
        assert_eq!(
            resolve_java_class_import("src/Main.java", "src/App.java", &index),
            None
        );
    }

    #[test]
    fn resolve_java_class_import_without_dot_returns_none() {
        // Source without '.' is not a Java package path → early None.
        let index = HashMap::new();
        assert_eq!(
            resolve_java_class_import("react", "src/App.java", &index),
            None
        );
    }

    #[test]
    fn resolve_include_suffix_prefers_same_directory() {
        // Two files both suffix-match "format.h": one in the same directory
        // as the importer, one in a different directory. Same-dir wins.
        let mut index = HashMap::new();
        index.insert("src/format.h".to_string(), "id-same".to_string());
        index.insert("include/fmt/format.h".to_string(), "id-other".to_string());

        let result = resolve_include_suffix("format.h", "src/main.cpp", &index);
        assert_eq!(result, Some("id-same".to_string()));
    }

    #[test]
    fn resolve_include_suffix_falls_back_to_other_directory() {
        // No same-directory match, only other-directory → same_dir.or(other)
        // returns the other match (line 347 `other` branch).
        let mut index = HashMap::new();
        index.insert("include/fmt/format.h".to_string(), "id-other".to_string());

        let result = resolve_include_suffix("format.h", "src/main.cpp", &index);
        assert_eq!(result, Some("id-other".to_string()));
    }

    #[test]
    fn resolve_include_suffix_returns_none_when_no_match() {
        // No file suffix-matches the include path → returns None.
        let mut index = HashMap::new();
        index.insert("src/utils.h".to_string(), "id-utils".to_string());

        let result = resolve_include_suffix("format.h", "src/main.cpp", &index);
        assert!(result.is_none());
    }

    #[test]
    fn resolve_include_suffix_exact_match_with_no_importer_directory() {
        // Exact match (prefix_len == 0) and importer_path has no '/' →
        // importer_dir = "", match_dir = "" → same_dir match.
        let mut index = HashMap::new();
        index.insert("format.h".to_string(), "id-exact".to_string());

        let result = resolve_include_suffix("format.h", "main.cpp", &index);
        assert_eq!(result, Some("id-exact".to_string()));
    }

    #[test]
    fn normalise_relative_dot_dot_from_root_pops_empty() {
        // `../b` from `a.ts` (root-level file): importer_dir is empty,
        // combined = "../b", segments.pop() on empty stack is a no-op.
        let n = normalise_relative("../b", "a.ts");
        assert_eq!(n, "b");
    }

    #[test]
    fn resolve_include_suffix_picks_shortest_other_dir() {
        // Multiple other-directory matches: shortest path wins (closest to root).
        let mut index = HashMap::new();
        index.insert("lib/fmt/format.h".to_string(), "id-short".to_string());
        index.insert("include/fmt/format.h".to_string(), "id-long".to_string());

        let result = resolve_include_suffix("format.h", "src/main.cpp", &index);
        assert_eq!(result, Some("id-short".to_string()));
    }

    #[test]
    fn strip_js_style_extension_strips_all_js_variants() {
        assert_eq!(strip_js_style_extension("src/a.js"), "src/a");
        assert_eq!(strip_js_style_extension("src/a.jsx"), "src/a");
        assert_eq!(strip_js_style_extension("src/a.mjs"), "src/a");
        assert_eq!(strip_js_style_extension("src/a.cjs"), "src/a");
    }
}