sqry-lang-python 8.0.4

python language plugin for sqry
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
use std::{collections::HashMap, path::Path};

use sqry_core::graph::unified::StagingGraph;
use sqry_core::graph::unified::build::GraphBuildHelper;
use sqry_core::graph::unified::edge::FfiConvention;
use sqry_core::graph::unified::node::NodeId as UnifiedNodeId;
use sqry_core::graph::{GraphBuilder, GraphBuilderError, GraphResult, Language, Span};
use tree_sitter::{Node, Tree};

use super::local_scopes;

const DEFAULT_SCOPE_DEPTH: usize = 4;
const STD_C_MODULES: &[&str] = &[
    "_ctypes",
    "_socket",
    "_ssl",
    "_hashlib",
    "_json",
    "_pickle",
    "_struct",
    "_sqlite3",
    "_decimal",
    "_lzma",
    "_bz2",
    "_zlib",
    "_elementtree",
    "_csv",
    "_datetime",
    "_heapq",
    "_bisect",
    "_random",
    "_collections",
    "_functools",
    "_itertools",
    "_operator",
    "_io",
    "_thread",
    "_multiprocessing",
    "_posixsubprocess",
    "_asyncio",
    "array",
    "math",
    "cmath",
];
const THIRD_PARTY_C_PACKAGES: &[&str] = &[
    "numpy",
    "pandas",
    "scipy",
    "sklearn",
    "cv2",
    "PIL",
    "torch",
    "tensorflow",
    "lxml",
    "psycopg2",
    "MySQLdb",
    "sqlite3",
    "cryptography",
    "bcrypt",
    "regex",
    "ujson",
    "orjson",
    "msgpack",
    "greenlet",
    "gevent",
    "uvloop",
];

/// Graph builder for Python files using unified `CodeGraph` architecture.
#[derive(Debug, Clone, Copy)]
pub struct PythonGraphBuilder {
    max_scope_depth: usize,
}

impl Default for PythonGraphBuilder {
    fn default() -> Self {
        Self {
            max_scope_depth: DEFAULT_SCOPE_DEPTH,
        }
    }
}

impl PythonGraphBuilder {
    #[must_use]
    pub fn new(max_scope_depth: usize) -> Self {
        Self { max_scope_depth }
    }
}

impl GraphBuilder for PythonGraphBuilder {
    fn build_graph(
        &self,
        tree: &Tree,
        content: &[u8],
        file: &Path,
        staging: &mut StagingGraph,
    ) -> GraphResult<()> {
        // Create helper for staging graph population
        let mut helper = GraphBuildHelper::new(staging, file, Language::Python);

        // Build AST graph for call context tracking
        let ast_graph = ASTGraph::from_tree(tree, content, self.max_scope_depth).map_err(|e| {
            GraphBuilderError::ParseError {
                span: Span::default(),
                reason: e,
            }
        })?;

        // Check if __all__ is defined in the module
        let has_all = has_all_assignment(tree.root_node(), content);

        // Build local variable scope tree
        let mut scope_tree = local_scopes::build(tree.root_node(), content)?;

        // Create recursion guard for tree walking
        let recursion_limits =
            sqry_core::config::RecursionLimits::load_or_default().map_err(|e| {
                GraphBuilderError::ParseError {
                    span: Span::default(),
                    reason: format!("Failed to load recursion limits: {e}"),
                }
            })?;
        let file_ops_depth = recursion_limits.effective_file_ops_depth().map_err(|e| {
            GraphBuilderError::ParseError {
                span: Span::default(),
                reason: format!("Invalid file_ops_depth configuration: {e}"),
            }
        })?;
        let mut guard =
            sqry_core::query::security::RecursionGuard::new(file_ops_depth).map_err(|e| {
                GraphBuilderError::ParseError {
                    span: Span::default(),
                    reason: format!("Failed to create recursion guard: {e}"),
                }
            })?;

        // Walk tree to find functions, classes, methods, calls, and imports
        walk_tree_for_graph(
            tree.root_node(),
            content,
            &ast_graph,
            &mut helper,
            has_all,
            &mut guard,
            &mut scope_tree,
        )?;

        Ok(())
    }

    fn language(&self) -> Language {
        Language::Python
    }
}

/// Check if the module defines `__all__`.
fn has_all_assignment(node: Node, content: &[u8]) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "expression_statement" {
            // Check for __all__ assignment
            let assignment = child
                .children(&mut child.walk())
                .find(|c| c.kind() == "assignment" || c.kind() == "augmented_assignment");

            if let Some(assignment) = assignment
                && let Some(left) = assignment.child_by_field_name("left")
                && let Ok(left_text) = left.utf8_text(content)
                && left_text.trim() == "__all__"
            {
                return true;
            }
        }
    }
    false
}

/// Walk the tree and populate the staging graph.
/// # Errors
///
/// Returns [`GraphBuilderError`] if graph operations fail or recursion depth exceeds the guard's limit.
#[allow(clippy::too_many_lines)]
fn walk_tree_for_graph(
    node: Node,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
    has_all: bool,
    guard: &mut sqry_core::query::security::RecursionGuard,
    scope_tree: &mut local_scopes::PythonScopeTree,
) -> GraphResult<()> {
    guard.enter().map_err(|e| GraphBuilderError::ParseError {
        span: Span::default(),
        reason: format!("Recursion limit exceeded: {e}"),
    })?;

    match node.kind() {
        "class_definition" => {
            // Extract class name
            if let Some(name_node) = node.child_by_field_name("name")
                && let Ok(class_name) = name_node.utf8_text(content)
            {
                let span = span_from_node(node);

                // Build qualified class name from scope
                let qualified_name = class_name.to_string();

                // Add class node
                let class_id = helper.add_class(&qualified_name, Some(span));

                // Process inheritance (base classes)
                process_class_inheritance(node, content, class_id, helper);

                // Note: Class body annotations are processed via normal recursion in walk_tree_for_graph

                // Export public classes at module level (only if __all__ is not defined)
                if !has_all && is_module_level(node) && is_public_name(class_name) {
                    export_from_file_module(helper, class_id);
                }
            }
        }
        "expression_statement" => {
            // Check for __all__ assignment (exports)
            process_all_assignment(node, content, helper);

            // Check for annotated assignments (type hints on variables)
            process_annotated_assignment(node, content, ast_graph, helper);
        }
        "function_definition" => {
            // Extract function context from AST graph
            if let Some(call_context) = ast_graph.get_callable_context(node.id()) {
                let span = span_from_node(node);

                // Extract visibility from function name
                let func_name = node
                    .child_by_field_name("name")
                    .and_then(|n| n.utf8_text(content).ok())
                    .unwrap_or("");
                let visibility = extract_visibility_from_name(func_name);

                // Check if this is a property (has @property decorator)
                let is_property = has_property_decorator(node, content);

                // Extract return type annotation for signature
                let return_type = extract_return_type_annotation(node, content);

                // Add function/method/property node
                let function_id = if is_property && call_context.is_method {
                    // Property node
                    helper.add_node_with_visibility(
                        &call_context.qualified_name,
                        Some(span),
                        sqry_core::graph::unified::node::NodeKind::Property,
                        Some(visibility),
                    )
                } else if call_context.is_method {
                    // Regular method with signature
                    if return_type.is_some() {
                        helper.add_method_with_signature(
                            &call_context.qualified_name,
                            Some(span),
                            call_context.is_async,
                            false, // Python doesn't have static methods in the same way
                            Some(visibility),
                            return_type.as_deref(),
                        )
                    } else {
                        helper.add_method_with_visibility(
                            &call_context.qualified_name,
                            Some(span),
                            call_context.is_async,
                            false,
                            Some(visibility),
                        )
                    }
                } else {
                    // Regular function with signature
                    if return_type.is_some() {
                        helper.add_function_with_signature(
                            &call_context.qualified_name,
                            Some(span),
                            call_context.is_async,
                            false, // Python doesn't have unsafe
                            Some(visibility),
                            return_type.as_deref(),
                        )
                    } else {
                        helper.add_function_with_visibility(
                            &call_context.qualified_name,
                            Some(span),
                            call_context.is_async,
                            false,
                            Some(visibility),
                        )
                    }
                };

                // Check for HTTP route decorators (Flask/FastAPI)
                if let Some((http_method, route_path)) = extract_route_decorator_info(node, content)
                {
                    let endpoint_name = format!("route::{http_method}::{route_path}");
                    let endpoint_id = helper.add_endpoint(&endpoint_name, Some(span));
                    helper.add_contains_edge(endpoint_id, function_id);
                }

                // Process parameters to create TypeOf and Reference edges for type hints
                process_function_parameters(node, content, ast_graph, helper);

                // Export public functions at module level (not methods, only if __all__ is not defined)
                if !has_all
                    && !call_context.is_method
                    && is_module_level(node)
                    && let Some(name_node) = node.child_by_field_name("name")
                    && let Ok(func_name) = name_node.utf8_text(content)
                    && is_public_name(func_name)
                {
                    export_from_file_module(helper, function_id);
                }
            }
        }
        "call" => {
            // Check for FFI patterns first (ctypes, cffi)
            let is_ffi = build_ffi_call_edge(ast_graph, node, content, helper)?;
            if !is_ffi {
                // Not an FFI call - build regular call edge
                if let Ok(Some((caller_qname, callee_qname, argument_count, is_awaited))) =
                    build_call_for_staging(ast_graph, node, content)
                {
                    // Ensure both nodes exist
                    let call_context = ast_graph.get_callable_context(node.id());
                    let is_async = call_context.is_some_and(|c| c.is_async);

                    let source_id = helper.ensure_function(&caller_qname, None, is_async, false);
                    let target_id = helper.ensure_function(&callee_qname, None, false, false);

                    // Add call edge
                    let call_span = span_from_node(node);
                    let argument_count = u8::try_from(argument_count).unwrap_or(u8::MAX);
                    helper.add_call_edge_full_with_span(
                        source_id,
                        target_id,
                        argument_count,
                        is_awaited,
                        vec![call_span],
                    );
                }
            }
        }
        "import_statement" | "import_from_statement" => {
            // Build import edge
            if let Ok(Some((from_qname, to_qname))) =
                build_import_for_staging(node, content, helper)
            {
                // Ensure both module nodes exist
                let from_id = helper.add_import(&from_qname, None);
                let to_id = helper.add_import(&to_qname, Some(span_from_node(node)));

                // Add import edge
                helper.add_import_edge(from_id, to_id);

                // Check if this imports a known native C extension module
                if is_native_extension_import(&to_qname) {
                    build_native_import_ffi_edge(&to_qname, node, helper);
                }
            }
        }
        "identifier" => {
            // Local variable reference tracking
            local_scopes::handle_identifier_for_reference(node, content, scope_tree, helper);
        }
        _ => {}
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_tree_for_graph(
            child, content, ast_graph, helper, has_all, guard, scope_tree,
        )?;
    }

    guard.exit();
    Ok(())
}

/// Build call edge information for the staging graph.
fn build_call_for_staging(
    ast_graph: &ASTGraph,
    call_node: Node<'_>,
    content: &[u8],
) -> GraphResult<Option<(String, String, usize, bool)>> {
    // Get or create module-level context for top-level calls
    let module_context;
    let call_context = if let Some(ctx) = ast_graph.get_callable_context(call_node.id()) {
        ctx
    } else {
        // Create synthetic module-level context for top-level calls
        module_context = CallContext {
            qualified_name: "<module>".to_string(),
            span: (0, content.len()),
            is_async: false,
            is_method: false,
            class_name: None,
        };
        &module_context
    };

    let Some(callee_expr) = call_node.child_by_field_name("function") else {
        return Ok(None);
    };

    let callee_text = callee_expr
        .utf8_text(content)
        .map_err(|_| GraphBuilderError::ParseError {
            span: span_from_node(call_node),
            reason: "failed to read call expression".to_string(),
        })?
        .trim()
        .to_string();

    if callee_text.is_empty() {
        return Ok(None);
    }

    let callee_simple = simple_name(&callee_text);
    if callee_simple.is_empty() {
        return Ok(None);
    }

    // Derive qualified callee name with proper self resolution
    let caller_qname = call_context.qualified_name();
    let target_qname = if let Some(method_name) = callee_text.strip_prefix("self.") {
        // Resolve self.method() to ClassName.method()
        if let Some(class_name) = &call_context.class_name {
            format!("{}.{}", class_name, simple_name(method_name))
        } else {
            callee_simple.to_string()
        }
    } else {
        callee_simple.to_string()
    };

    let argument_count = count_arguments(call_node);
    let is_awaited = is_awaited_call(call_node);
    Ok(Some((
        caller_qname,
        target_qname,
        argument_count,
        is_awaited,
    )))
}

/// Build import edge information for the staging graph.
fn build_import_for_staging(
    import_node: Node<'_>,
    content: &[u8],
    helper: &GraphBuildHelper,
) -> GraphResult<Option<(String, String)>> {
    // Extract the raw module name from the AST
    let raw_module_name = if import_node.kind() == "import_statement" {
        import_node
            .child_by_field_name("name")
            .and_then(|n| extract_module_name(n, content))
    } else if import_node.kind() == "import_from_statement" {
        import_node
            .child_by_field_name("module_name")
            .and_then(|n| extract_module_name(n, content))
    } else {
        None
    };

    // Handle relative imports with no module name
    let module_name = if raw_module_name.is_none() && import_node.kind() == "import_from_statement"
    {
        if let Ok(import_text) = import_node.utf8_text(content) {
            if let Some(from_idx) = import_text.find("from") {
                if let Some(import_idx) = import_text.find("import") {
                    let between = import_text[from_idx + 4..import_idx].trim();
                    if between.starts_with('.') {
                        Some(between.to_string())
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    } else {
        raw_module_name
    };

    let Some(module_name) = module_name else {
        return Ok(None);
    };

    if module_name.is_empty() {
        return Ok(None);
    }

    // Resolve the import path to a canonical module identifier
    let resolved_path = sqry_core::graph::resolve_python_import(
        std::path::Path::new(helper.file_path()),
        &module_name,
        import_node.kind() == "import_from_statement",
    )?;

    // Return from/to qualified names
    Ok(Some((helper.file_path().to_string(), resolved_path)))
}

fn span_from_node(node: Node<'_>) -> Span {
    let start = node.start_position();
    let end = node.end_position();
    Span::new(
        sqry_core::graph::node::Position::new(start.row, start.column),
        sqry_core::graph::node::Position::new(end.row, end.column),
    )
}

fn count_arguments(call_node: Node<'_>) -> usize {
    call_node
        .child_by_field_name("arguments")
        .map_or(0, |args| {
            args.named_children(&mut args.walk())
                .filter(|child| {
                    // Count actual arguments, not commas or parentheses
                    !matches!(child.kind(), "," | "(" | ")")
                })
                .count()
        })
}

fn is_awaited_call(call_node: Node<'_>) -> bool {
    let mut current = call_node.parent();
    while let Some(node) = current {
        let kind = node.kind();
        if kind == "await" || kind == "await_expression" {
            return true;
        }
        current = node.parent();
    }
    false
}

/// Extract the simple name from a dotted identifier (for general call targets).
///
/// Takes the last component after splitting by dots.
/// Used for qualified names like "module.func" → "func" or "obj.method" → "method".
fn simple_name(qualified: &str) -> &str {
    qualified.split('.').next_back().unwrap_or(qualified)
}

/// Extract a simple library name from an FFI library path.
///
/// For library paths with file extensions, extracts the base name before the extension.
/// This prevents different libraries with the same extension (lib1.so, lib2.so) from
/// colliding as duplicate "so" targets.
///
/// Handles:
/// - Full paths: "/opt/v1.2/libfoo.so" → "libfoo"
/// - Relative paths: "libs/lib1.so" → "lib1"
/// - Versioned libs: "libc.so.6" → "libc"
/// - Simple names: "kernel32" → "kernel32"
/// - Variable refs: "$libname" → "$libname"
fn ffi_library_simple_name(library_path: &str) -> String {
    use std::path::Path;

    // Strip directory components first (handles /opt/v1.2/libfoo.so)
    let filename = Path::new(library_path)
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(library_path);

    // Handle versioned .so files first (libc.so.6 → libc)
    if let Some(so_pos) = filename.find(".so.") {
        return filename[..so_pos].to_string();
    }

    // Handle standard library extensions
    if let Some(dot_pos) = filename.find('.') {
        let extension = &filename[dot_pos + 1..];

        // Check for known library extensions
        if extension == "so" || extension == "dll" || extension == "dylib" {
            // Extract base name before extension
            return filename[..dot_pos].to_string();
        }
    }

    // No library extension found - return filename as-is
    filename.to_string()
}

/// Check if a name is public (does not start with underscore).
///
/// In Python, names starting with a single underscore are considered private by convention.
/// Names starting with double underscores trigger name mangling in classes.
/// Public names do not start with an underscore.
fn is_public_name(name: &str) -> bool {
    !name.starts_with('_')
}

/// Check if a node is at module level (direct child of the module body).
///
/// In tree-sitter Python AST, module-level items are direct children of the root "module" node.
/// We check if the parent is "module" to determine module-level scope.
fn is_module_level(node: Node<'_>) -> bool {
    // Walk up the tree to find the immediate container
    let mut current = node.parent();
    while let Some(parent) = current {
        match parent.kind() {
            "module" => return true,
            "function_definition" | "class_definition" => return false,
            _ => current = parent.parent(),
        }
    }
    false
}

/// Export a symbol from the file module.
///
/// File-level module name for exports/imports.
/// Distinct from `<module>` to avoid conflicts with top-level call context.
const FILE_MODULE_NAME: &str = "<file_module>";

fn export_from_file_module(
    helper: &mut GraphBuildHelper,
    exported: sqry_core::graph::unified::node::NodeId,
) {
    let module_id = helper.add_module(FILE_MODULE_NAME, None);
    helper.add_export_edge(module_id, exported);
}

/// Extract module name from a `dotted_name`, `aliased_import`, or `relative_import` node
///
/// For `import numpy as np`, the "name" field is an `aliased_import` node with structure:
/// `aliased_import { name: dotted_name("numpy"), alias: identifier("np") }`
/// We need to extract just "numpy", not "numpy as np".
fn extract_module_name(node: Node<'_>, content: &[u8]) -> Option<String> {
    // Handle aliased imports: `import numpy as np` -> extract "numpy"
    if node.kind() == "aliased_import" {
        // The "name" field of aliased_import contains the actual module name
        return node
            .child_by_field_name("name")
            .and_then(|name_node| name_node.utf8_text(content).ok())
            .map(std::string::ToString::to_string);
    }

    // Regular dotted_name or identifier
    node.utf8_text(content)
        .ok()
        .map(std::string::ToString::to_string)
}

// ============================================================================
// Exports - __all__ assignment handling
// ============================================================================

/// Process `__all__ = ['name1', 'name2']` assignments to create export edges.
///
/// Python's `__all__` list explicitly defines the public API of a module.
/// Each name in the list gets an Export edge from the module to the exported symbol.
fn process_all_assignment(node: Node<'_>, content: &[u8], helper: &mut GraphBuildHelper) {
    // expression_statement contains an assignment child
    let assignment = node
        .children(&mut node.walk())
        .find(|child| child.kind() == "assignment" || child.kind() == "augmented_assignment");

    let Some(assignment) = assignment else {
        return;
    };

    // Check if left side is __all__
    let left = assignment.child_by_field_name("left");
    let Some(left) = left else {
        return;
    };

    let Ok(left_text) = left.utf8_text(content) else {
        return;
    };

    if left_text.trim() != "__all__" {
        return;
    }

    // Get the right side (should be a list)
    let right = assignment.child_by_field_name("right");
    let Some(right) = right else {
        return;
    };

    // Handle list or tuple literal (both valid for __all__)
    if right.kind() == "list" || right.kind() == "tuple" {
        process_all_list(right, content, helper);
    }
}

/// Process a list/tuple of exported names from __all__.
fn process_all_list(list_node: Node<'_>, content: &[u8], helper: &mut GraphBuildHelper) {
    for child in list_node.children(&mut list_node.walk()) {
        // Look for string literals
        if child.kind() == "string"
            && let Some(export_name) = extract_string_content(child, content)
            && !export_name.is_empty()
        {
            // Create a node for the exported symbol
            // We use add_function here as a generic symbol; the actual type
            // will be resolved later by cross-file analysis
            let span = span_from_node(child);
            let export_id = helper.add_function(&export_name, Some(span), false, false);

            // Add export edge (Direct export, no alias for Python __all__)
            export_from_file_module(helper, export_id);
        }
    }
}

/// Extract the content of a string literal node (removing quotes).
fn extract_string_content(string_node: Node<'_>, content: &[u8]) -> Option<String> {
    // String nodes contain string_content or string_start/string_content/string_end
    // Try to get the full text and strip quotes
    let Ok(text) = string_node.utf8_text(content) else {
        return None;
    };

    let text = text.trim();

    // Handle various Python string formats: 'x', "x", '''x''', """x""", r'x', etc.
    let stripped = text
        .trim_start_matches(|c: char| {
            c == 'r'
                || c == 'b'
                || c == 'f'
                || c == 'u'
                || c == 'R'
                || c == 'B'
                || c == 'F'
                || c == 'U'
        })
        .trim_start_matches("'''")
        .trim_end_matches("'''")
        .trim_start_matches("\"\"\"")
        .trim_end_matches("\"\"\"")
        .trim_start_matches('\'')
        .trim_end_matches('\'')
        .trim_start_matches('"')
        .trim_end_matches('"');

    Some(stripped.to_string())
}

// ============================================================================
// OOP - Inheritance handling
// ============================================================================

/// Process class inheritance to create Inherits edges.
///
/// Python supports multiple inheritance: `class Child(Parent1, Parent2):`
/// Each base class gets an Inherits edge from the child class.
fn process_class_inheritance(
    class_node: Node<'_>,
    content: &[u8],
    class_id: UnifiedNodeId,
    helper: &mut GraphBuildHelper,
) {
    // In Python AST, base classes are in the superclasses field (argument_list)
    // class_definition has a "superclasses" field containing argument_list
    let superclasses = class_node.child_by_field_name("superclasses");

    let Some(superclasses) = superclasses else {
        return;
    };

    // argument_list contains the base classes
    for child in superclasses.children(&mut superclasses.walk()) {
        if child.kind() == "keyword_argument" {
            // Skip keyword arguments like metaclass=ABCMeta.
            continue;
        }

        match child.kind() {
            "identifier" => {
                // Simple base class: class Child(Parent):
                if let Ok(base_name) = child.utf8_text(content) {
                    let base_name = base_name.trim();
                    if !base_name.is_empty() {
                        let span = span_from_node(child);
                        let base_id = helper.add_class(base_name, Some(span));
                        helper.add_inherits_edge(class_id, base_id);
                    }
                }
            }
            "attribute" => {
                // Qualified base class: class Child(module.Parent):
                if let Ok(base_name) = child.utf8_text(content) {
                    let base_name = base_name.trim();
                    if !base_name.is_empty() {
                        let span = span_from_node(child);
                        let base_id = helper.add_class(base_name, Some(span));
                        helper.add_inherits_edge(class_id, base_id);
                    }
                }
            }
            "call" => {
                // Parameterized base class with call syntax: class Child(SomeBase(arg)):
                // Extract the function being called
                if let Some(func) = child.child_by_field_name("function")
                    && let Ok(base_name) = func.utf8_text(content)
                {
                    let base_name = base_name.trim();
                    if !base_name.is_empty() {
                        let span = span_from_node(child);
                        let base_id = helper.add_class(base_name, Some(span));
                        helper.add_inherits_edge(class_id, base_id);
                    }
                }
            }
            "subscript" => {
                // Generic base class: class Child(Generic[T]): or class Child(List[int]):
                // Extract the base type from the subscript (value field)
                if let Some(value) = child.child_by_field_name("value")
                    && let Ok(base_name) = value.utf8_text(content)
                {
                    let base_name = base_name.trim();
                    if !base_name.is_empty() {
                        let span = span_from_node(child);
                        let base_id = helper.add_class(base_name, Some(span));
                        helper.add_inherits_edge(class_id, base_id);
                    }
                }
            }
            _ => {}
        }
    }
}

// ============================================================================
// AST Graph - tracks callable contexts (functions, methods, classes)
// ============================================================================

#[derive(Debug, Clone)]
struct CallContext {
    qualified_name: String,
    #[allow(dead_code)] // Reserved for scope analysis
    span: (usize, usize),
    is_async: bool,
    is_method: bool,
    class_name: Option<String>,
}

impl CallContext {
    fn qualified_name(&self) -> String {
        self.qualified_name.clone()
    }
}

struct ASTGraph {
    contexts: Vec<CallContext>,
    node_to_context: HashMap<usize, usize>,
}

impl ASTGraph {
    fn from_tree(tree: &Tree, content: &[u8], max_depth: usize) -> Result<Self, String> {
        let mut contexts = Vec::new();
        let mut node_to_context = HashMap::new();
        let mut scope_stack: Vec<String> = Vec::new();
        let mut class_stack: Vec<String> = Vec::new();

        walk_ast(
            tree.root_node(),
            content,
            &mut contexts,
            &mut node_to_context,
            &mut scope_stack,
            &mut class_stack,
            max_depth,
        )?;

        Ok(Self {
            contexts,
            node_to_context,
        })
    }

    #[allow(dead_code)] // Reserved for future context queries
    fn contexts(&self) -> &[CallContext] {
        &self.contexts
    }

    fn get_callable_context(&self, node_id: usize) -> Option<&CallContext> {
        self.node_to_context
            .get(&node_id)
            .and_then(|idx| self.contexts.get(*idx))
    }
}

fn walk_ast(
    node: Node,
    content: &[u8],
    contexts: &mut Vec<CallContext>,
    node_to_context: &mut HashMap<usize, usize>,
    scope_stack: &mut Vec<String>,
    class_stack: &mut Vec<String>,
    max_depth: usize,
) -> Result<(), String> {
    if scope_stack.len() > max_depth {
        return Ok(());
    }

    match node.kind() {
        "class_definition" => {
            let name_node = node
                .child_by_field_name("name")
                .ok_or_else(|| "class_definition missing name".to_string())?;
            let class_name = name_node
                .utf8_text(content)
                .map_err(|_| "failed to read class name".to_string())?;

            // Build qualified class name
            let qualified_class = if scope_stack.is_empty() {
                class_name.to_string()
            } else {
                format!("{}.{}", scope_stack.join("."), class_name)
            };

            class_stack.push(qualified_class.clone());
            scope_stack.push(class_name.to_string());

            // Recurse into class body
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for child in body.children(&mut cursor) {
                    walk_ast(
                        child,
                        content,
                        contexts,
                        node_to_context,
                        scope_stack,
                        class_stack,
                        max_depth,
                    )?;
                }
            }

            class_stack.pop();
            scope_stack.pop();
        }
        "function_definition" => {
            let name_node = node
                .child_by_field_name("name")
                .ok_or_else(|| "function_definition missing name".to_string())?;
            let func_name = name_node
                .utf8_text(content)
                .map_err(|_| "failed to read function name".to_string())?;

            // Check if async
            let is_async = node
                .children(&mut node.walk())
                .any(|child| child.kind() == "async");

            // Build qualified function name
            let qualified_func = if scope_stack.is_empty() {
                func_name.to_string()
            } else {
                format!("{}.{}", scope_stack.join("."), func_name)
            };

            // Determine if this is a method (inside a class)
            let is_method = !class_stack.is_empty();
            let class_name = class_stack.last().cloned();

            let context_idx = contexts.len();
            contexts.push(CallContext {
                qualified_name: qualified_func.clone(),
                span: (node.start_byte(), node.end_byte()),
                is_async,
                is_method,
                class_name,
            });

            // Associate the function definition node itself with this context
            // This is required so walk_tree_for_graph can find the context
            node_to_context.insert(node.id(), context_idx);

            // Associate all descendants with this context
            if let Some(body) = node.child_by_field_name("body") {
                associate_descendants(body, context_idx, node_to_context);
            }

            scope_stack.push(func_name.to_string());

            // Recurse into function body to find nested functions
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for child in body.children(&mut cursor) {
                    walk_ast(
                        child,
                        content,
                        contexts,
                        node_to_context,
                        scope_stack,
                        class_stack,
                        max_depth,
                    )?;
                }
            }

            scope_stack.pop();
        }
        _ => {
            // Recurse into children for other node types
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                walk_ast(
                    child,
                    content,
                    contexts,
                    node_to_context,
                    scope_stack,
                    class_stack,
                    max_depth,
                )?;
            }
        }
    }

    Ok(())
}

fn associate_descendants(
    node: Node,
    context_idx: usize,
    node_to_context: &mut HashMap<usize, usize>,
) {
    node_to_context.insert(node.id(), context_idx);

    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        node_to_context.insert(current.id(), context_idx);

        let mut cursor = current.walk();
        for child in current.children(&mut cursor) {
            stack.push(child);
        }
    }
}

// ============================================================================
// FFI Detection - ctypes, cffi, and C extensions
// ============================================================================

/// Build FFI edges for call expressions.
///
/// Detects Python FFI patterns:
/// - `ctypes.CDLL('libfoo.so')` / `ctypes.cdll.LoadLibrary('libfoo.so')`
/// - `ctypes.WinDLL('kernel32')` / `ctypes.windll.kernel32`
/// - `ctypes.PyDLL('libpython.so')`
/// - `cffi.FFI().dlopen('libfoo.so')`
/// - `ffi.dlopen('libfoo.so')`
///
/// Returns true if an FFI edge was created, false otherwise.
fn build_ffi_call_edge(
    ast_graph: &ASTGraph,
    call_node: Node<'_>,
    content: &[u8],
    helper: &mut GraphBuildHelper,
) -> GraphResult<bool> {
    let Some(callee_expr) = call_node.child_by_field_name("function") else {
        return Ok(false);
    };

    let callee_text = callee_expr
        .utf8_text(content)
        .map_err(|_| GraphBuilderError::ParseError {
            span: span_from_node(call_node),
            reason: "failed to read call expression".to_string(),
        })?
        .trim();

    // Check for ctypes library loading patterns
    if is_ctypes_load_call(callee_text) {
        return Ok(build_ctypes_ffi_edge(
            ast_graph,
            call_node,
            content,
            callee_text,
            helper,
        ));
    }

    // Check for cffi dlopen patterns
    if is_cffi_dlopen_call(callee_text) {
        return Ok(build_cffi_ffi_edge(ast_graph, call_node, content, helper));
    }

    Ok(false)
}

/// Check if the callee is a ctypes library loading function.
///
/// Narrowed patterns to reduce false positives - only match explicit ctypes paths.
/// Previous: `callee_text.ends_with(".LoadLibrary")` matched too broadly.
///
/// Note: `ctypes.cdll.kernel32` style attribute access patterns are not detected
/// because they're attribute access (not function calls). We only detect explicit
/// library loading function calls like CDLL('lib.so').
fn is_ctypes_load_call(callee_text: &str) -> bool {
    // Direct ctypes constructors (fully qualified)
    callee_text == "ctypes.CDLL"
        || callee_text == "ctypes.WinDLL"
        || callee_text == "ctypes.OleDLL"
        || callee_text == "ctypes.PyDLL"
        // ctypes.cdll/windll LoadLibrary (fully qualified)
        || callee_text == "ctypes.cdll.LoadLibrary"
        || callee_text == "ctypes.windll.LoadLibrary"
        || callee_text == "ctypes.oledll.LoadLibrary"
        // After `from ctypes import *` or `from ctypes import CDLL, etc.`
        || callee_text == "CDLL"
        || callee_text == "WinDLL"
        || callee_text == "OleDLL"
        || callee_text == "PyDLL"
        // After `from ctypes import cdll` or similar
        || callee_text == "cdll.LoadLibrary"
        || callee_text == "windll.LoadLibrary"
        || callee_text == "oledll.LoadLibrary"
}

/// Check if the callee is a cffi dlopen function.
///
/// Narrowed patterns to reduce false positives - only match known cffi patterns.
/// Previous: `callee_text.ends_with(".dlopen")` matched too broadly.
fn is_cffi_dlopen_call(callee_text: &str) -> bool {
    // Common cffi FFI variable names followed by dlopen
    callee_text == "ffi.dlopen"
        || callee_text == "cffi.dlopen"
        || callee_text == "_ffi.dlopen"
        // FFI() constructor followed by dlopen (chained call)
        // This pattern typically appears as: FFI().dlopen('lib.so')
        // In tree-sitter, the callee text would be the method access part
        // After `from cffi import FFI`
        || callee_text == "FFI().dlopen"
}

/// Build FFI edge for ctypes library loading.
fn build_ctypes_ffi_edge(
    ast_graph: &ASTGraph,
    call_node: Node<'_>,
    content: &[u8],
    callee_text: &str,
    helper: &mut GraphBuildHelper,
) -> bool {
    // Get caller context
    let caller_id = get_ffi_caller_node_id(ast_graph, call_node, content, helper);

    // Determine FFI convention based on the ctypes type
    let convention = if callee_text.contains("WinDLL")
        || callee_text.contains("windll")
        || callee_text.contains("OleDLL")
    {
        FfiConvention::Stdcall
    } else {
        FfiConvention::C
    };

    // Try to extract library name from first argument
    let library_name = extract_ffi_library_name(call_node, content)
        .unwrap_or_else(|| "ctypes::unknown".to_string());

    let ffi_name = format!("native::{}", ffi_library_simple_name(&library_name));
    let ffi_node_id = helper.add_module(&ffi_name, Some(span_from_node(call_node)));

    // Add FFI edge
    helper.add_ffi_edge(caller_id, ffi_node_id, convention);

    true
}

/// Build FFI edge for cffi dlopen.
fn build_cffi_ffi_edge(
    ast_graph: &ASTGraph,
    call_node: Node<'_>,
    content: &[u8],
    helper: &mut GraphBuildHelper,
) -> bool {
    // Get caller context
    let caller_id = get_ffi_caller_node_id(ast_graph, call_node, content, helper);

    // Try to extract library name from first argument
    let library_name =
        extract_ffi_library_name(call_node, content).unwrap_or_else(|| "cffi::unknown".to_string());

    let ffi_name = format!("native::{}", ffi_library_simple_name(&library_name));
    let ffi_node_id = helper.add_module(&ffi_name, Some(span_from_node(call_node)));

    // cffi uses C calling convention
    helper.add_ffi_edge(caller_id, ffi_node_id, FfiConvention::C);

    true
}

/// Get the caller node ID for FFI edges.
fn get_ffi_caller_node_id(
    ast_graph: &ASTGraph,
    node: Node<'_>,
    content: &[u8],
    helper: &mut GraphBuildHelper,
) -> UnifiedNodeId {
    let module_context;
    let call_context = if let Some(ctx) = ast_graph.get_callable_context(node.id()) {
        ctx
    } else {
        module_context = CallContext {
            qualified_name: "<module>".to_string(),
            span: (0, content.len()),
            is_async: false,
            is_method: false,
            class_name: None,
        };
        &module_context
    };

    let caller_span = Some(Span::from_bytes(call_context.span.0, call_context.span.1));
    helper.ensure_function(
        &call_context.qualified_name(),
        caller_span,
        call_context.is_async,
        false,
    )
}

/// Extract the library name from the first argument of a call.
fn extract_ffi_library_name(call_node: Node<'_>, content: &[u8]) -> Option<String> {
    let args = call_node.child_by_field_name("arguments")?;

    let mut cursor = args.walk();
    let first_arg = args
        .children(&mut cursor)
        .find(|child| !matches!(child.kind(), "(" | ")" | ","))?;

    // Handle string literals
    if first_arg.kind() == "string" {
        return extract_string_content(first_arg, content);
    }

    // Handle identifiers (variable names) - we can't resolve them statically
    if first_arg.kind() == "identifier" {
        let text = first_arg.utf8_text(content).ok()?;
        return Some(format!("${}", text.trim())); // Mark as variable reference
    }

    None
}

/// Check if an import statement imports a known native extension module.
///
/// This detects patterns like:
/// - `import numpy` (known C extension)
/// - `from numpy import array` (known C extension)
/// - `import _sqlite3` (private C module)
fn is_native_extension_import(module_name: &str) -> bool {
    // Private C modules (underscore prefix)
    if module_name.starts_with('_') && !module_name.starts_with("__") {
        return true;
    }

    // Check against known modules
    let base_module = module_name.split('.').next().unwrap_or(module_name);

    STD_C_MODULES.contains(&base_module) || THIRD_PARTY_C_PACKAGES.contains(&base_module)
}

/// Build FFI edge for native extension import.
fn build_native_import_ffi_edge(
    module_name: &str,
    import_node: Node<'_>,
    helper: &mut GraphBuildHelper,
) {
    // Create module node for the importing file
    let file_path = helper.file_path().to_string();
    let importer_id = helper.add_module(&file_path, None);

    // Create node for the native module
    let ffi_name = format!("native::{}", simple_name(module_name));
    let ffi_node_id = helper.add_module(&ffi_name, Some(span_from_node(import_node)));

    // Add FFI edge (C convention for Python C extensions)
    helper.add_ffi_edge(importer_id, ffi_node_id, FfiConvention::C);
}

// ============================================================================
// HTTP Route Endpoint Detection - Flask/FastAPI decorators
// ============================================================================

/// HTTP methods recognized in route decorators.
const ROUTE_METHOD_NAMES: &[&str] = &["get", "post", "put", "delete", "patch"];

/// Receiver names recognized as route-capable objects.
///
/// `Flask` uses `app` or `blueprint`, `FastAPI` uses `app` or `router`.
const ROUTE_RECEIVER_NAMES: &[&str] = &["app", "router", "blueprint"];

/// Extract HTTP route information from Flask/FastAPI-style decorators on a function.
///
/// Checks whether the given `function_definition` node is wrapped in a `decorated_definition`
/// and whether any of its decorators match known route patterns:
///
/// - `@app.route('/path')` or `@app.route('/path', methods=['GET'])` -- GET by default
/// - `@app.get('/path')` / `@app.post('/path')` / `@app.put('/path')` / etc.
/// - `@router.get('/path')` (`FastAPI`)
/// - `@blueprint.route('/path')` (Flask blueprints)
///
/// Returns `Some((method, path))` where `method` is the uppercased HTTP method and
/// `path` is the route path string, or `None` if no route decorator is found.
fn extract_route_decorator_info(func_node: Node<'_>, content: &[u8]) -> Option<(String, String)> {
    // The function_definition must be a child of decorated_definition
    let parent = func_node.parent()?;
    if parent.kind() != "decorated_definition" {
        return None;
    }

    // Iterate through decorator children of the decorated_definition
    let mut cursor = parent.walk();
    for child in parent.children(&mut cursor) {
        if child.kind() != "decorator" {
            continue;
        }

        let Ok(decorator_text) = child.utf8_text(content) else {
            continue;
        };
        let decorator_text = decorator_text.trim();

        // Strip the leading '@'
        let without_at = decorator_text.strip_prefix('@')?;

        // Try to parse as a route decorator
        if let Some(result) = parse_route_decorator_text(without_at) {
            return Some(result);
        }
    }

    None
}

/// Parse a single decorator text (without the leading `@`) to extract route information.
///
/// Recognized patterns:
/// - `app.route('/path')` or `app.route('/path', methods=['POST'])`
/// - `app.get('/path')` / `router.post('/path')` / `blueprint.delete('/path')`
///
/// Returns `Some((HTTP_METHOD, path))` or `None`.
fn parse_route_decorator_text(text: &str) -> Option<(String, String)> {
    // Split into receiver.method and argument portion
    // e.g. "app.route('/api/users')" -> ("app.route", "'/api/users')")
    let paren_pos = text.find('(')?;
    let accessor = &text[..paren_pos];
    let args_text = &text[paren_pos + 1..];

    // Split accessor into receiver and method_name
    let dot_pos = accessor.rfind('.')?;
    let receiver = &accessor[..dot_pos];
    let method_name = &accessor[dot_pos + 1..];

    // Check that the receiver is a known route-capable object.
    // Allow dotted receivers (e.g., "api.v1") as long as the final segment matches.
    let receiver_base = receiver.rsplit('.').next().unwrap_or(receiver);
    if !ROUTE_RECEIVER_NAMES.contains(&receiver_base) {
        return None;
    }

    // Extract the route path from the first argument (string literal)
    let path = extract_path_from_decorator_args(args_text)?;

    // Determine the HTTP method
    let method_lower = method_name.to_ascii_lowercase();
    if ROUTE_METHOD_NAMES.contains(&method_lower.as_str()) {
        // Direct method decorator: @app.get('/path') -> GET
        return Some((method_lower.to_ascii_uppercase(), path));
    }

    if method_lower == "route" {
        // Generic route decorator: @app.route('/path', methods=['POST'])
        let http_method = extract_method_from_route_args(args_text);
        return Some((http_method, path));
    }

    None
}

/// Extract the route path string from decorator arguments text.
///
/// The `args_text` parameter is everything after the opening parenthesis of the decorator call,
/// e.g. `'/api/users', methods=['GET'])` or `"/api/items")`.
///
/// Returns the path string with quotes stripped, or `None` if no path is found.
fn extract_path_from_decorator_args(args_text: &str) -> Option<String> {
    let trimmed = args_text.trim();

    // Find the first string literal (single or double quoted)
    let (quote_char, start_pos) = {
        let single_pos = trimmed.find('\'');
        let double_pos = trimmed.find('"');
        match (single_pos, double_pos) {
            (Some(s), Some(d)) => {
                if s < d {
                    ('\'', s)
                } else {
                    ('"', d)
                }
            }
            (Some(s), None) => ('\'', s),
            (None, Some(d)) => ('"', d),
            (None, None) => return None,
        }
    };

    // Find the closing quote
    let after_open = start_pos + 1;
    let close_pos = trimmed[after_open..].find(quote_char)?;
    let path = &trimmed[after_open..after_open + close_pos];

    if path.is_empty() {
        return None;
    }

    Some(path.to_string())
}

/// Extract the HTTP method from `@app.route('/path', methods=['POST'])` style arguments.
///
/// Looks for a `methods=` keyword argument containing a list of method strings.
/// If found, returns the first method in uppercase. Otherwise defaults to `"GET"`.
fn extract_method_from_route_args(args_text: &str) -> String {
    // Look for 'methods' keyword in the arguments
    let Some(methods_pos) = args_text.find("methods") else {
        return "GET".to_string();
    };

    // Find the opening bracket after 'methods='
    let after_methods = &args_text[methods_pos..];
    let Some(bracket_pos) = after_methods.find('[') else {
        return "GET".to_string();
    };

    let after_bracket = &after_methods[bracket_pos + 1..];

    // Find the first string literal inside the bracket
    let method_str = extract_first_string_literal(after_bracket);
    match method_str {
        Some(m) => m.to_ascii_uppercase(),
        None => "GET".to_string(),
    }
}

/// Extract the first single- or double-quoted string literal from the given text.
fn extract_first_string_literal(text: &str) -> Option<String> {
    let trimmed = text.trim();

    let (quote_char, start_pos) = {
        let single_pos = trimmed.find('\'');
        let double_pos = trimmed.find('"');
        match (single_pos, double_pos) {
            (Some(s), Some(d)) => {
                if s < d {
                    ('\'', s)
                } else {
                    ('"', d)
                }
            }
            (Some(s), None) => ('\'', s),
            (None, Some(d)) => ('"', d),
            (None, None) => return None,
        }
    };

    let after_open = start_pos + 1;
    let close_pos = trimmed[after_open..].find(quote_char)?;
    let literal = &trimmed[after_open..after_open + close_pos];

    if literal.is_empty() {
        return None;
    }

    Some(literal.to_string())
}

// ============================================================================
// Property Detection - @property decorator
// ============================================================================

/// Check if a function definition has a `@property` decorator.
///
/// Python AST structure for decorated functions:
/// ```python
/// @property
/// def name(self):
///     return self._name
/// ```
///
/// The tree-sitter AST wraps the `function_definition` in a `decorated_definition` node:
/// ```text
/// (block
///   (decorated_definition
///     decorator: (decorator "@property")
///     definition: (function_definition)))
/// ```
fn has_property_decorator(func_node: Node<'_>, content: &[u8]) -> bool {
    // The function_definition is a child of decorated_definition
    let Some(parent) = func_node.parent() else {
        return false;
    };

    // Check if parent is decorated_definition
    if parent.kind() != "decorated_definition" {
        return false;
    }

    // Look for @property decorator in the decorated_definition
    let mut cursor = parent.walk();
    for child in parent.children(&mut cursor) {
        if child.kind() == "decorator" {
            // Extract decorator text
            if let Ok(decorator_text) = child.utf8_text(content) {
                let decorator_text = decorator_text.trim();
                // Match @property or @property()
                if decorator_text == "@property"
                    || decorator_text.starts_with("@property(")
                    || decorator_text.starts_with("@property (")
                {
                    return true;
                }
            }
        }
    }

    false
}

/// Extract visibility from Python identifier based on naming convention.
///
/// Python uses naming conventions for visibility:
/// - `__name` (dunder) -> private (name mangling)
/// - `_name` (single underscore) -> protected/internal
/// - `name` -> public
fn extract_visibility_from_name(name: &str) -> &'static str {
    if name.starts_with("__") && !name.ends_with("__") {
        "private"
    } else if name.starts_with('_') {
        "protected"
    } else {
        "public"
    }
}

// ============================================================================
// Type Hint Processing - TypeOf and Reference Edges
// ============================================================================

/// Find the containing scope (function/class) for a node to create scope-qualified names.
///
/// This walks up the AST to find the nearest enclosing function or class definition.
/// Returns:
/// - Empty string for module-level
/// - Class name for class-level (e.g., "`MyClass`")
/// - Function qualified name for function-level (e.g., "MyClass.method" or "process")
fn find_containing_scope(node: Node<'_>, content: &[u8], ast_graph: &ASTGraph) -> String {
    let mut current = node;
    let mut found_class_name: Option<String> = None;

    // Walk up the tree to find enclosing function or class
    while let Some(parent) = current.parent() {
        match parent.kind() {
            "function_definition" => {
                // Found enclosing function - get its qualified name
                if let Some(ctx) = ast_graph.get_callable_context(parent.id()) {
                    return ctx.qualified_name.clone();
                }
            }
            "class_definition" => {
                // Remember the class name but continue walking up
                // to check if we're inside a function within this class
                if found_class_name.is_none() {
                    // Extract class name directly from node
                    if let Some(name_node) = parent.child_by_field_name("name")
                        && let Ok(class_name) = name_node.utf8_text(content)
                    {
                        found_class_name = Some(class_name.to_string());
                    }
                }
            }
            _ => {}
        }
        current = parent;
    }

    // If we found a class but no enclosing function, it's a class attribute
    found_class_name.unwrap_or_default()
}

/// Extract return type annotation from a function definition.
///
/// Python AST structure:
/// ```python
/// def foo() -> int:  # return_type field contains type annotation
/// ```
fn extract_return_type_annotation(func_node: Node<'_>, content: &[u8]) -> Option<String> {
    let return_type_node = func_node.child_by_field_name("return_type")?;
    extract_type_from_node(return_type_node, content)
}

/// Process function parameters to create `TypeOf` and Reference edges for type hints.
///
/// Handles:
/// - `def foo(x: int, y: str):` - typed parameters
/// - `def foo(self, x: int):` - skips self/cls
/// - `def foo(x: List[int]):` - extracts base type from generics
fn process_function_parameters(
    func_node: Node<'_>,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    let Some(params_node) = func_node.child_by_field_name("parameters") else {
        return;
    };

    // Get the qualified name of the containing function/method for scope qualification
    let scope_prefix = ast_graph
        .get_callable_context(func_node.id())
        .map_or("", |ctx| ctx.qualified_name.as_str());

    // Iterate through parameters in the parameter_list
    for param in params_node.children(&mut params_node.walk()) {
        // Python tree-sitter uses "typed_parameter" and "typed_default_parameter"
        // but we need to handle the actual structure
        match param.kind() {
            "typed_parameter" | "typed_default_parameter" => {
                process_typed_parameter(param, content, scope_prefix, helper);
            }
            // Untyped parameter - check if it has a type annotation in parent context
            // For now, skip (no type hint)
            // Default parameter without type - skip
            "identifier" | "default_parameter" => {}
            _ => {
                // Other parameter types - try to process if they have type annotations
                // This handles various parameter structures
                if param.child_by_field_name("type").is_some() {
                    process_typed_parameter(param, content, scope_prefix, helper);
                }
            }
        }
    }
}

/// Process a single typed parameter node.
///
/// Creates scope-qualified variable names to prevent cross-scope type contamination.
/// Format: `<scope_prefix>:<param_name>` (e.g., `MyClass.method:x` or `process:x`)
fn process_typed_parameter(
    param: Node<'_>,
    content: &[u8],
    scope_prefix: &str,
    helper: &mut GraphBuildHelper,
) {
    // Extract parameter name (could be in "name" field or as identifier child)
    let param_name = if let Some(name_node) = param.child_by_field_name("name") {
        name_node.utf8_text(content).ok()
    } else {
        // Fallback: look for identifier child
        param
            .children(&mut param.walk())
            .find(|c| c.kind() == "identifier")
            .and_then(|n| n.utf8_text(content).ok())
    };

    let Some(param_name) = param_name else {
        return;
    };

    // Skip self and cls (special method parameters)
    if param_name == "self" || param_name == "cls" {
        return;
    }

    // Extract type annotation
    let Some(type_node) = param.child_by_field_name("type") else {
        return;
    };

    let Some(type_name) = extract_type_from_node(type_node, content) else {
        return;
    };

    // Create scope-qualified parameter name to prevent cross-scope contamination
    // Format: <scope_prefix>:<param_name> (e.g., "MyClass.method:x" or "process:x")
    let qualified_param_name = if scope_prefix.is_empty() {
        // Top-level function parameter
        format!(":{param_name}")
    } else {
        format!("{scope_prefix}:{param_name}")
    };

    // Create parameter variable node with qualified name
    let param_id = helper.add_variable(&qualified_param_name, Some(span_from_node(param)));

    // Create type node
    let type_id = helper.add_type(&type_name, None);

    // Add TypeOf and Reference edges
    helper.add_typeof_edge(param_id, type_id);
    helper.add_reference_edge(param_id, type_id);
}

/// Process annotated assignments to create `TypeOf` and Reference edges.
///
/// Handles:
/// - `user: User = get_user()` - annotated assignment with value
/// - `count: int` - annotated assignment without value
/// - `items: List[str] = []` - generic types
fn process_annotated_assignment(
    expr_stmt_node: Node<'_>,
    content: &[u8],
    ast_graph: &ASTGraph,
    helper: &mut GraphBuildHelper,
) {
    // Get the containing scope for scope qualification
    // For assignments, we need to find the enclosing function/class
    let scope_prefix = find_containing_scope(expr_stmt_node, content, ast_graph);

    // Look for expression_statement containing an assignment
    for child in expr_stmt_node.children(&mut expr_stmt_node.walk()) {
        if child.kind() == "assignment" {
            process_typed_assignment(child, content, &scope_prefix, helper);
        }
    }
}

/// Process a typed assignment node (shared logic for variables and class attributes).
///
/// Creates scope-qualified variable names to prevent cross-scope type contamination.
fn process_typed_assignment(
    assignment_node: Node<'_>,
    content: &[u8],
    scope_prefix: &str,
    helper: &mut GraphBuildHelper,
) {
    // Check if this is a typed assignment by looking for type annotation
    // In Python, annotated assignments look like: name: type = value
    // The AST structure is: assignment { left: identifier, type: type, right: expression }

    let Some(left) = assignment_node.child_by_field_name("left") else {
        return;
    };

    let Some(type_node) = assignment_node.child_by_field_name("type") else {
        return;
    };

    // Extract variable name
    let Ok(var_name) = left.utf8_text(content) else {
        return;
    };

    // Extract type
    let Some(type_name) = extract_type_from_node(type_node, content) else {
        return;
    };

    // Create scope-qualified variable name to prevent cross-scope contamination
    // For class attributes (module-level or class-level), use simple name
    // For function-local variables, use qualified name
    let qualified_var_name = if scope_prefix.is_empty() {
        // Module-level variable
        var_name.to_string()
    } else if scope_prefix.contains('.') && !scope_prefix.contains(':') {
        // Class attribute (scope_prefix is class name without function)
        format!("{scope_prefix}.{var_name}")
    } else {
        // Function-local variable
        format!("{scope_prefix}:{var_name}")
    };

    // Create variable node with qualified name
    let var_id = helper.add_variable(&qualified_var_name, Some(span_from_node(assignment_node)));

    // Create type node
    let type_id = helper.add_type(&type_name, None);

    // Add TypeOf and Reference edges
    helper.add_typeof_edge(var_id, type_id);
    helper.add_reference_edge(var_id, type_id);
}

/// Extract type name from a type annotation node.
///
/// Handles:
/// - Simple types: `int`, `str`, `bool`
/// - Generic types: `List[int]` → extract base type `List`
/// - Optional types: `Optional[User]` → extract base type `Optional`
/// - Qualified types: `module.Type` → extract full qualified name
/// - Forward references: `"User"` → `User` (strips quotes)
/// - PEP 604 unions: `User | None` → `User` (extracts left-most base type)
fn extract_type_from_node(type_node: Node<'_>, content: &[u8]) -> Option<String> {
    match type_node.kind() {
        "type" => {
            // The "type" node wraps the actual type - recurse into first child
            type_node
                .named_child(0)
                .and_then(|child| extract_type_from_node(child, content))
        }
        "identifier" => {
            // Simple type: int, str, User
            type_node.utf8_text(content).ok().map(String::from)
        }
        "string" => {
            // Forward reference: "User" -> User
            // Strip surrounding quotes from string literal annotations
            let text = type_node.utf8_text(content).ok()?;
            let trimmed = text.trim();

            // Remove quotes: "User" or 'User' -> User
            if (trimmed.starts_with('"') && trimmed.ends_with('"'))
                || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
            {
                let unquoted = &trimmed[1..trimmed.len() - 1];
                // Handle potential unions inside string: "User | None" -> "User"
                Some(normalize_union_type(unquoted))
            } else {
                Some(trimmed.to_string())
            }
        }
        "binary_operator" => {
            // PEP 604 union: User | None -> User
            // Extract left operand as the primary type
            if let Some(left) = type_node.child_by_field_name("left") {
                extract_type_from_node(left, content)
            } else {
                // Fallback: extract text and normalize
                type_node
                    .utf8_text(content)
                    .ok()
                    .map(|text| normalize_union_type(text.trim()))
            }
        }
        "generic_type" | "subscript" => {
            // Generic type: List[int], Dict[str, int], Optional[User]
            // Extract base type (before the brackets)
            // Structure: subscript { value: identifier, subscript: [...] }
            if let Some(value_node) = type_node.child_by_field_name("value") {
                extract_type_from_node(value_node, content)
            } else {
                // Fallback: try first named child
                type_node
                    .named_child(0)
                    .and_then(|child| extract_type_from_node(child, content))
                    .or_else(|| {
                        // Last resort: extract the full text and take the base type
                        type_node.utf8_text(content).ok().and_then(|text| {
                            // Extract base type from "List[str]" -> "List"
                            text.split('[').next().map(|s| s.trim().to_string())
                        })
                    })
            }
        }
        "attribute" => {
            // Qualified type: module.Type or package.module.Type
            type_node.utf8_text(content).ok().map(String::from)
        }
        "list" | "tuple" | "set" => {
            // Collection literals (though rare in type annotations)
            type_node.utf8_text(content).ok().map(String::from)
        }
        _ => {
            // Fallback: try to extract text from any other node
            // For unknown node types, try to extract intelligently
            let text = type_node.utf8_text(content).ok()?;
            let trimmed = text.trim();

            // If it looks like a generic type, extract base type
            if trimmed.contains('[') {
                trimmed.split('[').next().map(|s| s.trim().to_string())
            } else {
                // Check for union syntax
                Some(normalize_union_type(trimmed))
            }
        }
    }
}

/// Normalize union types by extracting the left-most/primary type.
///
/// Examples:
/// - `User | None` → `User`
/// - `str | int` → `str`
/// - `Optional[User]` → `Optional[User]` (unchanged, not a union)
fn normalize_union_type(type_str: &str) -> String {
    if let Some(pipe_pos) = type_str.find('|') {
        // Extract left side of union and trim
        type_str[..pipe_pos].trim().to_string()
    } else {
        type_str.to_string()
    }
}

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

    #[test]
    fn test_simple_name_extracts_dotted_identifiers() {
        // General dotted identifier handling (for call targets)
        assert_eq!(simple_name("module.func"), "func");
        assert_eq!(simple_name("obj.method"), "method");
        assert_eq!(simple_name("package.module.func"), "func");
        assert_eq!(simple_name("self.helper"), "helper");

        // No dots - return as-is
        assert_eq!(simple_name("function"), "function");
        assert_eq!(simple_name(""), "");
    }

    #[test]
    fn test_ffi_library_simple_name_extracts_library_base_names() {
        // Standard shared library names
        assert_eq!(ffi_library_simple_name("libfoo.so"), "libfoo");
        assert_eq!(ffi_library_simple_name("lib1.so"), "lib1");
        assert_eq!(ffi_library_simple_name("lib2.so"), "lib2");

        // Different extensions
        assert_eq!(ffi_library_simple_name("kernel32.dll"), "kernel32");
        assert_eq!(ffi_library_simple_name("libSystem.dylib"), "libSystem");

        // Versioned shared libraries (libc.so.6)
        assert_eq!(ffi_library_simple_name("libc.so.6"), "libc");

        // No extension - return as-is
        assert_eq!(ffi_library_simple_name("kernel32"), "kernel32");
        assert_eq!(ffi_library_simple_name("numpy"), "numpy");

        // Variable references (prefixed with $)
        assert_eq!(ffi_library_simple_name("$libname"), "$libname");

        // Edge cases
        assert_eq!(ffi_library_simple_name(""), "");
        assert_eq!(ffi_library_simple_name("lib.so"), "lib");
    }

    #[test]
    fn test_ffi_library_simple_name_prevents_duplicate_edges() {
        // This was the bug: lib1.so and lib2.so both became "so"
        let name1 = ffi_library_simple_name("lib1.so");
        let name2 = ffi_library_simple_name("lib2.so");

        // They should be different
        assert_ne!(
            name1, name2,
            "lib1.so and lib2.so must produce different simple names"
        );
        assert_eq!(name1, "lib1");
        assert_eq!(name2, "lib2");
    }

    #[test]
    fn test_ffi_library_simple_name_handles_directory_paths() {
        // Full paths with directories containing dots (Codex finding)
        assert_eq!(ffi_library_simple_name("/opt/v1.2/libfoo.so"), "libfoo");
        assert_eq!(
            ffi_library_simple_name("/usr/lib/x86_64-linux-gnu/libc.so.6"),
            "libc"
        );
        assert_eq!(ffi_library_simple_name("libs/lib1.so"), "lib1");

        // Relative paths
        assert_eq!(ffi_library_simple_name("./libs/kernel32.dll"), "kernel32");
        assert_eq!(
            ffi_library_simple_name("../lib/libSystem.dylib"),
            "libSystem"
        );
    }

    // ====================================================================
    // Route decorator parsing unit tests
    // ====================================================================

    #[test]
    fn test_parse_route_decorator_app_route_default_get() {
        let result = parse_route_decorator_text("app.route('/api/users')");
        assert_eq!(result, Some(("GET".to_string(), "/api/users".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_app_route_with_methods_post() {
        let result = parse_route_decorator_text("app.route('/api/users', methods=['POST'])");
        assert_eq!(result, Some(("POST".to_string(), "/api/users".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_app_route_with_methods_put_double_quotes() {
        let result = parse_route_decorator_text("app.route(\"/api/items\", methods=[\"PUT\"])");
        assert_eq!(result, Some(("PUT".to_string(), "/api/items".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_app_get() {
        let result = parse_route_decorator_text("app.get('/api/users')");
        assert_eq!(result, Some(("GET".to_string(), "/api/users".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_app_post() {
        let result = parse_route_decorator_text("app.post('/api/items')");
        assert_eq!(result, Some(("POST".to_string(), "/api/items".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_app_put() {
        let result = parse_route_decorator_text("app.put('/api/items/1')");
        assert_eq!(
            result,
            Some(("PUT".to_string(), "/api/items/1".to_string()))
        );
    }

    #[test]
    fn test_parse_route_decorator_app_delete() {
        let result = parse_route_decorator_text("app.delete('/api/items/1')");
        assert_eq!(
            result,
            Some(("DELETE".to_string(), "/api/items/1".to_string()))
        );
    }

    #[test]
    fn test_parse_route_decorator_app_patch() {
        let result = parse_route_decorator_text("app.patch('/api/items/1')");
        assert_eq!(
            result,
            Some(("PATCH".to_string(), "/api/items/1".to_string()))
        );
    }

    #[test]
    fn test_parse_route_decorator_router_get_fastapi() {
        let result = parse_route_decorator_text("router.get('/api/users')");
        assert_eq!(result, Some(("GET".to_string(), "/api/users".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_router_post_fastapi() {
        let result = parse_route_decorator_text("router.post('/api/items')");
        assert_eq!(result, Some(("POST".to_string(), "/api/items".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_blueprint_route() {
        let result = parse_route_decorator_text("blueprint.route('/health')");
        assert_eq!(result, Some(("GET".to_string(), "/health".to_string())));
    }

    #[test]
    fn test_parse_route_decorator_unknown_receiver_returns_none() {
        // "server" is not a recognized receiver
        let result = parse_route_decorator_text("server.get('/api/users')");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_route_decorator_unknown_method_returns_none() {
        // "options" is not in the ROUTE_METHOD_NAMES list and is not "route"
        let result = parse_route_decorator_text("app.options('/api/users')");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_route_decorator_no_parens_returns_none() {
        let result = parse_route_decorator_text("app.route");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_route_decorator_no_dot_returns_none() {
        let result = parse_route_decorator_text("route('/api/users')");
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_path_from_decorator_args_single_quotes() {
        let result = extract_path_from_decorator_args("'/api/users')");
        assert_eq!(result, Some("/api/users".to_string()));
    }

    #[test]
    fn test_extract_path_from_decorator_args_double_quotes() {
        let result = extract_path_from_decorator_args("\"/api/items\")");
        assert_eq!(result, Some("/api/items".to_string()));
    }

    #[test]
    fn test_extract_path_from_decorator_args_empty_returns_none() {
        let result = extract_path_from_decorator_args("'')");
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_path_from_decorator_args_no_string_returns_none() {
        let result = extract_path_from_decorator_args("some_var)");
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_method_from_route_args_with_methods_keyword() {
        let result = extract_method_from_route_args("'/api/users', methods=['POST'])");
        assert_eq!(result, "POST");
    }

    #[test]
    fn test_extract_method_from_route_args_without_methods_keyword() {
        let result = extract_method_from_route_args("'/api/users')");
        assert_eq!(result, "GET");
    }

    #[test]
    fn test_extract_method_from_route_args_delete() {
        let result = extract_method_from_route_args("'/api/items', methods=['DELETE'])");
        assert_eq!(result, "DELETE");
    }

    #[test]
    fn test_extract_method_from_route_args_lowercase_normalizes() {
        let result = extract_method_from_route_args("'/x', methods=['put'])");
        assert_eq!(result, "PUT");
    }

    #[test]
    fn test_extract_first_string_literal_single_quotes() {
        let result = extract_first_string_literal("'POST']");
        assert_eq!(result, Some("POST".to_string()));
    }

    #[test]
    fn test_extract_first_string_literal_double_quotes() {
        let result = extract_first_string_literal("\"DELETE\"]");
        assert_eq!(result, Some("DELETE".to_string()));
    }

    #[test]
    fn test_extract_first_string_literal_empty_returns_none() {
        let result = extract_first_string_literal("no quotes here");
        assert_eq!(result, None);
    }
}