brokk-bifrost-python 0.15.1

Python language knowledge for brokk-bifrost: module identity, declarations, imports, and usage-graph resolution
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
//! Python import syntax, binding, and FQN resolution.
//!
//! Everything here is a free function over [`PythonSource`]; the
//! `ImportAnalysisProvider` impl that memoizes the per-file results stays on
//! `PythonAnalyzer` in `analyzer/python/imports.rs`.

use crate::bindings::python_direct_scope_bindings_bounded;
use crate::declarations::{parse_python_tree, py_node_text, python_module_name};
use crate::graph_support::{
    PythonSource, import_binder_from_imports, public_declarations_in_module,
    resolve_module_code_unit, resolve_module_code_units_batch,
};
use crate::runtime_values::enclosing_execution_context;
use crate::syntax::python_static_attribute_path;
use brokk_bifrost_core::analyzer::common::node_source_text;
use brokk_bifrost_core::analyzer::model::{
    ImportInfo, StructuredImportPath, StructuredImportPathKind,
};
use brokk_bifrost_core::analyzer::query_token::QueryToken;
use brokk_bifrost_core::analyzer::usages::model::{ExportEntry, ImportBinding, ImportKind};
use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, ProjectFile};
use brokk_bifrost_core::hash::{HashMap, HashSet};
use std::collections::VecDeque;
use tree_sitter::Node;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PythonModuleReplacement {
    pub target_module: String,
}

/// Return the absolute module named by the last direct assignment to `local`
/// that dominates `reference` when that assignment has the exact structured
/// shape `local = importlib_binding.import_module("module.name")`.
///
/// Assignments hidden in a branch do not dominate the reference. Any later
/// direct binding of `local` invalidates an earlier result. The caller proves
/// that the receiver of `import_module` is an in-scope namespace binding for
/// Python's `importlib` module; this helper only interprets the syntax and
/// statement order.
pub(crate) fn imported_module_assignment_at(
    reference: Node<'_>,
    local: &str,
    source: &str,
    mut is_importlib_binding: impl FnMut(&str) -> bool,
) -> Option<String> {
    let suite = enclosing_execution_suite(reference)?;
    let mut resolved = None;
    let mut cursor = suite.walk();
    for statement in suite.named_children(&mut cursor) {
        if statement.start_byte() >= reference.start_byte()
            || (statement.start_byte() <= reference.start_byte()
                && reference.end_byte() <= statement.end_byte())
        {
            break;
        }

        let expression = if statement.kind() == "expression_statement" {
            statement.named_child(0).unwrap_or(statement)
        } else {
            statement
        };
        if expression.kind() == "assignment"
            && expression.child_by_field_name("left").is_some_and(|left| {
                left.kind() == "identifier" && node_source_text(left, source) == local
            })
        {
            resolved = expression
                .child_by_field_name("right")
                .and_then(|right| importlib_call_module(right, source, &mut is_importlib_binding));
            continue;
        }

        let binds_local = python_direct_scope_bindings_bounded(statement, source, || true)
            .expect("unbounded binding collection cannot be cancelled")
            .into_iter()
            .any(|binding| node_source_text(binding.declaration, source) == local);
        if binds_local {
            resolved = None;
        }
    }
    resolved
}

/// Resolve a local name assigned a module object before `reference`.
///
/// The caller resolves imported module expressions from its structured import
/// binder. This helper follows only straight-line assignments in the current
/// function or module suite; branches and other direct rebinding statements
/// invalidate an earlier alias. Attribute paths are read from tree-sitter
/// nodes, never reconstructed from source text.
pub fn python_local_module_alias_path_before<E, C>(
    reference: Node<'_>,
    local_name: &str,
    source: &str,
    context: &mut C,
    mut imported_module_path: impl FnMut(Node<'_>, &mut C) -> Result<Option<Box<[Box<str>]>>, E>,
    mut charge_step: impl FnMut(&mut C) -> Result<(), E>,
) -> Result<Option<Box<[Box<str>]>>, E> {
    let mut current = reference;
    let suite = loop {
        let Some(parent) = current.parent() else {
            return Ok(None);
        };
        match parent.kind() {
            "function_definition" | "lambda" => break parent.child_by_field_name("body"),
            "module" => break Some(parent),
            "class_definition" => return Ok(None),
            _ => current = parent,
        }
    };
    let Some(suite) = suite else {
        return Ok(None);
    };

    let mut aliases: HashMap<Box<str>, Box<[Box<str>]>> = HashMap::default();
    let mut cursor = suite.walk();
    for statement in suite.named_children(&mut cursor) {
        if statement.start_byte() >= reference.start_byte()
            || (statement.start_byte() <= reference.start_byte()
                && reference.end_byte() <= statement.end_byte())
        {
            break;
        }
        charge_step(context)?;
        let expression = if statement.kind() == "expression_statement" {
            statement.named_child(0).unwrap_or(statement)
        } else {
            statement
        };
        if expression.kind() == "assignment" {
            let (targets, value) = python_assignment_chain(expression);
            if !targets.is_empty() && targets.iter().all(|target| target.kind() == "identifier") {
                let module_path = value
                    .map(|value| {
                        python_module_alias_expression_path(
                            value,
                            source,
                            &aliases,
                            context,
                            &mut imported_module_path,
                        )
                    })
                    .transpose()?
                    .flatten();
                for target in targets {
                    let name = node_source_text(target, source);
                    if let Some(module_path) = module_path.as_ref() {
                        aliases.insert(name.into(), module_path.clone());
                    } else {
                        aliases.remove(name);
                    }
                }
                continue;
            }
        }

        if !matches!(
            expression.kind(),
            "assignment"
                | "augmented_assignment"
                | "delete_statement"
                | "for_statement"
                | "async_for_statement"
                | "while_statement"
                | "with_statement"
                | "try_statement"
                | "match_statement"
                | "import_statement"
                | "import_from_statement"
                | "function_definition"
                | "class_definition"
                | "global_statement"
                | "nonlocal_statement"
                | "named_expression"
                | "if_statement"
        ) {
            continue;
        }
        let mut binding_error = None;
        let bindings =
            python_direct_scope_bindings_bounded(statement, source, || {
                match charge_step(context) {
                    Ok(()) => true,
                    Err(error) => {
                        binding_error = Some(error);
                        false
                    }
                }
            });
        if let Some(error) = binding_error {
            return Err(error);
        }
        let bindings = bindings.expect("bounded Python alias scan stopped without a cause");
        for binding in bindings {
            aliases.remove(node_source_text(binding.declaration, source));
        }
    }
    Ok(aliases.get(local_name).cloned())
}

fn python_module_alias_expression_path<E, C>(
    expression: Node<'_>,
    source: &str,
    aliases: &HashMap<Box<str>, Box<[Box<str>]>>,
    context: &mut C,
    imported_module_path: &mut impl FnMut(Node<'_>, &mut C) -> Result<Option<Box<[Box<str>]>>, E>,
) -> Result<Option<Box<[Box<str>]>>, E> {
    if let Some(path) = python_static_attribute_path(expression)
        && let Some(name) = path
            .first()
            .map(|segment| node_source_text(*segment, source))
        && let Some(module_path) = aliases.get(name)
    {
        let mut canonical = module_path.to_vec();
        canonical.extend(path.iter().skip(1).map(|segment| {
            node_source_text(*segment, source)
                .to_owned()
                .into_boxed_str()
        }));
        return Ok(Some(canonical.into_boxed_slice()));
    }
    imported_module_path(expression, context)
}

/// Flatten a right-recursive assignment into its targets and terminal value.
/// Targets are returned in runtime order, followed by the single evaluated
/// right-hand expression.
pub fn python_assignment_chain<'tree>(
    node: Node<'tree>,
) -> (Vec<Node<'tree>>, Option<Node<'tree>>) {
    let mut targets = Vec::new();
    let mut assignment = node;
    loop {
        let Some(target) = assignment.child_by_field_name("left") else {
            return (targets, None);
        };
        targets.push(target);
        let Some(value) = assignment.child_by_field_name("right") else {
            return (targets, None);
        };
        if value.kind() != "assignment" {
            return (targets, Some(value));
        }
        assignment = value;
    }
}

fn enclosing_execution_suite(node: Node<'_>) -> Option<Node<'_>> {
    if let Some(function) = enclosing_execution_context(node) {
        return function.child_by_field_name("body");
    }

    let mut current = node;
    while let Some(parent) = current.parent() {
        if parent.kind() == "class_definition" {
            return parent.child_by_field_name("body");
        }
        if parent.kind() == "module" {
            return Some(parent);
        }
        current = parent;
    }
    None
}

fn importlib_call_module(
    call: Node<'_>,
    source: &str,
    is_importlib_binding: &mut impl FnMut(&str) -> bool,
) -> Option<String> {
    if call.kind() != "call" {
        return None;
    }
    let function = call.child_by_field_name("function")?;
    if function.kind() != "attribute" {
        return None;
    }
    let (object, attribute) = (
        function.child_by_field_name("object")?,
        function.child_by_field_name("attribute")?,
    );
    if object.kind() != "identifier"
        || attribute.kind() != "identifier"
        || node_source_text(attribute, source) != "import_module"
        || !is_importlib_binding(node_source_text(object, source))
    {
        return None;
    }

    let arguments = call.child_by_field_name("arguments")?;
    if arguments.named_child_count() != 1 {
        return None;
    }
    let literal = arguments.named_child(0)?;
    if literal.kind() != "string"
        || literal
            .parent()
            .is_some_and(|parent| parent.kind() == "concatenated_string")
    {
        return None;
    }
    let mut content = None;
    for index in 0..literal.named_child_count() {
        let child = literal.named_child(index)?;
        match child.kind() {
            "string_start" | "string_end" => {}
            "string_content" if content.is_none() && child.named_child_count() == 0 => {
                content = Some(child);
            }
            _ => return None,
        }
    }
    let content = content?;
    let module = node_source_text(content, source);
    (!module.is_empty() && !module.starts_with('.')).then(|| module.to_string())
}

/// Collect absolute module names from structurally exact
/// `local = importlib.import_module("...")` assignments. This is a conservative
/// candidate-file index: dominance and local shadowing are checked later at the
/// reference site by [`imported_module_assignment_at`].
pub(crate) fn literal_importlib_modules(
    source: &str,
    bindings: &HashMap<String, ImportBinding>,
) -> HashSet<String> {
    let Some(tree) = parse_python_tree(source) else {
        return HashSet::default();
    };
    let mut modules = HashSet::default();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        if node.kind() == "assignment"
            && node
                .child_by_field_name("left")
                .is_some_and(|left| left.kind() == "identifier")
            && let Some(module) = node.child_by_field_name("right").and_then(|right| {
                importlib_call_module(right, source, &mut |local| {
                    bindings.get(local).is_some_and(|binding| {
                        binding.kind == ImportKind::Namespace
                            && binding
                                .namespace_imported_module
                                .as_deref()
                                .unwrap_or(&binding.module_specifier)
                                == "importlib"
                    })
                })
            })
        {
            modules.insert(module);
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    modules
}

/// Recognize the compatibility-shim idiom that replaces the current module
/// object with an imported workspace module:
///
/// `sys.modules[__name__] = imported_module`
///
/// Every component is resolved from tree-sitter fields and the import binder;
/// similarly spelled attributes or locals do not create an alias edge.
fn module_replacement_from_assignment(
    assignment: Node<'_>,
    source: &str,
    bindings: &HashMap<String, ImportBinding>,
) -> Option<PythonModuleReplacement> {
    let (left, right) = (
        assignment.child_by_field_name("left")?,
        assignment.child_by_field_name("right")?,
    );
    if left.kind() != "subscript" || right.kind() != "identifier" {
        return None;
    }
    let (value, subscript) = (
        left.child_by_field_name("value")?,
        left.child_by_field_name("subscript")?,
    );
    if value.kind() != "attribute"
        || subscript.kind() != "identifier"
        || node_source_text(subscript, source) != "__name__"
    {
        return None;
    }
    let (sys_local, modules) = (
        value.child_by_field_name("object")?,
        value.child_by_field_name("attribute")?,
    );
    if sys_local.kind() != "identifier"
        || modules.kind() != "identifier"
        || node_source_text(modules, source) != "modules"
    {
        return None;
    }
    let sys_binding = bindings.get(node_source_text(sys_local, source))?;
    let sys_module = sys_binding
        .namespace_imported_module
        .as_deref()
        .unwrap_or(&sys_binding.module_specifier);
    if sys_binding.kind != ImportKind::Namespace || sys_module != "sys" {
        return None;
    }

    let target_binding = bindings.get(node_source_text(right, source))?;
    if target_binding.kind != ImportKind::Namespace {
        return None;
    }
    Some(PythonModuleReplacement {
        target_module: target_binding
            .namespace_imported_module
            .clone()
            .unwrap_or_else(|| target_binding.module_specifier.clone()),
    })
}

fn remove_direct_scope_bindings(
    statement: Node<'_>,
    source: &str,
    bindings: &mut HashMap<String, ImportBinding>,
) {
    let mut stack = vec![statement];
    while let Some(node) = stack.pop() {
        for binding in python_direct_scope_bindings_bounded(node, source, || true)
            .expect("unbounded binding collection cannot be cancelled")
        {
            bindings.remove(node_source_text(binding.declaration, source));
        }
        if matches!(
            node.kind(),
            "function_definition" | "class_definition" | "lambda"
        ) {
            continue;
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
}

fn python_import_statement_nodes<'tree>(root: Node<'tree>) -> Vec<Node<'tree>> {
    let mut pending = vec![root];
    let mut nodes = Vec::new();
    while let Some(node) = pending.pop() {
        if matches!(node.kind(), "import_statement" | "import_from_statement") {
            nodes.push(node);
            continue;
        }
        let mut cursor = node.walk();
        pending.extend(node.named_children(&mut cursor));
    }
    nodes
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PythonImportBinding {
    pub start_byte: usize,
    pub scope_start_byte: usize,
    pub scope_end_byte: usize,
    function_scoped: bool,
    pub local_name: String,
    pub qualified_name: String,
    pub consumed_attributes: usize,
}

impl PythonImportBinding {
    pub fn is_function_scoped(&self) -> bool {
        self.function_scoped
    }
}

/// Select the latest visible function-scoped import binding for `name`.
pub fn python_function_scoped_import_binding<'a>(
    bindings: &'a [PythonImportBinding],
    name: &str,
    reference: Node<'_>,
) -> Option<&'a PythonImportBinding> {
    bindings.iter().rev().find(|binding| {
        binding.is_function_scoped()
            && binding.start_byte <= reference.start_byte()
            && binding.scope_start_byte <= reference.start_byte()
            && reference.end_byte() <= binding.scope_end_byte
            && binding.local_name == name
    })
}

/// Return structured import bindings from a tree the caller already owns.
/// Query paths use this form so one request never reparses a document merely
/// to recover function-local import scope.
pub fn python_import_bindings_from_tree(root: Node<'_>, source: &str) -> Vec<PythonImportBinding> {
    let mut nodes = python_import_statement_nodes(root);
    nodes.sort_by_key(Node::start_byte);
    nodes
        .into_iter()
        .flat_map(|node| {
            let (scope_start_byte, scope_end_byte, function_scoped) =
                python_import_binding_scope(node, source.len());
            python_import_infos_from_node(node, source)
                .into_iter()
                .filter_map(move |import| {
                    let path = import.path.as_ref()?;
                    let details = python_import_details(&import)?;
                    match details {
                        PythonImportDetails::Import { module, alias } => {
                            let consumed_attributes = if alias.is_some() {
                                0
                            } else {
                                path.segments.len().saturating_sub(1)
                            };
                            Some(PythonImportBinding {
                                start_byte: node.start_byte(),
                                scope_start_byte,
                                scope_end_byte,
                                function_scoped,
                                local_name: import.identifier.clone()?,
                                qualified_name: module,
                                consumed_attributes,
                            })
                        }
                        PythonImportDetails::FromImport {
                            module,
                            name,
                            alias: _,
                            wildcard: false,
                        } => Some(PythonImportBinding {
                            start_byte: node.start_byte(),
                            scope_start_byte,
                            scope_end_byte,
                            function_scoped,
                            local_name: import.identifier.clone()?,
                            qualified_name: format!("{module}.{name}"),
                            consumed_attributes: 0,
                        }),
                        PythonImportDetails::FromImport { wildcard: true, .. } => None,
                    }
                })
        })
        .collect()
}

/// Build import bindings from the canonical generic import projection.
///
/// The producer has already interpreted each path and retained lexical scope
/// byte ranges in the import facts. This adapter only maps those ranges back
/// to the caller's prepared tree to recover the nearest function or lambda
/// scope; it never reparses source or reconstructs import syntax.
pub fn python_import_bindings_from_imports(
    imports: &[ImportInfo],
    root: Node<'_>,
    source_len: usize,
) -> Vec<PythonImportBinding> {
    python_import_bindings_from_imports_bounded(imports, root, source_len, || true)
        .expect("unbounded import projection completes")
}

/// Project canonical import facts under the caller's own sticky traversal
/// budget. A stopped projection is distinct from a complete empty inventory.
pub fn python_import_bindings_from_imports_bounded(
    imports: &[ImportInfo],
    root: Node<'_>,
    source_len: usize,
    mut scope_step: impl FnMut() -> bool,
) -> Option<Vec<PythonImportBinding>> {
    let mut bindings = Vec::new();
    for import in imports {
        if !scope_step() {
            return None;
        }
        let Some(path) = import.path.as_ref() else {
            continue;
        };
        for _segment in &path.segments {
            if !scope_step() {
                return None;
            }
        }
        let Some(details) = python_import_details(import) else {
            continue;
        };
        let mut binding_scope = None;
        let mut valid = true;
        for scope in path.lexical_scopes.iter().rev() {
            if !scope_step() {
                return None;
            }
            let Some(node) = root.descendant_for_byte_range(scope.start_byte, scope.end_byte)
            else {
                valid = false;
                break;
            };
            if node.start_byte() != scope.start_byte || node.end_byte() != scope.end_byte {
                valid = false;
                break;
            }
            if matches!(node.kind(), "function_definition" | "lambda") {
                binding_scope = Some((scope.start_byte, scope.end_byte, true));
                break;
            }
        }
        if !valid {
            continue;
        }
        let (scope_start_byte, scope_end_byte, function_scoped) =
            binding_scope.unwrap_or((0, source_len, false));
        let Some(local_name) = import.identifier.clone() else {
            continue;
        };
        let (qualified_name, consumed_attributes) = match details {
            PythonImportDetails::Import { module, alias } => (
                module,
                if alias.is_some() {
                    0
                } else {
                    path.segments.len().saturating_sub(1)
                },
            ),
            PythonImportDetails::FromImport {
                module,
                name,
                wildcard: false,
                ..
            } => (format!("{module}.{name}"), 0),
            PythonImportDetails::FromImport { wildcard: true, .. } => continue,
        };
        bindings.push(PythonImportBinding {
            start_byte: path.declaration_start_byte,
            scope_start_byte,
            scope_end_byte,
            function_scoped,
            local_name,
            qualified_name,
            consumed_attributes,
        });
    }
    bindings.sort_by_key(|binding| binding.start_byte);
    Some(bindings)
}

fn python_import_binding_scope(node: Node<'_>, source_len: usize) -> (usize, usize, bool) {
    let mut parent = node.parent();
    while let Some(scope) = parent {
        if matches!(scope.kind(), "function_definition" | "lambda") {
            return (scope.start_byte(), scope.end_byte(), true);
        }
        parent = scope.parent();
    }
    (0, source_len, false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use brokk_bifrost_core::analyzer::usages::model::ImportBinder;
    use brokk_bifrost_test_macros::hardwon;

    fn importlib_assignment_for(source: &str, importlib_local: &str) -> Option<String> {
        let tree = parse_python_tree(source).expect("valid Python fixture");
        let reference_start = source.rfind("canonical.setup").expect("reference site");
        let mut stack = vec![tree.root_node()];
        let mut reference = None;
        while let Some(node) = stack.pop() {
            if node.kind() == "identifier"
                && node.start_byte() == reference_start
                && node_source_text(node, source) == "canonical"
            {
                reference = Some(node);
                break;
            }
            let mut cursor = node.walk();
            stack.extend(node.named_children(&mut cursor));
        }
        imported_module_assignment_at(
            reference.expect("canonical reference node"),
            "canonical",
            source,
            |local| local == importlib_local,
        )
    }

    #[test]
    fn importlib_assignment_requires_a_direct_literal_dominating_write() {
        let valid = r#"import importlib as loader

def test():
    canonical = loader.import_module("routes.contacts.contacts_routes")
    assert canonical.setup_contacts_routes
"#;
        assert_eq!(
            importlib_assignment_for(valid, "loader"),
            Some("routes.contacts.contacts_routes".to_string())
        );

        for near_miss in [
            r#"import importlib as loader
def test(module_name):
    canonical = loader.import_module(module_name)
    assert canonical.setup_contacts_routes
"#,
            r#"import importlib as loader
def test():
    if enabled:
        canonical = loader.import_module("routes.contacts.contacts_routes")
    assert canonical.setup_contacts_routes
"#,
            r#"import importlib as loader
def test():
    canonical = loader.import_module("routes.contacts.contacts_routes")
    canonical = object()
    assert canonical.setup_contacts_routes
"#,
        ] {
            assert_eq!(
                importlib_assignment_for(near_miss, "loader"),
                None,
                "near miss must not infer a module receiver: {near_miss:?}"
            );
        }
        assert_eq!(
            importlib_assignment_for(valid, "shadowed_loader"),
            None,
            "a similarly shaped non-importlib receiver must not resolve"
        );
    }

    fn replacement_for(source: &str, binder: &ImportBinder) -> Option<PythonModuleReplacement> {
        let tree = parse_python_tree(source).expect("valid Python fixture");
        let root = tree.root_node();
        let mut replacement = None;
        let mut cursor = root.walk();
        for statement in root.named_children(&mut cursor) {
            let statement = if statement.kind() == "expression_statement" {
                statement.named_child(0).expect("fixture expression")
            } else {
                statement
            };
            if statement.kind() == "assignment"
                && let Some(next) =
                    module_replacement_from_assignment(statement, source, &binder.bindings)
                && replacement.replace(next).is_some()
            {
                return None;
            }
        }
        replacement
    }

    #[test]
    #[hardwon("59dfb80c3bb8: module replacement accepted malformed or shadowed import shapes")]
    fn module_replacement_requires_exact_structured_import_bindings() {
        let source = r#"import sys as _sys
from routes.contacts import contacts_routes as _canonical

_sys.modules[__name__] = _canonical
"#;
        let mut binder = ImportBinder::empty();
        binder.bindings.insert(
            "_sys".to_string(),
            ImportBinding {
                module_specifier: "sys".to_string(),
                namespace_imported_module: Some("sys".to_string()),
                kind: ImportKind::Namespace,
                imported_name: None,
            },
        );
        binder.bindings.insert(
            "_canonical".to_string(),
            ImportBinding {
                module_specifier: "routes.contacts.contacts_routes".to_string(),
                namespace_imported_module: None,
                kind: ImportKind::Namespace,
                imported_name: None,
            },
        );

        assert_eq!(
            replacement_for(source, &binder),
            Some(PythonModuleReplacement {
                target_module: "routes.contacts.contacts_routes".to_string(),
            })
        );

        for near_miss in [
            "cache.modules[__name__] = _canonical\n",
            "_sys.modules[module_name] = _canonical\n",
            "_sys.modules[__name__] = build()\n",
            "def replace():\n    _sys.modules[__name__] = _canonical\n",
        ] {
            assert_eq!(
                replacement_for(near_miss, &binder),
                None,
                "near miss must not replace module identity: {near_miss:?}"
            );
        }
    }

    #[test]
    #[hardwon(
        "b58235b247fd: Python import bindings lost function scope or relative module identity"
    )]
    fn existing_tree_import_bindings_preserve_function_scope_and_relative_identity() {
        let source = r#"def register():
    from .workers.special import Worker
    return Worker()
"#;
        let tree = parse_python_tree(source).expect("Python tree");
        let bindings = python_import_bindings_from_tree(tree.root_node(), source);

        assert_eq!(bindings.len(), 1, "{bindings:#?}");
        assert!(bindings[0].is_function_scoped(), "{bindings:#?}");
        assert_eq!(bindings[0].local_name, "Worker");
        assert_eq!(bindings[0].qualified_name, ".workers.special.Worker");
        assert!(bindings[0].scope_start_byte <= bindings[0].start_byte);
        assert!(bindings[0].scope_end_byte >= source.rfind("Worker()").unwrap());
    }
}

/// Borrow each statement's contiguous canonical leaves without reinterpreting
/// target or alias syntax in executable binding timelines.
pub(crate) fn python_imports_by_statement(imports: &[ImportInfo]) -> HashMap<usize, &[ImportInfo]> {
    let mut statement_imports = HashMap::default();
    for group in imports.chunk_by(|left, right| {
        left.path.as_ref().map(|path| path.declaration_start_byte)
            == right.path.as_ref().map(|path| path.declaration_start_byte)
    }) {
        if let Some(path) = &group[0].path {
            assert!(
                statement_imports
                    .insert(path.declaration_start_byte, group)
                    .is_none(),
                "canonical Python import leaves must remain in statement order"
            );
        }
    }
    statement_imports
}

pub fn module_replacement_of(
    python: &dyn PythonSource,
    file: &ProjectFile,
    source: &str,
    imports: &[ImportInfo],
) -> Option<PythonModuleReplacement> {
    let tree = parse_python_tree(source)?;
    let root = tree.root_node();
    let mut bindings: HashMap<String, ImportBinding> = HashMap::default();
    let statement_imports = python_imports_by_statement(imports);
    let mut replacement = None;
    let mut cursor = root.walk();
    for statement in root.named_children(&mut cursor) {
        let statement = if statement.kind() == "expression_statement" {
            let Some(expression) = statement.named_child(0) else {
                continue;
            };
            expression
        } else {
            statement
        };
        match statement.kind() {
            "import_statement" | "import_from_statement" => {
                if let Some(imports) = statement_imports.get(&statement.start_byte()) {
                    bindings.extend(import_binder_from_imports(python, file, imports).bindings);
                }
            }
            "assignment" => {
                if let Some(next) = module_replacement_from_assignment(statement, source, &bindings)
                    && replacement.replace(next).is_some()
                {
                    return None;
                }
                remove_direct_scope_bindings(statement, source, &mut bindings);
            }
            _ => remove_direct_scope_bindings(statement, source, &mut bindings),
        }
    }
    replacement
}

pub fn resolve_import_bindings(
    python: &dyn PythonSource,
    token: QueryToken<'_>,
    file: &ProjectFile,
) -> HashMap<String, CodeUnit> {
    let imports = python.import_info_of(token, file);
    let mut bindings = HashMap::default();
    for resolved in resolve_imports_batched(python, file, &imports) {
        for (binding, code_unit) in resolved {
            bindings.insert(binding, code_unit);
        }
    }
    bindings
}

/// Resolves every import in `imports` (`file`'s own imports), batching each import's primary
/// module FQN lookup (see `primary_module_fqn`) into one store transaction instead of one per
/// import. Shared by `resolve_import_bindings` and `resolve_import_target_files`, the two per-file
/// "resolve everything" entry points -- both are called once per candidate file by the usages
/// candidate walker, so unbatched resolution here means one store transaction per import times
/// every file in the workspace.
pub fn resolve_imports_batched(
    python: &dyn PythonSource,
    file: &ProjectFile,
    imports: &[ImportInfo],
) -> Vec<Vec<(String, CodeUnit)>> {
    let primary_fqns: Vec<Option<String>> = imports
        .iter()
        .map(|import| primary_module_fqn(python, file, import))
        .collect();
    let to_resolve: Vec<String> = primary_fqns.iter().flatten().cloned().collect();
    let mut batch_results =
        resolve_module_code_units_batch(python, Some(file), &to_resolve).into_iter();

    imports
        .iter()
        .zip(primary_fqns.iter())
        .map(|(import, primary_fqn)| {
            let hint = primary_fqn.as_ref().map(|_| batch_results.next().unwrap());
            resolve_import_with_hint(python, file, import, hint.as_ref())
        })
        .collect()
}

/// Resolve Python imports to the workspace files whose modules they execute.
///
/// A file dependency graph does not need declaration binding: for
/// `from pkg import member`, the dependency on `pkg` exists whether `member`
/// is a local declaration, a re-export, or an optional external name. When
/// `member` is itself the workspace submodule `pkg.member`, that file is a
/// dependency too. Resolve both module spellings from the path-backed module
/// index in one batch and deliberately avoid the exact-definition fallbacks
/// used by [`resolve_imports_batched`].
pub fn resolve_import_files_batched(
    python: &dyn PythonSource,
    file: &ProjectFile,
    imports: &[ImportInfo],
) -> HashSet<ProjectFile> {
    let mut module_fqns = Vec::new();
    for import in imports {
        match python_import_details(import) {
            Some(PythonImportDetails::Import { module, .. }) => module_fqns.push(module),
            Some(PythonImportDetails::FromImport {
                module,
                name,
                wildcard,
                ..
            }) => {
                let resolved_module = if module.starts_with('.') {
                    resolve_python_relative_module(python.project(), file, &module)
                } else {
                    Some(module)
                };
                let Some(resolved_module) = resolved_module else {
                    continue;
                };
                if !wildcard {
                    module_fqns.push(format!("{resolved_module}.{name}"));
                }
                module_fqns.push(resolved_module);
            }
            None => {}
        }
    }
    module_fqns.sort();
    module_fqns.dedup();

    python
        .path_module_fqns_batch(&module_fqns)
        .into_iter()
        .flatten()
        .flatten()
        .filter(CodeUnit::is_module)
        .map(|unit| unit.source().clone())
        .collect()
}

/// The module FQN fast path checks first, if any -- must stay in sync with the
/// two `resolve_module_code_unit` call sites in `resolve_import_with_hint` below, since it's what
/// lets `resolve_import_target_files` batch-resolve them ahead of the serial fallback logic.
fn primary_module_fqn(
    python: &dyn PythonSource,
    file: &ProjectFile,
    import: &ImportInfo,
) -> Option<String> {
    match python_import_details(import)? {
        PythonImportDetails::Import { module, alias } => Some(python_namespace_binding_module(
            import,
            alias.as_deref(),
            &module,
        )),
        PythonImportDetails::FromImport {
            module,
            name,
            wildcard,
            ..
        } => {
            if wildcard {
                return None;
            }
            let resolved_module = resolve_python_module_specifier(python.project(), file, &module);
            resolved_module.map(|resolved_module| format!("{resolved_module}.{name}"))
        }
    }
}

/// `primary_hint`, when `Some`, is the already-resolved result of this import's primary module FQN
/// (see `primary_module_fqn`) so the batched caller doesn't pay for a second lookup of the same FQN.
fn resolve_import_with_hint(
    python: &dyn PythonSource,
    file: &ProjectFile,
    import: &ImportInfo,
    primary_hint: Option<&Option<CodeUnit>>,
) -> Vec<(String, CodeUnit)> {
    if let Some(details) = python_import_details(import) {
        match details {
            PythonImportDetails::Import { module, alias } => {
                let binding = python_namespace_binding_name(import, alias.as_deref(), &module);
                let bound_module =
                    python_namespace_binding_module(import, alias.as_deref(), &module);
                let resolved = match primary_hint {
                    Some(hint) => hint.clone(),
                    None => resolve_module_code_unit(python, Some(file), &bound_module),
                };
                if let Some(module_code_unit) = resolved {
                    return vec![(binding, module_code_unit)];
                }
            }
            PythonImportDetails::FromImport {
                module,
                name,
                alias,
                wildcard,
            } => {
                let resolved_module =
                    resolve_python_module_specifier(python.project(), file, &module);
                let Some(resolved_module) = resolved_module else {
                    return Vec::new();
                };
                if wildcard {
                    return public_declarations_in_module(python, file, &resolved_module)
                        .into_iter()
                        .map(|code_unit| (code_unit.identifier().to_string(), code_unit))
                        .collect();
                }

                let binding = alias.clone().unwrap_or_else(|| name.clone());
                let module_candidate = format!("{resolved_module}.{name}");
                let exported =
                    resolve_exported_name_from_module(python, Some(file), &resolved_module, &name);
                if !exported.is_empty() {
                    return exported
                        .into_iter()
                        .map(|code_unit| (binding.clone(), code_unit))
                        .collect();
                }
                let resolved = match primary_hint {
                    Some(hint) => hint.clone(),
                    None => resolve_module_code_unit(python, Some(file), &module_candidate),
                };
                if let Some(code_unit) = resolved {
                    return vec![(binding, code_unit)];
                }
                let definitions: Vec<_> = python.definitions(&module_candidate).collect();
                if !definitions.is_empty() {
                    return definitions
                        .into_iter()
                        .map(|code_unit| (binding.clone(), code_unit))
                        .collect();
                }
                let package_candidate: Vec<_> = python
                    .definitions(&format!("{resolved_module}.{name}"))
                    .collect();
                if !package_candidate.is_empty() {
                    return package_candidate
                        .into_iter()
                        .map(|code_unit| (binding.clone(), code_unit))
                        .collect();
                }
            }
        }
    }
    Vec::new()
}

/// `importer`, when known, is the file whose import statement asked for `fqn`;
/// its own import root is what decides between two same-named modules. `None`
/// is for an FQN-level question no import statement asked.
pub fn resolve_exported_fqn(
    python: &dyn PythonSource,
    importer: Option<&ProjectFile>,
    fqn: &str,
) -> Vec<CodeUnit> {
    let Some((module, name)) = fqn.rsplit_once('.') else {
        return Vec::new();
    };
    resolve_exported_name_from_module(python, importer, module, name)
}

/// Resolve an unambiguous chain of explicit named reexports without
/// constructing export indexes for each intermediate module. Star exports,
/// shadowing, and every other ambiguous shape return `None` so callers can
/// use the complete, source-order-aware export resolver below.
///
/// Each hop carries its own importer: the first is the file that asked, and
/// every later one is the module whose reexport named the next specifier, so
/// a facade chain stays inside the roots that actually wrote it.
fn resolve_direct_named_exported_fqn(
    python: &dyn PythonSource,
    importer: Option<&ProjectFile>,
    fqn: &str,
) -> Option<Vec<CodeUnit>> {
    let (module, name) = fqn.rsplit_once('.')?;
    let mut results = Vec::new();
    let mut queue = VecDeque::from([(importer.cloned(), module.to_string(), name.to_string())]);
    let mut visited = HashSet::default();

    while let Some((importer, module, export_name)) = queue.pop_front() {
        if !visited.insert((module.clone(), export_name.clone())) {
            continue;
        }
        let module_unit = resolve_module_code_unit(python, importer.as_ref(), &module)?;
        let file = module_unit.source();
        let local = local_export_declarations(python, file, &export_name);
        let binder = python.import_binder_of(file);
        let binding = binder.bindings.get(&export_name);
        if !local.is_empty() && binding.is_some() {
            return None;
        }
        if !local.is_empty() {
            results.extend(local);
            continue;
        }
        let binding = binding?;
        if binding.kind != ImportKind::Named {
            return None;
        }
        let imported_name = binding.imported_name.as_ref()?;
        queue.push_back((
            Some(file.clone()),
            binding.module_specifier.clone(),
            imported_name.clone(),
        ));
    }

    results.sort_by(|left, right| {
        left.source()
            .cmp(right.source())
            .then_with(|| left.fq_name().cmp(&right.fq_name()))
    });
    results.dedup();
    (!results.is_empty()).then_some(results)
}

/// Resolve a Python FQN with the cheapest semantically complete tier that
/// can answer it. The direct reexport walk handles only proven,
/// collision-free chains; ambiguous shapes use the ordered export index,
/// and the exact lookup remains the final fallback for non-export symbols.
///
/// The first two tiers resolve a module specifier, so they take `importer`
/// for the same reason the import resolver does. The exact lookup is a
/// workspace-wide question about a dotted name and stays root-blind.
pub fn resolve_fqn_candidates(
    python: &dyn PythonSource,
    importer: Option<&ProjectFile>,
    fqn: &str,
    exact: impl FnOnce(&str) -> Vec<CodeUnit>,
) -> Vec<CodeUnit> {
    if let Some(candidates) = resolve_direct_named_exported_fqn(python, importer, fqn) {
        return candidates;
    }
    let candidates = resolve_exported_fqn(python, importer, fqn);
    if !candidates.is_empty() {
        return candidates;
    }
    exact(fqn)
}

fn resolve_exported_name_from_module(
    python: &dyn PythonSource,
    importer: Option<&ProjectFile>,
    module: &str,
    name: &str,
) -> Vec<CodeUnit> {
    let Some(module_unit) = resolve_module_code_unit(python, importer, module) else {
        return Vec::new();
    };
    resolve_exported_name(python, module_unit.source(), name)
}

fn resolve_exported_name(
    python: &dyn PythonSource,
    module_file: &ProjectFile,
    name: &str,
) -> Vec<CodeUnit> {
    let mut results = Vec::new();
    let mut queue = VecDeque::from([(module_file.clone(), name.to_string())]);
    let mut visited = HashSet::default();

    while let Some((file, export_name)) = queue.pop_front() {
        if !visited.insert((file.clone(), export_name.clone())) {
            continue;
        }

        let index = python.export_index_of(&file);
        if let Some(entry) = index.exports_by_name.get(&export_name) {
            match entry {
                ExportEntry::Local { local_name } => {
                    results.extend(local_export_declarations(python, &file, local_name));
                }
                ExportEntry::ReexportedNamed {
                    module_specifier,
                    imported_name,
                } => {
                    for target_file in
                        resolve_module_files_for_export(python, &file, module_specifier)
                    {
                        queue.push_back((target_file, imported_name.clone()));
                    }
                }
                ExportEntry::ReexportedModule { module_specifier } => {
                    // Terminal: the export *is* the module, so the walk stops
                    // here instead of looking the name up inside it.
                    results.extend(resolve_module_code_unit(
                        python,
                        Some(&file),
                        module_specifier,
                    ));
                }
                ExportEntry::Default { local_name } => {
                    if let Some(local_name) = local_name {
                        results.extend(local_export_declarations(python, &file, local_name));
                    }
                }
            }
            continue;
        }

        if !export_name.starts_with('_') {
            for star in &index.reexport_stars {
                for target_file in
                    resolve_module_files_for_export(python, &file, &star.module_specifier)
                {
                    queue.push_back((target_file, export_name.clone()));
                }
            }
        }
    }

    results.sort_by(|left, right| {
        left.source()
            .cmp(right.source())
            .then_with(|| left.fq_name().cmp(&right.fq_name()))
    });
    results.dedup();
    results
}

fn local_export_declarations(
    index: &dyn CodeUnitIndex,
    file: &ProjectFile,
    local_name: &str,
) -> Vec<CodeUnit> {
    index
        .top_level_declarations(file)
        .into_iter()
        .filter(|unit| {
            unit.identifier() == local_name
                && index
                    .parent_of(unit)
                    .is_some_and(|parent| parent.is_module() && parent.source() == file)
        })
        .collect()
}

fn resolve_module_files_for_export(
    python: &dyn PythonSource,
    importing_file: &ProjectFile,
    module_specifier: &str,
) -> Vec<ProjectFile> {
    let resolved_module =
        resolve_python_module_specifier(python.project(), importing_file, module_specifier);
    let Some(resolved_module) = resolved_module else {
        return Vec::new();
    };
    // Tree-sitter tells us the import syntax, but module-to-file resolution
    // is analyzer state. Use the prebuilt module code-unit map here instead
    // of the usage index so interactive definition lookup stays lightweight.
    resolve_module_code_unit(python, Some(importing_file), &resolved_module)
        .map(|unit| vec![unit.source().clone()])
        .unwrap_or_default()
}

pub fn extract_package_from_python_wildcard(import: &ImportInfo) -> Option<String> {
    let details = python_import_details(import)?;
    match details {
        PythonImportDetails::FromImport {
            module, wildcard, ..
        } if wildcard => Some(module),
        _ => None,
    }
}

#[derive(Debug, Clone)]
pub enum PythonImportDetails {
    Import {
        module: String,
        alias: Option<String>,
    },
    FromImport {
        module: String,
        name: String,
        alias: Option<String>,
        wildcard: bool,
    },
}

/// One import leaf interpreted directly from the Python AST.
///
/// The generic [`ImportInfo`] remains the display/query projection. The
/// source nodes are retained beside it so the coordinated primary producer can
/// intern declaration, binder, and alias occurrences without matching names or
/// byte ranges after the tree has been walked.
#[derive(Debug, Clone)]
pub struct PythonImportSyntax<'tree> {
    pub info: ImportInfo,
    pub module: Node<'tree>,
    pub member: Option<Node<'tree>>,
    pub leaf: Node<'tree>,
    pub declaration: Node<'tree>,
    pub target: Option<Node<'tree>>,
    pub alias: Option<Node<'tree>>,
}

pub fn python_import_infos_from_node(node: Node<'_>, source: &str) -> Vec<ImportInfo> {
    python_import_syntaxes_from_node(node, source)
        .into_iter()
        .map(|syntax| syntax.info)
        .collect()
}

/// Interpret every import leaf in one statement and retain its exact AST
/// binder nodes. Malformed leaves are omitted with the same admission rules as
/// the historical generic import projection.
pub fn python_import_syntaxes_from_node<'tree>(
    node: Node<'tree>,
    source: &str,
) -> Vec<PythonImportSyntax<'tree>> {
    match node.kind() {
        "import_statement" => python_namespace_import_syntaxes(node, source),
        "import_from_statement" => python_from_import_syntaxes(node, source),
        _ => Vec::new(),
    }
}

pub fn python_import_details(import: &ImportInfo) -> Option<PythonImportDetails> {
    let path = import.path.as_ref()?;
    match path.kind? {
        StructuredImportPathKind::Namespace => Some(PythonImportDetails::Import {
            module: join_python_import_segments(&path.segments),
            alias: import.alias.clone(),
        }),
        // These declaration forms belong to Java and Rust, not Python.
        StructuredImportPathKind::StaticMember | StructuredImportPathKind::ExternCrate => None,
        // PHP include kinds are not Python import statements.
        StructuredImportPathKind::FileInclude | StructuredImportPathKind::DynamicInclude => None,
        StructuredImportPathKind::ImportFrom => {
            let (name, module_segments) = if import.is_wildcard {
                ("*".to_string(), path.segments.as_slice())
            } else {
                let (name, module_segments) = path.segments.split_last()?;
                (name.clone(), module_segments)
            };
            Some(PythonImportDetails::FromImport {
                module: join_python_import_segments(module_segments),
                name,
                alias: import.alias.clone(),
                wildcard: import.is_wildcard,
            })
        }
    }
}

fn python_namespace_import_syntaxes<'tree>(
    node: Node<'tree>,
    source: &str,
) -> Vec<PythonImportSyntax<'tree>> {
    let mut infos = Vec::new();
    let mut cursor = node.walk();
    for imported in node.children_by_field_name("name", &mut cursor) {
        let (module_node, alias_node) = if imported.kind() == "aliased_import" {
            let Some(name) = imported.child_by_field_name("name") else {
                continue;
            };
            (name, imported.child_by_field_name("alias"))
        } else {
            (imported, None)
        };
        let alias = alias_node
            .map(|alias| py_node_text(alias, source).trim().to_string())
            .filter(|alias| !alias.is_empty());
        let segments = python_path_segments(module_node, source);
        if segments.is_empty() {
            continue;
        }
        // `import a.b` binds `a`: the first segment's own token. A renamed
        // import binds its alias token instead.
        let target = alias
            .is_none()
            .then(|| python_first_segment_node(module_node))
            .flatten();
        let binder_span = alias_node
            .or(target)
            .map(brokk_bifrost_core::analyzer::common::node_span);
        let module = join_python_import_segments(&segments);
        let identifier = alias.clone().or_else(|| segments.first().cloned());
        let info = ImportInfo {
            raw_snippet: if let Some(alias) = &alias {
                format!("import {module} as {alias}")
            } else {
                format!("import {module}")
            },
            is_wildcard: false,
            is_global: false,
            identifier,
            alias,
            path: Some(StructuredImportPath {
                segments,
                kind: Some(StructuredImportPathKind::Namespace),
                lexical_prefixes: Vec::new(),
                lexical_scopes: Vec::new(),
                declaration_start_byte: node.start_byte(),
            }),
            binder_span,
        };
        infos.push(PythonImportSyntax {
            info,
            module: module_node,
            member: None,
            leaf: imported,
            declaration: node,
            target,
            alias: alias_node,
        });
    }
    infos
}

fn python_from_import_syntaxes<'tree>(
    node: Node<'tree>,
    source: &str,
) -> Vec<PythonImportSyntax<'tree>> {
    let Some(module_node) = node.child_by_field_name("module_name") else {
        return Vec::new();
    };
    let module_segments = python_module_segments(module_node, source);
    if module_segments.is_empty() {
        return Vec::new();
    }

    let mut infos = Vec::new();
    let has_wildcard_import = {
        let mut cursor = node.walk();
        node.named_children(&mut cursor)
            .any(|child| child.kind() == "wildcard_import")
    };
    let mut cursor = node.walk();
    let imported_names: Vec<_> = node.children_by_field_name("name", &mut cursor).collect();
    if has_wildcard_import {
        let module = join_python_import_segments(&module_segments);
        let info = ImportInfo {
            raw_snippet: format!("from {module} import *"),
            is_wildcard: true,
            is_global: false,
            identifier: None,
            alias: None,
            path: Some(StructuredImportPath {
                segments: module_segments,
                kind: Some(StructuredImportPathKind::ImportFrom),
                lexical_prefixes: Vec::new(),
                lexical_scopes: Vec::new(),
                declaration_start_byte: node.start_byte(),
            }),
            binder_span: None,
        };
        infos.push(PythonImportSyntax {
            info,
            module: module_node,
            member: None,
            leaf: node,
            declaration: node,
            target: None,
            alias: None,
        });
        return infos;
    }
    if imported_names.is_empty() {
        return infos;
    }

    for imported in imported_names {
        let (name_node, alias_node) = if imported.kind() == "aliased_import" {
            let Some(name) = imported.child_by_field_name("name") else {
                continue;
            };
            (name, imported.child_by_field_name("alias"))
        } else {
            (imported, None)
        };
        let alias = alias_node
            .map(|alias| py_node_text(alias, source).trim().to_string())
            .filter(|alias| !alias.is_empty());
        let name_segments = python_path_segments(name_node, source);
        if name_segments.is_empty() {
            continue;
        }
        // `from m import x` binds `x`'s own token; a rename binds the alias
        // token. A multi-segment imported name binds no single token.
        let target = alias
            .is_none()
            .then(|| {
                (name_segments.len() == 1)
                    .then(|| python_first_segment_node(name_node))
                    .flatten()
            })
            .flatten();
        let binder_span = alias_node
            .or(target)
            .map(brokk_bifrost_core::analyzer::common::node_span);
        let imported_name = join_python_import_segments(&name_segments);
        let mut segments = module_segments.clone();
        segments.extend(name_segments);
        let module = join_python_import_segments(&module_segments);
        let info = ImportInfo {
            raw_snippet: if let Some(alias) = &alias {
                format!("from {module} import {imported_name} as {alias}")
            } else {
                format!("from {module} import {imported_name}")
            },
            is_wildcard: false,
            is_global: false,
            identifier: Some(alias.clone().unwrap_or_else(|| imported_name.clone())),
            alias,
            path: Some(StructuredImportPath {
                segments,
                kind: Some(StructuredImportPathKind::ImportFrom),
                lexical_prefixes: Vec::new(),
                lexical_scopes: Vec::new(),
                declaration_start_byte: node.start_byte(),
            }),
            binder_span,
        };
        infos.push(PythonImportSyntax {
            info,
            module: module_node,
            member: Some(name_node),
            leaf: imported,
            declaration: node,
            target,
            alias: alias_node,
        });
    }
    infos
}

fn python_module_segments(module: Node<'_>, source: &str) -> Vec<String> {
    if module.kind() == "relative_import" {
        let mut cursor = module.walk();
        let mut prefix = String::new();
        let mut path_node = None;
        for child in module.named_children(&mut cursor) {
            match child.kind() {
                "import_prefix" if prefix.is_empty() => {
                    prefix = py_node_text(child, source).trim().to_string();
                }
                "dotted_name" if path_node.is_none() => {
                    path_node = Some(child);
                }
                _ => {}
            }
        }
        let mut segments = path_node
            .map(|path| python_path_segments(path, source))
            .unwrap_or_default();
        if !prefix.is_empty() {
            if let Some(first) = segments.first_mut() {
                first.insert_str(0, &prefix);
            } else {
                segments.push(prefix);
            }
        }
        return segments;
    }
    python_path_segments(module, source)
}

/// The token that spells a path's first segment: the identifier itself, or a
/// dotted name's first identifier. `None` when the shape has no leading
/// identifier token of its own (e.g. a relative-import prefix).
fn python_first_segment_node(node: Node<'_>) -> Option<Node<'_>> {
    match node.kind() {
        "identifier" => Some(node),
        "dotted_name" => {
            let mut cursor = node.walk();
            node.named_children(&mut cursor)
                .find(|child| child.kind() == "identifier")
        }
        _ => None,
    }
}

/// Identifier components selected from an import path AST, in source order.
/// Relative punctuation is deliberately not a name component.
pub(crate) fn python_import_identifier_nodes(node: Node<'_>) -> Vec<Node<'_>> {
    use brokk_bifrost_core::analyzer::tree_walk::{WalkControl, walk_named_tree_preorder};
    let mut segments = Vec::new();
    walk_named_tree_preorder(node, true, |node| {
        if node.kind() == "identifier" {
            segments.push(node);
        }
        WalkControl::Continue
    });
    segments
}

fn python_path_segments(node: Node<'_>, source: &str) -> Vec<String> {
    python_import_identifier_nodes(node)
        .into_iter()
        .map(|node| py_node_text(node, source).trim().to_string())
        .collect()
}

fn join_python_import_segments(segments: &[String]) -> String {
    let Some((first, rest)) = segments.split_first() else {
        return String::new();
    };
    if first.starts_with('.') && !rest.is_empty() {
        format!("{first}.{}", rest.join("."))
    } else {
        segments.join(".")
    }
}

pub fn python_namespace_binding_name(
    import: &ImportInfo,
    alias: Option<&str>,
    module: &str,
) -> String {
    import
        .identifier
        .clone()
        .or_else(|| alias.map(str::to_string))
        .unwrap_or_else(|| module.to_string())
}

pub fn python_namespace_binding_module(
    import: &ImportInfo,
    alias: Option<&str>,
    module: &str,
) -> String {
    if alias.is_some() {
        return module.to_string();
    }
    import
        .path
        .as_ref()
        .and_then(|path| path.segments.first().cloned())
        .unwrap_or_else(|| module.to_string())
}

pub fn resolve_python_relative_module(
    project: &dyn brokk_bifrost_core::analyzer::project::Project,
    source_file: &ProjectFile,
    module_expr: &str,
) -> Option<String> {
    resolve_python_relative_module_from_package(
        &python_current_package(project, source_file),
        module_expr,
    )
}

/// Resolve a relative Python module specifier against the importing file.
pub fn resolve_python_module_specifier(
    project: &dyn brokk_bifrost_core::analyzer::project::Project,
    importing_file: &ProjectFile,
    module_specifier: &str,
) -> Option<String> {
    if module_specifier.starts_with('.') {
        resolve_python_relative_module(project, importing_file, module_specifier)
    } else {
        Some(module_specifier.to_string())
    }
}

/// Resolve a structured Python module expression against an already-known
/// package identity. Dependency-pack producers know module identities without
/// owning a workspace [`ProjectFile`], so they use this entry point.
pub fn resolve_python_relative_module_from_package(
    current_package: &str,
    module_expr: &str,
) -> Option<String> {
    let level = module_expr.chars().take_while(|ch| *ch == '.').count();
    let suffix = module_expr[level..].trim_matches('.');
    let mut parts: Vec<_> = current_package
        .split('.')
        .filter(|part| !part.is_empty())
        .map(str::to_string)
        .collect();
    if level == 0 {
        return Some(module_expr.to_string());
    }
    if level > 0 {
        if level - 1 > parts.len() {
            return None;
        }
        parts.truncate(parts.len() - (level - 1));
    }
    if !suffix.is_empty() {
        parts.extend(suffix.split('.').map(str::to_string));
    }
    Some(parts.join("."))
}

fn python_current_package(
    project: &dyn brokk_bifrost_core::analyzer::project::Project,
    source_file: &ProjectFile,
) -> String {
    let module = match project.selected_module_name(source_file) {
        Ok(Some(name))
            if crate::declarations::python_module_components_from_name(source_file, &name)
                .is_some() =>
        {
            name
        }
        Ok(Some(name)) => {
            tracing::warn!(
                file = %source_file.abs_path().display(),
                published_name = %name,
                mounted_path = ?source_file.rel_path(),
                "published Python module is not a suffix of its mounted path; deriving module identity from package probes"
            );
            python_module_name(project, source_file)
        }
        Ok(None) => python_module_name(project, source_file),
        Err(error) => {
            tracing::warn!(
                file = %source_file.abs_path().display(),
                mounted_path = ?source_file.rel_path(),
                %error,
                "cannot read published Python module; deriving module identity from package probes"
            );
            python_module_name(project, source_file)
        }
    };
    if source_file
        .rel_path()
        .file_name()
        .and_then(|name| name.to_str())
        == Some("__init__.py")
    {
        module
    } else {
        module
            .rsplit_once('.')
            .map(|(package, _)| package.to_string())
            .unwrap_or_default()
    }
}