loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
//! Python file analysis module.
//!
//! Provides comprehensive Python code analysis including:
//! - Import/export detection (static and dynamic)
//! - Type hint usage extraction
//! - Framework decorator detection (pytest, FastAPI, Flask, Django, etc.)
//! - Concurrency pattern detection for race conditions
//! - Dynamic code generation detection (exec/eval/compile)
//! - Package metadata (typed packages, namespace packages)
//!
//! VibeCrafted with AI Agents (c)2026 Loctree Team

mod concurrency;
mod decorators;
mod dynamic;
mod exports;
mod helpers;
mod imports;
mod metadata;
mod stdlib;
mod usages;

// Re-export the public API
pub(crate) use stdlib::python_stdlib_set;

// Private imports from submodules
use concurrency::detect_py_race_indicators;
use decorators::{extract_decorator_type_usages, is_framework_decorator, parse_route_decorator};
use dynamic::{detect_dynamic_exec_templates, detect_sys_modules_injection};
use exports::{parse_all_list, read_all_from_resolved};
use imports::resolve_python_import;
use metadata::{check_namespace_package, check_typed_package, is_python_test_file};
use usages::{
    extract_bare_class_references, extract_class_from_containers, extract_python_function_calls,
    extract_type_hint_usages,
};

// External imports
use super::regexes::{regex_py_dynamic_dunder, regex_py_dynamic_importlib};
use crate::types::{
    ExportSymbol, FileAnalysis, ImportEntry, ImportKind, ImportSymbol, LocalSymbol, ParamInfo,
    ReexportEntry, ReexportKind, SymbolUsage,
};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

/// Parse Python function parameters from the text between parentheses.
///
/// Handles formats like:
/// - `x: int`
/// - `y: str = 'default'`
/// - `*args`
/// - `**kwargs`
/// - `self`
fn parse_python_params(params_text: &str) -> Vec<ParamInfo> {
    let mut params = Vec::new();
    let trimmed = params_text.trim();
    if trimmed.is_empty() {
        return params;
    }

    // Split by commas, but respect brackets for generic types like List[int]
    let mut current = String::new();
    let mut bracket_depth: usize = 0;
    let mut paren_depth: usize = 0;

    for ch in trimmed.chars() {
        match ch {
            '[' => {
                bracket_depth += 1;
                current.push(ch);
            }
            ']' => {
                bracket_depth = bracket_depth.saturating_sub(1);
                current.push(ch);
            }
            '(' => {
                paren_depth += 1;
                current.push(ch);
            }
            ')' => {
                paren_depth = paren_depth.saturating_sub(1);
                current.push(ch);
            }
            ',' if bracket_depth == 0 && paren_depth == 0 => {
                let param = parse_single_param(current.trim());
                if let Some(p) = param {
                    params.push(p);
                }
                current.clear();
            }
            _ => current.push(ch),
        }
    }

    // Don't forget the last parameter
    if !current.trim().is_empty()
        && let Some(p) = parse_single_param(current.trim())
    {
        params.push(p);
    }

    params
}

/// Parse a single Python parameter like `x: int = 5` or `*args` or `**kwargs`.
fn parse_single_param(param: &str) -> Option<ParamInfo> {
    let param = param.trim();
    if param.is_empty() {
        return None;
    }

    // Handle *args and **kwargs
    let (name_part, is_variadic) = if let Some(rest) = param.strip_prefix("**") {
        (rest, true)
    } else if let Some(rest) = param.strip_prefix('*') {
        (rest, true)
    } else {
        (param, false)
    };

    // Check for default value
    let (before_default, has_default) = if let Some(pos) = name_part.find('=') {
        (&name_part[..pos], true)
    } else {
        (name_part, false)
    };

    // Check for type annotation
    let (name, type_annotation) = if let Some(pos) = before_default.find(':') {
        let n = before_default[..pos].trim();
        let t = before_default[pos + 1..].trim();
        (
            n,
            if t.is_empty() {
                None
            } else {
                Some(t.to_string())
            },
        )
    } else {
        (before_default.trim(), None)
    };

    // Reconstruct name with prefix for variadic params
    let final_name = if is_variadic {
        if param.starts_with("**") {
            format!("**{}", name)
        } else {
            format!("*{}", name)
        }
    } else {
        name.to_string()
    };

    if final_name.is_empty() || final_name == "*" || final_name == "**" {
        return None;
    }

    Some(ParamInfo {
        name: final_name,
        type_annotation,
        has_default,
    })
}

fn collect_symbol_usages_from_lines(
    lines: &[&str],
    names: &HashSet<String>,
    max: usize,
) -> Vec<SymbolUsage> {
    let mut usages = Vec::new();
    let mut seen: HashSet<(String, usize)> = HashSet::new();

    for (idx, line) in lines.iter().enumerate() {
        if usages.len() >= max {
            break;
        }
        let mut start: Option<usize> = None;
        for (i, ch) in line.char_indices() {
            let is_ident = ch.is_ascii_alphanumeric() || ch == '_';
            if is_ident {
                if start.is_none() {
                    start = Some(i);
                }
                continue;
            }
            if let Some(begin) = start.take() {
                let token = &line[begin..i];
                let Some(first) = token.chars().next() else {
                    continue;
                };
                if !(first.is_ascii_alphabetic() || first == '_') {
                    continue;
                }
                if !names.contains(token) {
                    continue;
                }
                let line_num = idx + 1;
                if seen.insert((token.to_string(), line_num)) {
                    usages.push(SymbolUsage {
                        name: token.to_string(),
                        line: line_num,
                        context: line.trim().to_string(),
                    });
                    if usages.len() >= max {
                        break;
                    }
                }
            }
        }
        if usages.len() >= max {
            break;
        }
        if let Some(begin) = start.take() {
            let token = &line[begin..];
            let Some(first) = token.chars().next() else {
                continue;
            };
            if !(first.is_ascii_alphabetic() || first == '_') {
                continue;
            }
            if !names.contains(token) {
                continue;
            }
            let line_num = idx + 1;
            if seen.insert((token.to_string(), line_num)) {
                usages.push(SymbolUsage {
                    name: token.to_string(),
                    line: line_num,
                    context: line.trim().to_string(),
                });
            }
        }
    }

    usages
}

/// Process a `from X import Y, Z` statement and update analysis.
///
/// This is extracted to handle both single-line and multiline imports uniformly.
#[allow(clippy::too_many_arguments)]
fn process_from_import(
    module: &str,
    names_clean: &str,
    path: &Path,
    root: &Path,
    py_roots: &[PathBuf],
    extensions: Option<&HashSet<String>>,
    stdlib: &HashSet<String>,
    is_type_checking: bool,
    is_lazy: bool,
    _indent: usize,
    line_num: usize,
    is_package_init: bool,
    analysis: &mut FileAnalysis,
) {
    let module = module.trim().trim_end_matches('.');
    if module.is_empty() {
        return;
    }

    let mut entry = ImportEntry::new(module.to_string(), ImportKind::Static);
    entry.line = Some(line_num);
    let (resolved, resolution) =
        resolve_python_import(module, path, root, py_roots, extensions, stdlib);
    entry.resolution = resolution;
    entry.resolved_path = resolved.clone();
    entry.is_type_checking = is_type_checking;
    entry.is_lazy = is_lazy;
    entry.source_raw = format!("from {} import {}", module, names_clean);

    if names_clean != "*" {
        for sym in names_clean.split(',') {
            let sym = sym.trim();
            if sym.is_empty() {
                continue;
            }
            let (name, alias) = if let Some((lhs, rhs)) = sym.split_once(" as ") {
                (lhs.trim(), Some(rhs.trim().to_string()))
            } else {
                (sym, None)
            };
            entry.symbols.push(ImportSymbol {
                name: name.to_string(),
                alias,
                is_default: false,
            });
        }
    }
    analysis.imports.push(entry);

    // Python package API re-export pattern:
    // __init__.py often re-exports names via `from .mod import Foo as Bar`.
    // Treat these as re-exports (not fresh definitions) to reduce duplicate/dead noise.
    if is_package_init && names_clean != "*" {
        let mut name_pairs: Vec<(String, String)> = Vec::new();
        for sym in names_clean.split(',') {
            let sym = sym.trim();
            if sym.is_empty() {
                continue;
            }
            let (original, exported) = if let Some((lhs, rhs)) = sym.split_once(" as ") {
                (lhs.trim(), rhs.trim())
            } else {
                (sym, sym)
            };
            if exported.is_empty() || exported.starts_with('_') {
                continue;
            }
            name_pairs.push((original.to_string(), exported.to_string()));
            analysis.exports.push(ExportSymbol::new(
                exported.to_string(),
                "reexport",
                "named",
                Some(line_num),
            ));
        }

        if !name_pairs.is_empty() {
            analysis.reexports.push(ReexportEntry {
                source: module.to_string(),
                kind: ReexportKind::Named(name_pairs),
                resolved: resolved.clone(),
            });
        }
    }

    if names_clean == "*" {
        let mut entry = ReexportEntry {
            source: module.to_string(),
            kind: ReexportKind::Star,
            resolved: resolved.clone(),
        };
        if let Some(names) = read_all_from_resolved(&resolved, root) {
            for name in &names {
                analysis
                    .exports
                    .push(ExportSymbol::new(name.clone(), "reexport", "named", None));
            }
            // Star imports have no aliases - original and exported are the same
            let name_pairs: Vec<(String, String)> =
                names.into_iter().map(|n| (n.clone(), n)).collect();
            entry.kind = ReexportKind::Named(name_pairs);
        }
        analysis.reexports.push(entry);
    }
}

/// Main entry point for Python file analysis.
///
/// Analyzes a Python file and extracts:
/// - Import statements (static and dynamic)
/// - Export symbols (functions, classes, __all__ list)
/// - Re-exports from __init__.py files
/// - Type hint usages
/// - Framework decorators
/// - Concurrency patterns
/// - Entry points
pub(crate) fn analyze_py_file(
    content: &str,
    path: &Path,
    root: &Path,
    extensions: Option<&HashSet<String>>,
    relative: String,
    py_roots: &[PathBuf],
    stdlib: &HashSet<String>,
) -> FileAnalysis {
    let mut analysis = FileAnalysis::new(relative);
    let mut local_symbols: Vec<LocalSymbol> = Vec::new();
    let mut type_check_stack: Vec<usize> = Vec::new();
    let mut pending_callback_decorator = false;
    let mut pending_framework_decorator = false;
    let mut pending_fixture_decorator = false;
    let mut pending_routes: Vec<crate::types::RouteInfo> = Vec::new();
    let mut pending_fixture_name: Option<String> = None;
    let mut in_docstring = false;
    // State for multiline imports: (module, accumulated_symbols, start_line, is_type_checking, is_lazy)
    let mut pending_multiline_from: Option<(String, Vec<String>, usize, bool, bool)> = None;
    let is_package_init = path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| n == "__init__.py");

    // Set Python-specific metadata
    analysis.is_test = is_python_test_file(path, content);
    analysis.is_typed_package = check_typed_package(path, root);
    analysis.is_namespace_package = check_namespace_package(path, root);

    for (idx, line) in content.lines().enumerate() {
        let line_num = idx + 1;
        let trimmed_leading = line.trim_start();

        if in_docstring {
            // End docstring on closing triple quotes
            if trimmed_leading.contains("\"\"\"") || trimmed_leading.contains("'''") {
                in_docstring = false;
            }
            continue;
        }

        // Skip docstring/comment blocks at the start of a line
        if trimmed_leading.starts_with("\"\"\"") || trimmed_leading.starts_with("'''") {
            // If closing appears on the same line, exit docstring immediately
            let mut occurrences = 0;
            for token in ["\"\"\"", "'''"] {
                occurrences += trimmed_leading.matches(token).count();
            }
            if occurrences < 2 {
                in_docstring = true;
            }
            continue;
        }

        let without_comment = line.split('#').next().unwrap_or("").trim_end();
        let indent = without_comment
            .chars()
            .take_while(|c| c.is_whitespace())
            .count();
        if !without_comment.trim().is_empty() {
            while let Some(level) = type_check_stack.last() {
                if indent < *level {
                    type_check_stack.pop();
                } else {
                    break;
                }
            }
        }

        let trimmed = without_comment.trim_start();
        if let Some(body) = trimmed
            .strip_prefix("if ")
            .and_then(|rest| rest.strip_suffix(':'))
        {
            if body.contains("TYPE_CHECKING") {
                type_check_stack.push(indent + 1);
            }
            continue;
        }

        let in_type_checking = !type_check_stack.is_empty();
        if trimmed.starts_with('@') {
            // Track decorators that register callbacks (e.g., @rumps.clicked)
            if trimmed.contains("clicked") || trimmed.contains("rumps.") {
                pending_callback_decorator = true;
            }
            // Track framework decorators that mark functions as "used"
            if is_framework_decorator(trimmed) {
                pending_framework_decorator = true;
            }
            if let Some(route) = parse_route_decorator(trimmed, line_num) {
                pending_routes.push(route);
            }
            // pytest fixtures: treat next def as used
            if trimmed.contains("pytest.fixture") {
                pending_fixture_decorator = true;
                pending_fixture_name = None;
            }
            // Extract type usages from decorator parameters (response_model=X, Depends(X))
            extract_decorator_type_usages(trimmed, &mut analysis.local_uses);
            continue;
        }

        // Handle multiline import continuation
        if let Some((ref module, ref mut symbols, start_line, is_tc, is_lz)) =
            pending_multiline_from
        {
            // Accumulate symbols from continuation lines
            let line_content = trimmed.trim_end_matches(')').trim_end_matches(',');
            let line_content = line_content.split('#').next().unwrap_or("").trim();

            // Parse symbols from this line
            for sym in line_content.split(',') {
                let sym = sym.trim();
                if sym.is_empty() {
                    continue;
                }
                symbols.push(sym.to_string());
            }

            // Check if this line closes the import (contains closing paren)
            if trimmed.contains(')') {
                // Process the complete multiline import
                let module_clone = module.clone();
                let symbols_clone = symbols.clone();
                let start_line_val = start_line;
                let is_type_checking = is_tc;
                let is_lazy = is_lz;

                // Clear pending state before processing
                pending_multiline_from = None;

                // Process the import
                process_from_import(
                    &module_clone,
                    &symbols_clone.join(", "),
                    path,
                    root,
                    py_roots,
                    extensions,
                    stdlib,
                    is_type_checking,
                    is_lazy,
                    indent,
                    start_line_val,
                    is_package_init,
                    &mut analysis,
                );
            }
            continue;
        }

        if let Some(rest) = trimmed.strip_prefix("import ") {
            for part in rest.split(',') {
                let mut name = part.trim();
                if let Some((lhs, _)) = name.split_once(" as ") {
                    name = lhs.trim();
                }
                if !name.is_empty() {
                    let mut entry = ImportEntry::new(name.to_string(), ImportKind::Static);
                    entry.line = Some(line_num);
                    let (resolved, resolution) =
                        resolve_python_import(name, path, root, py_roots, extensions, stdlib);
                    entry.resolution = resolution;
                    entry.resolved_path = resolved;
                    entry.is_type_checking = in_type_checking;
                    entry.is_lazy = indent > 0;
                    analysis.imports.push(entry);
                }
            }
        } else if let Some(rest) = trimmed.strip_prefix("from ")
            && let Some((module, names_raw)) = rest.split_once(" import ")
        {
            let module = module.trim().trim_end_matches('.');
            let names_raw_trimmed = names_raw.trim();

            // Check if this is a multiline import: starts with ( but doesn't end with )
            let is_multiline_start =
                names_raw_trimmed.starts_with('(') && !names_raw_trimmed.contains(')');

            if is_multiline_start {
                // Start accumulating multiline import
                // Extract any symbols on the first line after the opening paren
                let first_line_symbols = names_raw_trimmed
                    .trim_start_matches('(')
                    .split('#')
                    .next()
                    .unwrap_or("")
                    .trim();
                let mut initial_symbols: Vec<String> = Vec::new();
                for sym in first_line_symbols.split(',') {
                    let sym = sym.trim();
                    if !sym.is_empty() {
                        initial_symbols.push(sym.to_string());
                    }
                }
                pending_multiline_from = Some((
                    module.to_string(),
                    initial_symbols,
                    line_num,
                    in_type_checking,
                    indent > 0,
                ));
            } else {
                // Single-line import - process immediately
                let names_clean = names_raw_trimmed.trim_matches('(').trim_matches(')');
                let names_clean = names_clean.split('#').next().unwrap_or("").trim();
                process_from_import(
                    module,
                    names_clean,
                    path,
                    root,
                    py_roots,
                    extensions,
                    stdlib,
                    in_type_checking,
                    indent > 0,
                    indent,
                    line_num,
                    is_package_init,
                    &mut analysis,
                );
            }
        } else {
            // Detect callback assignment patterns (callback=self.refresh or callback=refresh)
            if let Some(pos) = trimmed.find("callback")
                && let Some(eq_pos) = trimmed[pos..].find('=')
            {
                let after_eq = trimmed[pos + eq_pos + 1..].trim();
                let target = after_eq
                    .trim_start_matches("self.")
                    .trim_start_matches("cls.")
                    .trim_start_matches('&')
                    .trim_start_matches('*');
                let ident = target
                    .split(|c: char| !c.is_alphanumeric() && c != '_')
                    .next()
                    .unwrap_or("")
                    .trim();
                if !ident.is_empty() {
                    analysis.local_uses.push(ident.to_string());
                }
            }

            // Track class bases and top-level exports
            if let Some(rest) = trimmed.strip_prefix("class ") {
                let (name_part, _) = rest.split_once(':').unwrap_or((rest, ""));
                let (name, bases_part) = if let Some((n, bases)) = name_part.split_once('(') {
                    (n.trim(), Some(bases.trim_end_matches(')').trim()))
                } else {
                    (name_part.trim(), None)
                };

                if !name.is_empty() {
                    local_symbols.push(LocalSymbol {
                        name: name.to_string(),
                        kind: "class".to_string(),
                        line: Some(line_num),
                        context: line.trim().to_string(),
                        is_exported: false,
                    });
                }

                if indent == 0 && !name.starts_with('_') && !name.is_empty() {
                    analysis.exports.push(ExportSymbol::new(
                        name.to_string(),
                        "class",
                        "named",
                        Some(line_num),
                    ));
                }

                if let Some(bases) = bases_part {
                    for base in bases.split(',') {
                        let base = base
                            .trim_start_matches("self.")
                            .trim_start_matches("cls.")
                            .trim();
                        if !base.is_empty() {
                            // Extract the last component for dotted names (e.g., wagtail.models.Page -> Page)
                            // But also keep the full dotted name in case it's a relative import
                            let simple_name = base.rsplit('.').next().unwrap_or(base);
                            if simple_name != base {
                                // If it's a dotted name, add both the full name and the simple name
                                analysis.local_uses.push(base.to_string());
                            }
                            if !simple_name.is_empty() {
                                analysis.local_uses.push(simple_name.to_string());
                            }
                        }
                    }
                }
            } else if let Some(rest) = trimmed
                .strip_prefix("async def ")
                .or_else(|| trimmed.strip_prefix("def "))
            {
                // Handle both "def foo" and "async def foo"
                // Extract function name and parameters
                let (name, params_text) = if let Some(paren_pos) = rest.find('(') {
                    let fn_name = rest[..paren_pos].trim().trim_matches(':');
                    // Find matching closing paren
                    let after_open = &rest[paren_pos + 1..];
                    let close_pos = after_open.find(')').unwrap_or(after_open.len());
                    let params = &after_open[..close_pos];
                    (fn_name, params)
                } else {
                    (rest.trim().trim_matches(':'), "")
                };

                if !name.is_empty() {
                    local_symbols.push(LocalSymbol {
                        name: name.to_string(),
                        kind: "function".to_string(),
                        line: Some(line_num),
                        context: line.trim().to_string(),
                        is_exported: false,
                    });
                }

                if indent == 0 && !name.starts_with('_') && !name.is_empty() {
                    let params = parse_python_params(params_text);
                    analysis.exports.push(ExportSymbol::with_params(
                        name.to_string(),
                        "def",
                        "named",
                        Some(line_num),
                        params,
                    ));
                }

                // Mark function as used if decorated with callback/framework decorator
                if (pending_callback_decorator || pending_framework_decorator) && !name.is_empty() {
                    analysis.local_uses.push(name.to_string());
                }
                if pending_fixture_decorator && !name.is_empty() {
                    analysis.local_uses.push(name.to_string());
                    pending_fixture_name = Some(name.to_string());
                }
                if !name.is_empty() && !pending_routes.is_empty() {
                    for mut r in pending_routes.drain(..) {
                        if r.name.is_none() {
                            r.name = Some(name.to_string());
                        }
                        analysis.routes.push(r);
                    }
                } else {
                    pending_routes.clear();
                }
                pending_callback_decorator = false;
                pending_framework_decorator = false;
                pending_fixture_decorator = false;
                if let Some(fix) = pending_fixture_name.take() {
                    analysis.pytest_fixtures.push(fix);
                }
            } else if !trimmed.is_empty()
                && !trimmed.starts_with('#')
                && !trimmed.starts_with("class ")
            {
                // Reset decorator flags if we hit a non-decorator, non-def, non-class line
                pending_framework_decorator = false;
                pending_routes.clear();
                pending_fixture_name = None;
            }
        }
    }

    for caps in regex_py_dynamic_importlib().captures_iter(content) {
        if let Some(m) = caps.get(1) {
            analysis.dynamic_imports.push(m.as_str().trim().to_string());
        }
    }
    for caps in regex_py_dynamic_dunder().captures_iter(content) {
        if let Some(m) = caps.get(1) {
            analysis.dynamic_imports.push(m.as_str().trim().to_string());
        }
    }

    // Process __all__ list: only add exports that aren't already defined
    // in this file (e.g., by class/def). This avoids "twins" false positives
    // where `__all__ = ["Foo"]` duplicates `class Foo:`.
    let existing_export_names: std::collections::HashSet<String> =
        analysis.exports.iter().map(|e| e.name.clone()).collect();
    for name in parse_all_list(content) {
        if !existing_export_names.contains(&name) {
            analysis
                .exports
                .push(ExportSymbol::new(name, "__all__", "named", None));
        }
    }

    if !local_symbols.is_empty() {
        let export_names: HashSet<String> =
            analysis.exports.iter().map(|e| e.name.clone()).collect();
        for symbol in &mut local_symbols {
            symbol.is_exported = export_names.contains(&symbol.name);
        }
        analysis.local_symbols = local_symbols;
    }

    // Detect Python entry points
    // 1. __main__.py files are package entry points
    if analysis.path.ends_with("__main__.py") {
        analysis.entry_points.push("__main__".to_string());
    }
    // 2. if __name__ == "__main__": is a script entry point
    if content.contains("if __name__")
        && (content.contains("__main__") || content.contains("'__main__'"))
        && !analysis.entry_points.contains(&"script".to_string())
    {
        analysis.entry_points.push("script".to_string());
        // Also mark 'main' as locally used if it's called in the __main__ block
        if content.contains("main()") && !analysis.local_uses.contains(&"main".to_string()) {
            analysis.local_uses.push("main".to_string());
        }
    }

    // Detect bare function calls in Python (similar to Rust detection)
    // This catches local function calls like `helper_func(...)` within the same file
    extract_python_function_calls(content, &mut analysis.local_uses);

    // Detect type hint usages (dict[str, MyClass], defaultdict(MyClass), etc.)
    extract_type_hint_usages(content, &mut analysis.local_uses);

    // Detect class references in tuple/list/dict literals (issue #2)
    // This catches patterns like: (ClassName, 'value'), [Foo, Bar], {'key': Baz}
    extract_class_from_containers(content, &mut analysis.local_uses);

    // Detect bare class name usage in function arguments and returns (issue #3)
    // This catches: return ClassName, issubclass(x, ClassName), isinstance(obj, MyClass)
    extract_bare_class_references(content, &mut analysis.local_uses);

    // Detect exec/eval/compile dynamic code generation patterns
    // This catches template strings like "def get%s" that generate symbols dynamically
    analysis.dynamic_exec_templates = detect_dynamic_exec_templates(content);

    // Detect sys.modules monkey-patching (e.g., sys.modules['compat'] = wrapper)
    // Files with these patterns have all exports accessible at runtime via the injected name
    analysis.sys_modules_injections = detect_sys_modules_injection(content);

    // Detect Python concurrency race indicators
    analysis.py_race_indicators = detect_py_race_indicators(content);

    if !analysis.local_uses.is_empty() {
        let usage_names: HashSet<String> = analysis.local_uses.iter().cloned().collect();
        let lines: Vec<&str> = content.lines().collect();
        const MAX_USAGES_PER_FILE: usize = 1500;
        let usages = collect_symbol_usages_from_lines(&lines, &usage_names, MAX_USAGES_PER_FILE);
        if !usages.is_empty() {
            analysis.symbol_usages = usages;
        }
    }

    analysis
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ImportResolutionKind;
    use tempfile::tempdir;

    fn py_exts() -> HashSet<String> {
        ["py"].iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn marks_type_checking_imports_and_stdlib() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::write(root.join("foo.py"), "VALUE = 1").expect("write foo.py");
        let content = r#"
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    import foo

import sys
"#;
        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );
        assert!(analysis.imports.len() >= 2);
        let foo = analysis
            .imports
            .iter()
            .find(|i| i.source == "foo")
            .expect("foo import");
        assert!(foo.is_type_checking);
        assert_eq!(foo.resolution, ImportResolutionKind::Local);
        assert!(foo.resolved_path.as_deref().unwrap().contains("foo.py"));

        let sys = analysis
            .imports
            .iter()
            .find(|i| i.source == "sys")
            .expect("sys import");
        assert!(!sys.is_type_checking);
        assert_eq!(sys.resolution, ImportResolutionKind::Stdlib);
        assert!(sys.resolved_path.is_none());
    }

    #[test]
    fn python_local_symbols_and_usages() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        let path = root.join("sample.py");
        let content =
            "class Foo:\n    def method(self):\n        pass\n\ndef helper():\n    return Foo()\n";
        std::fs::write(&path, content).expect("write sample.py");

        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "sample.py".to_string(),
            &[],
            python_stdlib_set(),
        );

        assert!(
            analysis.local_symbols.iter().any(|s| s.name == "Foo"),
            "Foo should be in local_symbols"
        );
        assert!(
            analysis.local_symbols.iter().any(|s| s.name == "helper"),
            "helper should be in local_symbols"
        );
        assert!(
            analysis.symbol_usages.iter().any(|u| u.name == "Foo"),
            "Foo should appear in symbol_usages"
        );
    }

    #[test]
    fn tracks_from_import_symbols_and_aliases() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("utils")).expect("mkdir utils");
        std::fs::write(
            root.join("utils/helpers.py"),
            "class Foo: pass\nclass Baz: pass",
        )
        .expect("write helpers");
        let content = "from utils.helpers import Foo as Bar, Baz";
        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );
        let imp = analysis.imports.first().expect("import entry");
        assert_eq!(imp.symbols.len(), 2);
        assert_eq!(imp.symbols[0].name, "Foo");
        assert_eq!(imp.symbols[0].alias.as_deref(), Some("Bar"));
        assert_eq!(imp.symbols[1].name, "Baz");
    }

    #[test]
    fn ignores_imports_inside_docstrings() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        let content = "\"\"\"\nExample:\n    from app.middlewares.request_id import get_request_id\n\"\"\"\n\ndef real():\n    return 1\n";
        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );
        assert!(
            analysis.imports.is_empty(),
            "docstring-only import should be ignored"
        );
    }

    #[test]
    fn expands_all_for_star_import() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("pkg")).expect("mkdir pkg");
        std::fs::write(root.join("pkg/__init__.py"), "__all__ = ['Foo', 'Bar']")
            .expect("write __init__");
        let content = "from pkg import *";
        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );
        let reexports = analysis
            .reexports
            .iter()
            .find(|r| r.source == "pkg")
            .expect("pkg reexport");
        match &reexports.kind {
            ReexportKind::Named(names) => {
                assert_eq!(names.len(), 2);
                let exported_names: Vec<_> = names.iter().map(|(_, e)| e.as_str()).collect();
                assert!(exported_names.contains(&"Foo"));
                assert!(exported_names.contains(&"Bar"));
            }
            other => panic!("expected named reexport, got {:?}", other),
        }
        let exported: HashSet<_> = analysis.exports.iter().map(|e| e.name.clone()).collect();
        assert!(exported.contains("Foo"));
        assert!(exported.contains("Bar"));
    }

    #[test]
    fn treats_init_named_from_import_as_reexport() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("pkg")).expect("mkdir pkg");
        std::fs::write(
            root.join("pkg/foo.py"),
            "class Foo: pass\nclass Baz: pass\n",
        )
        .expect("write foo.py");

        let content = "from .foo import Foo as Bar, Baz";
        let path = root.join("pkg/__init__.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "pkg/__init__.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );

        let reexport = analysis
            .reexports
            .iter()
            .find(|r| r.source == ".foo")
            .expect("expected .foo reexport");

        match &reexport.kind {
            ReexportKind::Named(names) => {
                assert!(names.contains(&(String::from("Foo"), String::from("Bar"))));
                assert!(names.contains(&(String::from("Baz"), String::from("Baz"))));
            }
            other => panic!("expected named reexport, got {:?}", other),
        }

        let exported: HashSet<_> = analysis
            .exports
            .iter()
            .filter(|e| e.kind == "reexport")
            .map(|e| e.name.as_str())
            .collect();
        assert!(exported.contains("Bar"));
        assert!(exported.contains("Baz"));
    }

    #[test]
    fn dynamic_imports_and_local_over_stdlib() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::write(root.join("json.py"), "LOCAL = True").expect("write json.py");
        let content = r#"
import json
mod = importlib.import_module(f"pkg.{name}")
dyn = __import__("x.y")
"#;
        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );
        let json_imp = analysis
            .imports
            .iter()
            .find(|i| i.source == "json")
            .expect("json import");
        assert_eq!(json_imp.resolution, ImportResolutionKind::Local);
        assert!(
            json_imp
                .resolved_path
                .as_deref()
                .unwrap_or("")
                .ends_with("json.py")
        );

        assert_eq!(analysis.dynamic_imports.len(), 2);
        assert!(analysis.dynamic_imports.iter().any(|s| s.contains("pkg.")));
        assert!(analysis.dynamic_imports.iter().any(|s| s.contains("x.y")));
    }

    #[test]
    fn parses_all_list_exports() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
__all__ = ["foo", "bar"]

def foo():
    pass

def bar():
    pass

def _private():
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let export_names: Vec<_> = analysis.exports.iter().map(|e| e.name.as_str()).collect();
        assert!(export_names.contains(&"foo"));
        assert!(export_names.contains(&"bar"));
        assert!(!export_names.contains(&"_private"));
    }

    #[test]
    fn parses_all_list_with_comments() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
__all__ = [
    "foo",  # inline comment
    "bar",
    # "baz" is intentionally excluded
]
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let export_names: Vec<_> = analysis.exports.iter().map(|e| e.name.as_str()).collect();
        assert!(export_names.contains(&"foo"));
        assert!(export_names.contains(&"bar"));
        assert!(!export_names.iter().any(|n| n.contains('#')));
        assert!(!export_names.contains(&"baz"));
    }

    #[test]
    fn parses_class_exports() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
class MyClass:
    pass

class _PrivateClass:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("classes.py"),
            root,
            Some(&py_exts()),
            "classes.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let class_exports: Vec<_> = analysis
            .exports
            .iter()
            .filter(|e| e.kind == "class")
            .collect();
        assert!(class_exports.iter().any(|e| e.name == "MyClass"));
        assert!(!class_exports.iter().any(|e| e.name == "_PrivateClass"));
    }

    #[test]
    fn detects_main_entry_point() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
def main():
    print("Hello")

if __name__ == "__main__":
    main()
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("__main__.py"),
            root,
            Some(&py_exts()),
            "__main__.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.entry_points.contains(&"__main__".to_string()));
    }

    #[test]
    fn detects_script_entry_point() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
def main():
    print("Hello")

if __name__ == "__main__":
    main()
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("script.py"),
            root,
            Some(&py_exts()),
            "script.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.entry_points.contains(&"script".to_string()));
    }

    #[test]
    fn detects_test_file_by_path() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("tests")).expect("mkdir");
        std::fs::write(root.join("tests/test_utils.py"), "def test_foo(): pass")
            .expect("write test file");

        let content = "def test_foo(): pass";
        let analysis = analyze_py_file(
            content,
            &root.join("tests/test_utils.py"),
            root,
            Some(&py_exts()),
            "tests/test_utils.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.is_test);
    }

    #[test]
    fn detects_test_file_by_content() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
import pytest

@pytest.fixture
def sample_fixture():
    return 42

def test_something(sample_fixture):
    assert sample_fixture == 42
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("my_tests.py"),
            root,
            Some(&py_exts()),
            "my_tests.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.is_test);
    }

    #[test]
    fn detects_typed_package() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("mypackage")).expect("mkdir");
        std::fs::write(root.join("mypackage/__init__.py"), "").expect("write __init__");
        std::fs::write(root.join("mypackage/py.typed"), "").expect("write py.typed");
        std::fs::write(root.join("mypackage/utils.py"), "def foo(): pass").expect("write utils");

        let content = "def foo(): pass";
        let analysis = analyze_py_file(
            content,
            &root.join("mypackage/utils.py"),
            root,
            Some(&py_exts()),
            "mypackage/utils.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.is_typed_package);
    }

    #[test]
    fn detects_non_typed_package() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("mypackage")).expect("mkdir");
        std::fs::write(root.join("mypackage/__init__.py"), "").expect("write __init__");
        std::fs::write(root.join("mypackage/utils.py"), "def foo(): pass").expect("write utils");

        let content = "def foo(): pass";
        let analysis = analyze_py_file(
            content,
            &root.join("mypackage/utils.py"),
            root,
            Some(&py_exts()),
            "mypackage/utils.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(!analysis.is_typed_package);
    }

    #[test]
    fn detects_namespace_package() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("namespace_pkg")).expect("mkdir");
        std::fs::write(root.join("namespace_pkg/module.py"), "VALUE = 1").expect("write module");

        let content = "VALUE = 1";
        let analysis = analyze_py_file(
            content,
            &root.join("namespace_pkg/module.py"),
            root,
            Some(&py_exts()),
            "namespace_pkg/module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(analysis.is_namespace_package);
    }

    #[test]
    fn traditional_package_not_namespace() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("pkg")).expect("mkdir");
        std::fs::write(root.join("pkg/__init__.py"), "").expect("write __init__");
        std::fs::write(root.join("pkg/module.py"), "VALUE = 1").expect("write module");

        let content = "VALUE = 1";
        let analysis = analyze_py_file(
            content,
            &root.join("pkg/module.py"),
            root,
            Some(&py_exts()),
            "pkg/module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(!analysis.is_namespace_package);
    }

    #[test]
    fn top_level_exports_have_lines_and_methods_not_exported() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        let content = "\
class Base:\n    pass\n\nclass Child(Base):\n    def method(self):\n        pass\n\ndef top():\n    return True\n\nmenu = MenuItem(callback=top)\n";
        let analysis = analyze_py_file(
            content,
            &root.join("app.py"),
            root,
            Some(&py_exts()),
            "app.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let names: Vec<_> = analysis.exports.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Base"));
        assert!(names.contains(&"Child"));
        assert!(names.contains(&"top"));
        assert!(!names.contains(&"method"));

        let top_line = analysis
            .exports
            .iter()
            .find(|e| e.name == "top")
            .and_then(|e| e.line)
            .unwrap();
        assert_eq!(top_line, 8);

        assert!(analysis.local_uses.contains(&"top".to_string()));
        assert!(analysis.local_uses.contains(&"Base".to_string()));
    }

    #[test]
    fn detects_type_hint_usage() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
from collections import defaultdict
from typing import Dict, List

class UserRateLimit:
    pass

class Session:
    pass

rate_limits: dict[str, UserRateLimit] = {}
sessions: Dict[str, Session] = {}

user_limits = defaultdict(UserRateLimit)

def get_limit(user_id: str) -> UserRateLimit:
    return rate_limits[user_id]

def process(items: List[Session]) -> None:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("session_security.py"),
            root,
            Some(&py_exts()),
            "session_security.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(
            analysis.local_uses.contains(&"UserRateLimit".to_string()),
            "UserRateLimit not found in local_uses: {:?}",
            analysis.local_uses
        );
        assert!(
            analysis.local_uses.contains(&"Session".to_string()),
            "Session not found in local_uses: {:?}",
            analysis.local_uses
        );
    }

    #[test]
    fn marks_pytest_fixture_as_used() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
import pytest

@pytest.fixture
def client():
    return object()
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("conftest.py"),
            root,
            Some(&py_exts()),
            "conftest.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(
            analysis.local_uses.contains(&"client".to_string()),
            "pytest fixture should be marked as used"
        );
        assert!(
            analysis.pytest_fixtures.contains(&"client".to_string()),
            "pytest fixture list should capture fixture name"
        );
    }

    #[test]
    fn captures_fastapi_route_metadata() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
from fastapi import APIRouter
router = APIRouter()

@router.get("/patients")
def list_patients():
    return []
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("api.py"),
            root,
            Some(&py_exts()),
            "api.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert_eq!(analysis.routes.len(), 1);
        let route = &analysis.routes[0];
        assert_eq!(route.framework, "fastapi");
        assert_eq!(route.method, "GET");
        assert_eq!(route.path.as_deref(), Some("/patients"));
        assert_eq!(route.name.as_deref(), Some("list_patients"));
    }

    #[test]
    fn captures_async_def_fastapi_route() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        // Test that async def functions are correctly associated with routes
        let content = r#"
from fastapi import APIRouter
router = APIRouter()

@router.post("/items")
async def create_item(data: dict):
    return {"created": True}

@router.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"id": item_id}
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("api.py"),
            root,
            Some(&py_exts()),
            "api.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert_eq!(
            analysis.routes.len(),
            2,
            "Should detect both async def routes"
        );

        let post_route = &analysis.routes[0];
        assert_eq!(post_route.framework, "fastapi");
        assert_eq!(post_route.method, "POST");
        assert_eq!(post_route.path.as_deref(), Some("/items"));
        assert_eq!(post_route.name.as_deref(), Some("create_item"));

        let get_route = &analysis.routes[1];
        assert_eq!(get_route.framework, "fastapi");
        assert_eq!(get_route.method, "GET");
        assert_eq!(get_route.path.as_deref(), Some("/items/{item_id}"));
        assert_eq!(get_route.name.as_deref(), Some("get_item"));
    }

    #[test]
    fn captures_flask_route_methods_list() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
from flask import Blueprint
bp = Blueprint("bp", __name__)

@bp.route("/ping", methods=["GET", "POST"])
def ping():
    return "ok"
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("flask_app.py"),
            root,
            Some(&py_exts()),
            "flask_app.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert_eq!(analysis.routes.len(), 1);
        let route = &analysis.routes[0];
        assert_eq!(route.framework, "flask");
        assert_eq!(route.method, "GET,POST");
        assert_eq!(route.path.as_deref(), Some("/ping"));
        assert_eq!(route.name.as_deref(), Some("ping"));
    }

    #[test]
    fn golang_gdb_pattern_full_integration() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
class StringTypePrinter:
    pattern = re.compile(r'^struct string$')

class SliceTypePrinter:
    pattern = re.compile(r'^struct \[\]')

class MapTypePrinter:
    pattern = re.compile(r'^map\[')

class ChanTypePrinter:
    pattern = re.compile(r'^chan ')

class GoLenFunc(gdb.Function):
    how = ((StringTypePrinter, 'len'),
           (SliceTypePrinter, 'len'),
           (MapTypePrinter, 'used'),
           (ChanTypePrinter, 'qcount'))

    def invoke(self, obj):
        typename = str(obj.type)
        for klass, fld in self.how:
            if klass.pattern.match(typename):
                return obj[fld]
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("gdb_golang.py"),
            root,
            Some(&py_exts()),
            "gdb_golang.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(
            analysis
                .local_uses
                .contains(&"StringTypePrinter".to_string()),
            "StringTypePrinter not found in local_uses: {:?}",
            analysis.local_uses
        );
        assert!(
            analysis
                .local_uses
                .contains(&"SliceTypePrinter".to_string()),
            "SliceTypePrinter not found in local_uses"
        );
        assert!(
            analysis.local_uses.contains(&"MapTypePrinter".to_string()),
            "MapTypePrinter not found in local_uses"
        );
        assert!(
            analysis.local_uses.contains(&"ChanTypePrinter".to_string()),
            "ChanTypePrinter not found in local_uses"
        );

        let export_names: Vec<_> = analysis.exports.iter().map(|e| e.name.as_str()).collect();
        assert!(export_names.contains(&"StringTypePrinter"));
        assert!(export_names.contains(&"SliceTypePrinter"));
        assert!(export_names.contains(&"MapTypePrinter"));
        assert!(export_names.contains(&"ChanTypePrinter"));
        assert!(export_names.contains(&"GoLenFunc"));
    }

    #[test]
    fn detects_mixin_class_usage() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
class ButtonsColumnMixin:
    """Mixin for button column functionality"""
    pass

class WagtailAdminDraftStateFormMixin:
    pass

class IndexViewOptionalFeaturesMixin:
    pass

class NullAdminURLFinder:
    """Class used in same-file reference"""
    pass

class MyView(IndexViewOptionalFeaturesMixin, ButtonsColumnMixin):
    pass

def get_finder():
    return NullAdminURLFinder

def check_column(column_class):
    if issubclass(column_class, ButtonsColumnMixin):
        return True
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("views.py"),
            root,
            Some(&py_exts()),
            "views.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        assert!(
            analysis
                .local_uses
                .contains(&"ButtonsColumnMixin".to_string()),
            "ButtonsColumnMixin should be marked as used (inheritance): {:?}",
            analysis.local_uses
        );
        assert!(
            analysis
                .local_uses
                .contains(&"IndexViewOptionalFeaturesMixin".to_string()),
            "IndexViewOptionalFeaturesMixin should be marked as used (inheritance): {:?}",
            analysis.local_uses
        );
        assert!(
            analysis
                .local_uses
                .contains(&"NullAdminURLFinder".to_string()),
            "NullAdminURLFinder should be marked as used (function return): {:?}",
            analysis.local_uses
        );
    }

    #[test]
    fn handles_utf8_emoji_in_python_code() {
        let code = r#"
"""
This docstring has emoji and ellipsis and bullet points
"""

class MyClass:
    """Another docstring with emoji"""

    def method(self):
        return MyHelper  # Class reference after emoji content

class MyHelper:
    pass
"#;

        let temp = tempdir().unwrap();
        let py_file = temp.path().join("test_emoji.py");
        std::fs::write(&py_file, code).unwrap();

        let relative = py_file
            .strip_prefix(temp.path())
            .unwrap()
            .to_string_lossy()
            .to_string();
        let analysis = analyze_py_file(
            code,
            &py_file,
            temp.path(),
            Some(&py_exts()),
            relative,
            &[],
            &HashSet::new(),
        );

        assert!(analysis.exports.iter().any(|e| e.name == "MyClass"));
        assert!(analysis.exports.iter().any(|e| e.name == "MyHelper"));
    }

    #[test]
    fn parses_multiline_from_import() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("pkg/sub")).expect("mkdir pkg/sub");
        std::fs::write(
            root.join("pkg/sub/adapter.py"),
            "class AnthropicMessagesAdapter:\n    pass\n\nclass OtherClass:\n    pass\n",
        )
        .expect("write adapter.py");
        std::fs::write(root.join("pkg/__init__.py"), "").expect("write pkg init");
        std::fs::write(root.join("pkg/sub/__init__.py"), "").expect("write sub init");

        let content = r#"
from pkg.sub.adapter import (
    AnthropicMessagesAdapter,
)

def use_adapter():
    return AnthropicMessagesAdapter()
"#;

        let path = root.join("router.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "router.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );

        // Should have found the import
        assert!(
            !analysis.imports.is_empty(),
            "multiline import should be parsed"
        );

        let imp = analysis
            .imports
            .iter()
            .find(|i| i.source == "pkg.sub.adapter")
            .expect("pkg.sub.adapter import should exist");

        // Should have extracted the symbol
        assert_eq!(imp.symbols.len(), 1, "should have one imported symbol");
        assert_eq!(
            imp.symbols[0].name, "AnthropicMessagesAdapter",
            "symbol name should match"
        );

        // Should have resolved to local file
        assert_eq!(
            imp.resolution,
            ImportResolutionKind::Local,
            "should resolve as local"
        );
        assert!(
            imp.resolved_path
                .as_ref()
                .is_some_and(|p| p.contains("adapter.py")),
            "should resolve to adapter.py"
        );
    }

    #[test]
    fn parses_multiline_from_import_multiple_symbols() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("mypackage")).expect("mkdir mypackage");
        std::fs::write(
            root.join("mypackage/models.py"),
            "class Foo:\n    pass\n\nclass Bar:\n    pass\n\nclass Baz:\n    pass\n",
        )
        .expect("write models.py");
        std::fs::write(root.join("mypackage/__init__.py"), "").expect("write init");

        let content = r#"
from mypackage.models import (
    Foo,
    Bar as AliasedBar,
    Baz,  # trailing comma
)

x = Foo()
"#;

        let path = root.join("main.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "main.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );

        let imp = analysis
            .imports
            .iter()
            .find(|i| i.source == "mypackage.models")
            .expect("mypackage.models import should exist");

        assert_eq!(imp.symbols.len(), 3, "should have three imported symbols");

        let foo = imp.symbols.iter().find(|s| s.name == "Foo");
        assert!(foo.is_some(), "Foo should be imported");
        assert!(foo.unwrap().alias.is_none(), "Foo should have no alias");

        let bar = imp.symbols.iter().find(|s| s.name == "Bar");
        assert!(bar.is_some(), "Bar should be imported");
        assert_eq!(
            bar.unwrap().alias.as_deref(),
            Some("AliasedBar"),
            "Bar should have alias AliasedBar"
        );

        let baz = imp.symbols.iter().find(|s| s.name == "Baz");
        assert!(baz.is_some(), "Baz should be imported");
    }

    #[test]
    fn parses_multiline_from_import_in_init_as_reexport() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();
        std::fs::create_dir_all(root.join("chat/anthropic")).expect("mkdir");
        std::fs::write(
            root.join("chat/anthropic/anthropic_messages_adapter.py"),
            "class AnthropicMessagesAdapter:\n    pass\n",
        )
        .expect("write adapter");
        std::fs::write(root.join("chat/__init__.py"), "").expect("write chat init");
        std::fs::write(root.join("chat/anthropic/__init__.py"), "").expect("write anthropic init");

        // This is what __init__.py often looks like - multiline import for re-export
        let content = r#"
from .anthropic_messages_adapter import (
    AnthropicMessagesAdapter,
)
"#;

        let path = root.join("chat/anthropic/__init__.py");
        let analysis = analyze_py_file(
            content,
            &path,
            root,
            Some(&py_exts()),
            "chat/anthropic/__init__.py".to_string(),
            &[root.to_path_buf()],
            python_stdlib_set(),
        );

        // Should recognize this as a re-export
        assert!(
            !analysis.reexports.is_empty(),
            "should have re-exports from __init__.py"
        );

        let reexport = analysis
            .reexports
            .iter()
            .find(|r| r.source == ".anthropic_messages_adapter")
            .expect("should have reexport from .anthropic_messages_adapter");

        match &reexport.kind {
            ReexportKind::Named(names) => {
                assert!(
                    names.iter().any(|(_, e)| e == "AnthropicMessagesAdapter"),
                    "should re-export AnthropicMessagesAdapter"
                );
            }
            other => panic!("expected named reexport, got {:?}", other),
        }

        // Should also appear in exports
        assert!(
            analysis
                .exports
                .iter()
                .any(|e| e.name == "AnthropicMessagesAdapter" && e.kind == "reexport"),
            "AnthropicMessagesAdapter should be in exports as reexport"
        );
    }

    #[test]
    fn all_list_does_not_duplicate_class_exports() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        // Common Python pattern: class definition + __all__ list
        let content = r#"
__all__ = ["Foo", "Bar"]

class Foo:
    pass

class Bar:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        // Should have exactly 2 exports (Foo and Bar from class definitions)
        // NOT 4 (which would happen if __all__ duplicated them)
        let export_names: Vec<_> = analysis.exports.iter().map(|e| &e.name).collect();
        assert_eq!(
            export_names.len(),
            2,
            "should have 2 exports, not duplicates: {:?}",
            export_names
        );

        // Both should be class exports, not __all__ exports
        let foo_export = analysis.exports.iter().find(|e| e.name == "Foo");
        assert!(foo_export.is_some());
        assert_eq!(
            foo_export.unwrap().kind,
            "class",
            "Foo should be class export, not __all__"
        );
    }

    #[test]
    fn all_list_adds_exports_not_defined_in_file() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        // __all__ can export names imported from elsewhere (re-export pattern)
        let content = r#"
from .submodule import ExternalClass

__all__ = ["ExternalClass", "LocalClass"]

class LocalClass:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let export_names: Vec<_> = analysis.exports.iter().map(|e| &e.name).collect();

        // LocalClass should be class export
        let local = analysis.exports.iter().find(|e| e.name == "LocalClass");
        assert!(local.is_some());
        assert_eq!(local.unwrap().kind, "class");

        // ExternalClass should be __all__ export (not defined locally)
        let external = analysis.exports.iter().find(|e| e.name == "ExternalClass");
        assert!(
            external.is_some(),
            "ExternalClass should be in exports: {:?}",
            export_names
        );
        assert_eq!(
            external.unwrap().kind,
            "__all__",
            "ExternalClass should be __all__ export since not defined locally"
        );
    }

    #[test]
    fn parses_function_params() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
def simple(x, y):
    pass

def typed(x: int, y: str):
    pass

def with_defaults(x: int = 5, y: str = 'hello'):
    pass

def variadic(*args, **kwargs):
    pass

def typed_variadic(*args: tuple, **kwargs: dict):
    pass

def mixed(self, x: int, y: str = 'default', *args, **kwargs):
    pass

async def async_typed(request: Request, db: Database) -> Response:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        // Test simple function
        let simple = analysis.exports.iter().find(|e| e.name == "simple");
        assert!(simple.is_some(), "simple function should be exported");
        let simple_params = &simple.unwrap().params;
        assert_eq!(simple_params.len(), 2);
        assert_eq!(simple_params[0].name, "x");
        assert!(simple_params[0].type_annotation.is_none());
        assert!(!simple_params[0].has_default);

        // Test typed function
        let typed = analysis.exports.iter().find(|e| e.name == "typed");
        assert!(typed.is_some());
        let typed_params = &typed.unwrap().params;
        assert_eq!(typed_params.len(), 2);
        assert_eq!(typed_params[0].name, "x");
        assert_eq!(typed_params[0].type_annotation.as_deref(), Some("int"));
        assert_eq!(typed_params[1].type_annotation.as_deref(), Some("str"));

        // Test function with defaults
        let with_defaults = analysis.exports.iter().find(|e| e.name == "with_defaults");
        assert!(with_defaults.is_some());
        let wd_params = &with_defaults.unwrap().params;
        assert!(wd_params[0].has_default);
        assert!(wd_params[1].has_default);

        // Test variadic function
        let variadic = analysis.exports.iter().find(|e| e.name == "variadic");
        assert!(variadic.is_some());
        let var_params = &variadic.unwrap().params;
        assert_eq!(var_params.len(), 2);
        assert_eq!(var_params[0].name, "*args");
        assert_eq!(var_params[1].name, "**kwargs");

        // Test mixed function
        let mixed = analysis.exports.iter().find(|e| e.name == "mixed");
        assert!(mixed.is_some());
        let mixed_params = &mixed.unwrap().params;
        assert_eq!(mixed_params.len(), 5);
        assert_eq!(mixed_params[0].name, "self");
        assert_eq!(mixed_params[1].name, "x");
        assert_eq!(mixed_params[1].type_annotation.as_deref(), Some("int"));
        assert!(!mixed_params[1].has_default);
        assert_eq!(mixed_params[2].name, "y");
        assert!(mixed_params[2].has_default);
        assert_eq!(mixed_params[3].name, "*args");
        assert_eq!(mixed_params[4].name, "**kwargs");

        // Test async function
        let async_typed = analysis.exports.iter().find(|e| e.name == "async_typed");
        assert!(async_typed.is_some());
        let async_params = &async_typed.unwrap().params;
        assert_eq!(async_params.len(), 2);
        assert_eq!(async_params[0].name, "request");
        assert_eq!(async_params[0].type_annotation.as_deref(), Some("Request"));
        assert_eq!(async_params[1].type_annotation.as_deref(), Some("Database"));
    }

    #[test]
    fn parses_complex_type_annotations() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path();

        let content = r#"
def generic(items: List[Dict[str, Any]], callback: Callable[[int], bool]) -> Optional[str]:
    pass
"#;

        let analysis = analyze_py_file(
            content,
            &root.join("module.py"),
            root,
            Some(&py_exts()),
            "module.py".to_string(),
            &[root.to_path_buf()],
            &HashSet::new(),
        );

        let generic = analysis.exports.iter().find(|e| e.name == "generic");
        assert!(generic.is_some());
        let params = &generic.unwrap().params;
        assert_eq!(params.len(), 2);
        assert_eq!(params[0].name, "items");
        assert_eq!(
            params[0].type_annotation.as_deref(),
            Some("List[Dict[str, Any]]")
        );
        assert_eq!(params[1].name, "callback");
        assert_eq!(
            params[1].type_annotation.as_deref(),
            Some("Callable[[int], bool]")
        );
    }
}