r2x-ast 0.0.7

AST discovery utilities for the r2x CLI
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
//! AST-based plugin discovery using ast-grep
//!
//! This module provides static analysis based plugin discovery by:
//! 1. Using ast-grep to parse Python source code without runtime (Phase 1)
//! 2. Extracting plugin definitions from the register_plugin() function
//! 3. Resolving class/function references to extract metadata (Phase 2)
//! 4. Associating decorator registrations with plugins (Phase 3)
//!
//! This approach is significantly faster than Python-based discovery and requires
//! no Python interpreter startup.

pub mod decorator_scanner;
pub mod discovery_types;
pub mod extractor;
pub mod package_cache;
pub mod schema_extractor;

use crate::package_cache::PackageAstCache;
use anyhow::{anyhow, Result};
use ast_grep_language::Python;
use r2x_logger as logger;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

// Re-export commonly used types (also used internally)
pub use discovery_types::{
    ArgumentSpec, ConfigField, ConfigSpec, DecoratorRegistration, DiscoveredPlugin, EntryPointInfo,
    IOContract, IOSlot, ImplementationType, InvocationSpec, PluginKind, ResourceSpec, StoreMode,
    StoreSpec, UpgradeSpec,
};
pub use schema_extractor::SchemaExtractor;

type PythonAst = ast_grep_core::AstGrep<ast_grep_core::source::StrDoc<Python>>;

struct CachedFile {
    content: String,
    ast: PythonAst,
}

/// AST-based plugin discovery orchestrator
pub struct AstDiscovery;

impl AstDiscovery {
    /// Discover plugins from a Python package using AST parsing
    ///
    /// Uses an entry-points-first approach: parses entry_points.txt directly
    /// to find all plugin entry points, then uses AST to extract metadata.
    ///
    /// Performance optimizations:
    /// - Single directory walk via PackageAstCache
    /// - Single AST parse per file
    /// - Kind-based decorator matching
    ///
    /// # Arguments
    /// * `package_path` - Path to the installed package (e.g., site-packages/r2x_reeds)
    /// * `package_name_full` - Full package name (e.g., "r2x-reeds")
    /// * `venv_path` - Optional path to virtual environment for entry_points.txt lookup
    /// * `package_version` - Optional package version string
    ///
    /// # Returns
    /// Tuple of (discovered plugins, decorator registrations)
    pub fn discover_plugins(
        package_path: &Path,
        package_name_full: &str,
        venv_path: Option<&str>,
        _package_version: Option<&str>,
    ) -> Result<(Vec<DiscoveredPlugin>, Vec<DecoratorRegistration>)> {
        let total_start = Instant::now();
        logger::debug(&format!("AST discovery started for: {}", package_name_full));

        let discovery_root = Self::resolve_discovery_root(package_path, package_name_full);
        logger::debug(&format!("AST discovery root: {:?}", discovery_root));

        // Step 1: Check explicit entry points (entry_points.txt or pyproject.toml)
        let entry_start = Instant::now();
        let pyproject_entries =
            Self::find_pyproject_entry_points(package_path, &discovery_root, package_name_full);
        let entry_point_entries = if !pyproject_entries.is_empty() {
            pyproject_entries
        } else {
            match Self::find_entry_points_txt(package_path, package_name_full, venv_path) {
                Ok(entry_points_path) => {
                    logger::debug(&format!(
                        "Found entry_points.txt at: {:?}",
                        entry_points_path
                    ));

                    let content = std::fs::read_to_string(&entry_points_path)
                        .map_err(|e| anyhow!("Failed to read entry_points.txt: {}", e))?;

                    Self::parse_all_entry_points(&content)
                }
                Err(e) => {
                    logger::debug(&format!(
                        "No entry_points.txt found for '{}': {}",
                        package_name_full, e
                    ));
                    Vec::new()
                }
            }
        };

        logger::debug(&format!(
            "Entry points parsing: {} entries in {:.2}ms",
            entry_point_entries.len(),
            entry_start.elapsed().as_secs_f64() * 1000.0
        ));

        // Step 2: Package-wide AST discovery only when entry points are missing
        let mut package_cache: Option<PackageAstCache> = None;
        let mut class_entries = Vec::new();
        let mut function_entries = Vec::new();

        if entry_point_entries.is_empty() {
            let ast_start = Instant::now();
            let cache = PackageAstCache::build(&discovery_root);
            class_entries =
                Self::discover_plugins_with_ast_grep(&cache, &discovery_root, package_name_full);
            function_entries =
                Self::discover_expose_plugin_functions(&cache, &discovery_root, package_name_full);

            logger::debug(&format!(
                "AST-grep discovery: {} classes, {} functions in {:.2}ms ({} files)",
                class_entries.len(),
                function_entries.len(),
                ast_start.elapsed().as_secs_f64() * 1000.0,
                cache.file_count()
            ));

            package_cache = Some(cache);
        }

        // Step 3: Merge and deduplicate all discoveries
        // Priority: entry_points.txt > ast-grep (entry_points.txt has explicit registrations)
        let mut all_entries = Vec::new();
        all_entries.extend(entry_point_entries); // Entry points first (higher priority)
        all_entries.extend(class_entries);
        all_entries.extend(function_entries);

        let all_entries = Self::deduplicate_entries(all_entries);

        if all_entries.is_empty() {
            logger::debug(&format!("No plugins found for '{}'", package_name_full));
            return Ok((Vec::new(), Vec::new()));
        }

        logger::debug(&format!(
            "Total unique entry points: {} entries",
            all_entries.len()
        ));

        // Step 4: Discover plugins from each entry point using targeted file parsing
        // Only parse files that are actually needed (not the whole package)
        let discover_start = Instant::now();
        let mut plugins = Vec::new();
        let mut file_cache: HashMap<PathBuf, Arc<CachedFile>> = HashMap::new();

        for entry in &all_entries {
            match Self::discover_direct_entry_point(
                package_path,
                &discovery_root,
                entry,
                package_name_full,
                &mut file_cache,
                &mut package_cache,
            ) {
                Ok(plugin) => {
                    logger::debug(&format!(
                        "Discovered plugin: {} ({:?})",
                        plugin.name, plugin.kind
                    ));
                    plugins.push(plugin);
                }
                Err(e) => {
                    logger::debug(&format!(
                        "Failed to discover plugin from entry point '{}': {}",
                        entry.name, e
                    ));
                }
            }
        }
        logger::debug(&format!(
            "Plugin discovery: {} plugins in {:.2}ms (parsed {} files)",
            plugins.len(),
            discover_start.elapsed().as_secs_f64() * 1000.0,
            file_cache.len()
        ));

        // Step 5: Decorator registrations - only extract if needed (lazy)
        // For now, skip full package scanning - decorators can be extracted on-demand
        let decorator_registrations = Vec::new();

        logger::info(&format!(
            "AST discovery total: {} plugins, {} decorators in {:.2}ms for {}",
            plugins.len(),
            decorator_registrations.len(),
            total_start.elapsed().as_secs_f64() * 1000.0,
            package_name_full
        ));

        Ok((plugins, decorator_registrations))
    }

    /// Resolve the most likely package root for AST discovery.
    ///
    /// Prefers the actual module directory over a project root to avoid
    /// traversing unrelated directories like .git or build artifacts.
    fn resolve_discovery_root(package_path: &Path, package_name_full: &str) -> PathBuf {
        let normalized_name = package_name_full.replace('-', "_");

        let direct_candidate = package_path.join(&normalized_name);
        if direct_candidate.is_dir() {
            return direct_candidate;
        }

        let src_candidate = package_path.join("src").join(&normalized_name);
        if src_candidate.is_dir() {
            return src_candidate;
        }

        let path_name_matches = package_path
            .file_name()
            .and_then(|name| name.to_str())
            .map(|name| name == normalized_name)
            .unwrap_or(false);

        if path_name_matches || package_path.join("__init__.py").exists() {
            return package_path.to_path_buf();
        }

        package_path.to_path_buf()
    }

    /// Find entry_points.txt for the package
    ///
    /// Optimized to avoid directory scanning by trying direct paths first.
    fn find_entry_points_txt(
        package_path: &Path,
        package_name_full: &str,
        venv_path: Option<&str>,
    ) -> Result<std::path::PathBuf> {
        let normalized_name = package_name_full.replace('-', "_");

        // Strategy 1: Look for entry_points.txt directly in package_path (for source packages)
        // This handles editable installs where package_path is the source directory
        let direct_path = package_path.join("entry_points.txt");
        if direct_path.exists() {
            return Ok(direct_path);
        }

        // Strategy 2: Look in parent directory's dist-info (for installed packages)
        // Pattern: ../package_name-*.dist-info/entry_points.txt
        if let Some(parent) = package_path.parent() {
            // Try to find dist-info by scanning just the parent (usually site-packages)
            if let Some(entry_points) = Self::find_dist_info_entry_points(parent, &normalized_name)
            {
                return Ok(entry_points);
            }
        }

        // Strategy 3: Use venv site-packages if provided
        if let Some(venv) = venv_path {
            let venv_path = std::path::PathBuf::from(venv);
            if let Ok(site_packages) = r2x_python::resolve_site_package_path(&venv_path) {
                if let Some(entry_points) =
                    Self::find_dist_info_entry_points(&site_packages, &normalized_name)
                {
                    return Ok(entry_points);
                }
            }
        }

        Err(anyhow!(
            "Package '{}' has no entry_points.txt",
            package_name_full
        ))
    }

    /// Find entry points in pyproject.toml (PEP 621)
    fn find_pyproject_entry_points(
        package_path: &Path,
        discovery_root: &Path,
        package_name_full: &str,
    ) -> Vec<EntryPointInfo> {
        let pyproject_path = match Self::find_pyproject_toml_path(package_path, discovery_root) {
            Some(path) => path,
            None => return Vec::new(),
        };

        let content = match std::fs::read_to_string(&pyproject_path) {
            Ok(content) => content,
            Err(e) => {
                logger::debug(&format!(
                    "Failed to read pyproject.toml at {:?}: {}",
                    pyproject_path, e
                ));
                return Vec::new();
            }
        };

        let entries = Self::parse_pyproject_entry_points(&content);
        if !entries.is_empty() {
            logger::debug(&format!(
                "Parsed {} entry points from pyproject.toml for '{}'",
                entries.len(),
                package_name_full
            ));
        }

        entries
    }

    fn find_pyproject_toml_path(package_path: &Path, discovery_root: &Path) -> Option<PathBuf> {
        let mut seen = std::collections::HashSet::new();
        let candidates = [
            Some(package_path),
            package_path.parent(),
            discovery_root.parent(),
            discovery_root.parent().and_then(|p| p.parent()),
        ];

        for candidate in candidates.into_iter().flatten() {
            let candidate = candidate.to_path_buf();
            if !seen.insert(candidate.clone()) {
                continue;
            }

            let pyproject = candidate.join("pyproject.toml");
            if pyproject.exists() {
                return Some(pyproject);
            }
        }

        None
    }

    fn parse_pyproject_entry_points(content: &str) -> Vec<EntryPointInfo> {
        let mut entries = Vec::new();
        let parsed: toml::Value = match toml::from_str(content) {
            Ok(parsed) => parsed,
            Err(_) => return entries,
        };

        let entry_points = match parsed
            .get("project")
            .and_then(|project| project.get("entry-points"))
            .and_then(|value| value.as_table())
        {
            Some(entry_points) => entry_points,
            None => return entries,
        };

        for (section, values) in entry_points {
            if !Self::is_r2x_section(section) {
                continue;
            }

            let Some(table) = values.as_table() else {
                continue;
            };

            for (name, target) in table {
                let Some(target_str) = target.as_str() else {
                    continue;
                };

                let line = format!("{} = {}", name, target_str);
                if let Some(entry) = Self::parse_entry_point_line(&line, section) {
                    entries.push(entry);
                }
            }
        }

        entries
    }

    /// Find entry_points.txt in a dist-info directory within the given path
    fn find_dist_info_entry_points(
        dir: &Path,
        normalized_name: &str,
    ) -> Option<std::path::PathBuf> {
        let entries = std::fs::read_dir(dir).ok()?;
        let prefix = format!("{}-", normalized_name);

        for entry in entries.flatten() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();

            if name_str.starts_with(&prefix) && name_str.ends_with(".dist-info") {
                let entry_points = entry.path().join("entry_points.txt");
                if entry_points.exists() {
                    return Some(entry_points);
                }
            }
        }
        None
    }

    /// Parse all r2x-related entry points from entry_points.txt
    ///
    /// This function scans for all sections that are r2x-related:
    /// - `[r2x_plugin]` - main plugin registration
    /// - `[r2x.*]` - any section starting with "r2x." (e.g., r2x.transforms, r2x.parsers)
    ///
    /// Returns a vector of EntryPointInfo for all discovered entry points.
    fn parse_all_entry_points(content: &str) -> Vec<EntryPointInfo> {
        let mut entries = Vec::new();
        let mut current_section: Option<String> = None;

        for line in content.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Check for section header
            if line.starts_with('[') && line.ends_with(']') {
                let section = &line[1..line.len() - 1];
                // Check if this section is r2x-related
                if Self::is_r2x_section(section) {
                    current_section = Some(section.to_string());
                } else {
                    current_section = None;
                }
                continue;
            }

            // Parse entry point within a relevant section
            if let Some(ref section) = current_section {
                if let Some(entry) = Self::parse_entry_point_line(line, section) {
                    entries.push(entry);
                }
            }
        }

        logger::debug(&format!(
            "Parsed {} entry points from entry_points.txt",
            entries.len()
        ));
        entries
    }

    /// Check if a section name is r2x-related
    fn is_r2x_section(section: &str) -> bool {
        section == "r2x_plugin" || section.starts_with("r2x.")
    }

    /// Parse a single entry point line in the format: name = module:symbol
    fn parse_entry_point_line(line: &str, section: &str) -> Option<EntryPointInfo> {
        let eq_idx = line.find('=')?;
        let name = line[..eq_idx].trim();
        let value = line[eq_idx + 1..].trim();

        // Handle quoted values (e.g., name = "module:symbol")
        let value = value.trim_matches('"').trim_matches('\'');

        let colon_idx = value.find(':')?;
        let module = value[..colon_idx].trim();
        let symbol = value[colon_idx + 1..].trim();

        if name.is_empty() || module.is_empty() || symbol.is_empty() {
            return None;
        }

        Some(EntryPointInfo {
            name: name.to_string(),
            module: module.to_string(),
            symbol: symbol.to_string(),
            section: section.to_string(),
        })
    }

    /// Resolve a module path to a source file location
    ///
    /// Handles both regular and editable installs:
    /// - Regular: site-packages/r2x_reeds/sysmod/break_gens.py
    /// - Editable: src/r2x_reeds/sysmod/break_gens.py
    ///
    /// The function tries multiple path patterns to locate the source file.
    fn resolve_source_file(
        package_path: &Path,
        module: &str,
        package_name: &str,
    ) -> Option<std::path::PathBuf> {
        // Convert module path to relative file path
        // e.g., "r2x_reeds.sysmod.pcm_defaults" -> "r2x_reeds/sysmod/pcm_defaults.py"
        let relative_path = module.replace('.', "/") + ".py";

        // Also prepare a path without the package prefix
        // e.g., "sysmod/pcm_defaults.py" for use within package_path
        let normalized_package = package_name.replace('-', "_");
        let relative_without_prefix = module
            .strip_prefix(&normalized_package)
            .map(|s| s.trim_start_matches('.'))
            .filter(|s| !s.is_empty())
            .map(|s| s.replace('.', "/") + ".py");

        // Try various path patterns
        let candidates: Vec<std::path::PathBuf> = [
            // Direct path from package_path (for editable installs where package_path is the source)
            relative_without_prefix
                .as_ref()
                .map(|p| package_path.join(p)),
            // Full relative path from package_path
            Some(package_path.join(&relative_path)),
            // One level up (in case package_path is the package root)
            package_path.parent().map(|p| p.join(&relative_path)),
            // src/ subdirectory (common in editable installs)
            Some(package_path.join("src").join(&relative_path)),
            // Two levels up with src/ (common project structure)
            package_path
                .parent()
                .and_then(|p| p.parent())
                .map(|p| p.join(&relative_path)),
        ]
        .into_iter()
        .flatten()
        .collect();

        for candidate in &candidates {
            if candidate.exists() {
                logger::debug(&format!(
                    "Resolved source file for module '{}': {:?}",
                    module, candidate
                ));
                return Some(candidate.clone());
            }
        }

        // Also check for __init__.py if the module might be a package
        let init_path = module.replace('.', "/") + "/__init__.py";
        let init_candidates: Vec<std::path::PathBuf> = [
            Some(package_path.join(&init_path)),
            package_path.parent().map(|p| p.join(&init_path)),
            // Also try src/ subdirectory
            Some(package_path.join("src").join(&init_path)),
        ]
        .into_iter()
        .flatten()
        .collect();

        for candidate in &init_candidates {
            if candidate.exists() {
                logger::debug(&format!(
                    "Resolved source file for module '{}' (as package): {:?}",
                    module, candidate
                ));
                return Some(candidate.clone());
            }
        }

        logger::debug(&format!(
            "Could not resolve source file for module '{}'. Tried: {:?}",
            module, candidates
        ));
        None
    }

    // =========================================================================
    // AST-GREP LIBRARY-BASED DISCOVERY - Fast discovery without subprocess
    // =========================================================================

    /// Discover plugins using ast-grep library to search for Plugin class patterns
    ///
    /// Used when explicit entry points are missing to find classes that inherit from Plugin[Config].
    ///
    /// Uses ast-grep-core library directly for fast discovery without subprocess overhead.
    fn discover_plugins_with_ast_grep(
        package_cache: &PackageAstCache,
        discovery_root: &Path,
        package_name: &str,
    ) -> Vec<EntryPointInfo> {
        let start = Instant::now();
        let mut entries = Vec::new();
        let normalized_package = package_name.replace('-', "_");

        for (path, file) in package_cache.files() {
            let path_str = match path.to_str() {
                Some(path_str) => path_str,
                None => continue,
            };
            let module =
                Self::infer_module_from_file_path(path_str, discovery_root, &normalized_package);

            for class in &file.classes {
                if class.generic_param.is_none() {
                    continue;
                }

                entries.push(EntryPointInfo {
                    name: Self::camel_to_kebab(&class.name),
                    module: module.clone(),
                    symbol: class.name.clone(),
                    section: "r2x_plugin".to_string(),
                });
            }
        }

        logger::debug(&format!(
            "ast-grep discovery: found {} Plugin classes in {:.2}ms",
            entries.len(),
            start.elapsed().as_secs_f64() * 1000.0
        ));

        entries
    }

    /// Discover @expose_plugin decorated functions using ast-grep library
    ///
    /// Searches for functions decorated with @expose_plugin in the package.
    /// These are registered in the r2x.transforms section.
    fn discover_expose_plugin_functions(
        package_cache: &PackageAstCache,
        discovery_root: &Path,
        package_name: &str,
    ) -> Vec<EntryPointInfo> {
        let start = Instant::now();
        let mut entries = Vec::new();
        let normalized_package = package_name.replace('-', "_");

        for (path, func) in package_cache.get_all_decorated_functions() {
            let path_str = match path.to_str() {
                Some(path_str) => path_str,
                None => continue,
            };
            let module =
                Self::infer_module_from_file_path(path_str, discovery_root, &normalized_package);
            let func_name = func.function_name.as_str();

            entries.push(EntryPointInfo {
                name: Self::snake_to_kebab(func_name),
                module,
                symbol: func_name.to_string(),
                section: "r2x.transforms".to_string(),
            });
        }

        logger::debug(&format!(
            "ast-grep discovery: found {} @expose_plugin functions in {:.2}ms",
            entries.len(),
            start.elapsed().as_secs_f64() * 1000.0
        ));

        entries
    }

    /// Extract function name from decorated function text
    #[cfg(test)]
    fn extract_function_name_from_text(text: &str) -> Option<String> {
        // Look for "def function_name(" pattern
        let def_idx = text.find("def ")?;
        let after_def = &text[def_idx + 4..];
        let paren_idx = after_def.find('(')?;
        let name = after_def[..paren_idx].trim();

        if name.is_empty() {
            return None;
        }

        Some(name.to_string())
    }

    /// Extract class name from ast-grep matched text like "class MyParser(Plugin[Config]): ..."
    #[cfg(test)]
    fn extract_class_name_from_match(text: &str) -> Option<String> {
        // Pattern: "class ClassName(..."
        let text = text.trim();
        if !text.starts_with("class ") {
            return None;
        }
        let after_class = &text[6..];
        let end = after_class.find('(')?;
        let name = after_class[..end].trim();
        if name.is_empty() {
            return None;
        }
        Some(name.to_string())
    }

    /// Convert CamelCase class name to kebab-case plugin name
    ///
    /// Preserves suffixes (unlike the old implementation that stripped them):
    /// - ReEDSParser -> reeds-parser
    /// - MyExporter -> my-exporter
    /// - SimplePlugin -> simple-plugin
    fn camel_to_kebab(class_name: &str) -> String {
        let mut result = String::new();

        for (i, ch) in class_name.chars().enumerate() {
            if ch.is_uppercase() && i > 0 {
                let prev_upper = class_name
                    .chars()
                    .nth(i - 1)
                    .map(|c| c.is_uppercase())
                    .unwrap_or(false);
                let next_upper = class_name
                    .chars()
                    .nth(i + 1)
                    .map(|c| c.is_uppercase())
                    .unwrap_or(false);
                let next_lower = class_name
                    .chars()
                    .nth(i + 1)
                    .map(|c| c.is_lowercase())
                    .unwrap_or(false);

                // Add hyphen when:
                // 1. Starting new word from lowercase, unless entering an acronym
                //    (e.g., "my" -> "P" in "myParser", but NOT "Re" -> "E" in "ReEDS")
                // 2. End of acronym transitioning to new word
                //    (e.g., "S" -> "P" in "ReEDSParser")
                let start_new_word = !prev_upper && !next_upper;
                let end_of_acronym = prev_upper && next_lower;

                if start_new_word || end_of_acronym {
                    result.push('-');
                }
            }
            result.push(ch.to_ascii_lowercase());
        }

        result
    }

    /// Convert snake_case function name to kebab-case plugin name
    fn snake_to_kebab(func_name: &str) -> String {
        func_name.replace('_', "-")
    }

    /// Deduplicate entry points by symbol name
    ///
    /// When merging entry_points.txt with ast-grep discoveries, we may have
    /// duplicates (same class/function discovered via different paths).
    /// This function deduplicates by symbol, preserving the first occurrence
    /// (entry_points.txt entries have priority since they're added first).
    fn deduplicate_entries(entries: Vec<EntryPointInfo>) -> Vec<EntryPointInfo> {
        use std::collections::HashSet;

        let mut seen_symbols: HashSet<String> = HashSet::new();
        let mut result = Vec::new();

        for entry in entries {
            // Deduplicate by symbol name only
            // This prevents the same class (e.g., ReEDSParser) from being
            // registered twice with different inferred module paths
            if seen_symbols.insert(entry.symbol.clone()) {
                result.push(entry);
            }
        }

        result
    }

    /// Infer module path from file path
    fn infer_module_from_file_path(
        file_path: &str,
        package_path: &Path,
        package_name: &str,
    ) -> String {
        let path = std::path::Path::new(file_path);
        // Normalize package name: dashes to underscores for Python module names
        let normalized_package = package_name.replace('-', "_");

        // Try to get relative path from package_path
        if let Ok(rel) = path.strip_prefix(package_path) {
            let parts: Vec<&str> = rel
                .components()
                .filter_map(|c| c.as_os_str().to_str())
                .collect();

            if !parts.is_empty() {
                let module_parts: Vec<&str> = parts
                    .into_iter()
                    .map(|p| p.strip_suffix(".py").unwrap_or(p))
                    .filter(|p| *p != "__init__")
                    .collect();

                if module_parts.is_empty() {
                    return normalized_package;
                }

                // Check if the first part already matches the package name
                // (happens with editable installs where package_path is source root)
                if module_parts[0] == normalized_package {
                    return module_parts.join(".");
                }

                return format!("{}.{}", normalized_package, module_parts.join("."));
            }
        }

        // Fallback: just use normalized package name
        normalized_package
    }

    // =========================================================================
    // DIRECT FILE PARSING - Parse only the files needed for each entry point
    // =========================================================================

    /// Discover a plugin from a direct entry point using targeted file parsing
    ///
    /// This approach only parses the specific file(s) needed for each entry point,
    /// avoiding the overhead of parsing all files in the package upfront.
    fn discover_direct_entry_point(
        package_path: &Path,
        discovery_root: &Path,
        entry: &EntryPointInfo,
        package_name: &str,
        file_cache: &mut HashMap<PathBuf, Arc<CachedFile>>,
        package_cache: &mut Option<PackageAstCache>,
    ) -> Result<DiscoveredPlugin> {
        logger::debug(&format!(
            "Discovering direct entry point: {} = {}:{}",
            entry.name, entry.module, entry.symbol
        ));

        // Resolve the source file
        let mut source_file = Self::resolve_source_file(package_path, &entry.module, package_name);
        let mut cached = source_file
            .as_ref()
            .and_then(|source_path| Self::read_file_cached(file_cache, source_path));

        // Determine implementation type based on symbol naming convention
        let implementation = if entry.is_class() {
            ImplementationType::Class
        } else {
            ImplementationType::Function
        };

        // Infer plugin kind from section and symbol
        let kind = entry.infer_kind();

        // Build the fully qualified entry point
        let full_entry = format!("{}.{}", entry.module, entry.symbol);

        if matches!(implementation, ImplementationType::Class) {
            let mut has_class = cached
                .as_ref()
                .map(|cached| Self::ast_has_class(&cached.ast, &entry.symbol))
                .unwrap_or(false);

            if !has_class {
                if let Some(cached_file) = cached.as_ref() {
                    if let Some(resolved_module) = Self::resolve_reexported_symbol(
                        &cached_file.content,
                        &entry.module,
                        &entry.symbol,
                    ) {
                        if let Some(path) =
                            Self::resolve_source_file(package_path, &resolved_module, package_name)
                        {
                            source_file = Some(path.clone());
                            cached = Self::read_file_cached(file_cache, &path);
                            has_class = cached
                                .as_ref()
                                .map(|cached| Self::ast_has_class(&cached.ast, &entry.symbol))
                                .unwrap_or(false);
                        }
                    }
                }
            }

            if !has_class {
                if package_cache.is_none() {
                    *package_cache = Some(PackageAstCache::build(discovery_root));
                }

                if let Some(cache) = package_cache.as_ref() {
                    if let Some((path, _class)) = cache.find_class_with_path(&entry.symbol) {
                        source_file = Some(path.clone());
                        cached = Self::read_file_cached(file_cache, path);
                    }
                }
            }
        } else {
            // For functions, also check if it's re-exported and follow the import
            let has_function = cached
                .as_ref()
                .map(|cached| Self::ast_has_function(&cached.ast, &entry.symbol))
                .unwrap_or(false);

            if !has_function {
                // Function not defined here, try to resolve from imports
                if let Some(cached_file) = cached.as_ref() {
                    if let Some(resolved_module) = Self::resolve_reexported_symbol(
                        &cached_file.content,
                        &entry.module,
                        &entry.symbol,
                    ) {
                        if let Some(path) =
                            Self::resolve_source_file(package_path, &resolved_module, package_name)
                        {
                            source_file = Some(path.clone());
                            cached = Self::read_file_cached(file_cache, &path);
                        }
                    }
                }
            }
        }

        // Extract constructor/call arguments and config using direct file parsing
        let (constructor_args, call_args, resources) =
            if let (Some(source_path), Some(cached)) = (source_file.as_ref(), cached.as_ref()) {
                Self::extract_entry_metadata(
                    discovery_root,
                    source_path,
                    cached.as_ref(),
                    entry,
                    &implementation,
                    file_cache,
                    package_cache,
                    package_name,
                )
            } else {
                (Vec::new(), Vec::new(), None)
            };

        // Determine the method to call based on plugin kind
        let method = match (&kind, &implementation) {
            (PluginKind::Parser, ImplementationType::Class) => Some("build_system".to_string()),
            (PluginKind::Exporter, ImplementationType::Class) => Some("export".to_string()),
            (PluginKind::Translation, ImplementationType::Class) => Some("run".to_string()),
            _ => None,
        };

        // Build IO contract based on plugin kind
        let io = Self::io_contract_for_kind(&kind);

        let invocation = InvocationSpec {
            implementation,
            method,
            constructor: constructor_args,
            call: call_args,
        };

        Ok(DiscoveredPlugin {
            name: entry.name.clone(),
            kind,
            entry: full_entry,
            invocation,
            io,
            resources,
            upgrade: None,
            description: None,
            tags: vec![entry.section.clone()],
        })
    }

    /// Read file content with caching to avoid re-reading the same file
    fn read_file_cached(
        file_cache: &mut HashMap<PathBuf, Arc<CachedFile>>,
        path: &Path,
    ) -> Option<Arc<CachedFile>> {
        if let Some(cached) = file_cache.get(path) {
            return Some(Arc::clone(cached));
        }

        let content = std::fs::read_to_string(path).ok()?;
        let ast = PythonAst::new(&content, Python);
        let cached = Arc::new(CachedFile { content, ast });
        file_cache.insert(path.to_path_buf(), Arc::clone(&cached));
        Some(cached)
    }

    /// Extract entry metadata using direct file parsing
    #[allow(clippy::too_many_arguments)]
    fn extract_entry_metadata(
        discovery_root: &Path,
        source_path: &Path,
        cached: &CachedFile,
        entry: &EntryPointInfo,
        implementation: &ImplementationType,
        file_cache: &mut HashMap<PathBuf, Arc<CachedFile>>,
        package_cache: &mut Option<PackageAstCache>,
        package_name: &str,
    ) -> (Vec<ArgumentSpec>, Vec<ArgumentSpec>, Option<ResourceSpec>) {
        let (constructor_args, call_args) = match implementation {
            ImplementationType::Class => {
                let args = Self::extract_class_init_params(&cached.ast, &entry.symbol);
                (args, Vec::new())
            }
            ImplementationType::Function => {
                let args = Self::extract_function_params(&cached.content, &entry.symbol);
                (Vec::new(), args)
            }
        };

        // Try to extract config class from type hints or class generic
        let config = Self::extract_config_with_fields(
            discovery_root,
            source_path,
            cached,
            entry,
            implementation,
            file_cache,
            package_cache,
            package_name,
        );

        // For functions without a config class, convert call_args to ConfigField format
        let resources = if let Some(c) = config {
            Some(ResourceSpec {
                store: None,
                config: Some(c),
            })
        } else if matches!(implementation, ImplementationType::Function) && !call_args.is_empty() {
            // For functions without config, use function parameters as config fields
            let fields = call_args
                .iter()
                .map(Self::argument_to_config_field)
                .collect();

            Some(ResourceSpec {
                store: None,
                config: Some(ConfigSpec {
                    module: entry.module.to_string(),
                    name: format!("{}Params", entry.symbol),
                    fields,
                }),
            })
        } else {
            None
        };

        (constructor_args, call_args, resources)
    }

    /// Extract config class and fields using direct file parsing
    #[allow(clippy::too_many_arguments)]
    fn extract_config_with_fields(
        discovery_root: &Path,
        source_path: &Path,
        cached: &CachedFile,
        entry: &EntryPointInfo,
        implementation: &ImplementationType,
        file_cache: &mut HashMap<PathBuf, Arc<CachedFile>>,
        package_cache: &mut Option<PackageAstCache>,
        package_name: &str,
    ) -> Option<ConfigSpec> {
        // First, find the config class name from the current file
        let config_name = Self::find_config_class_name(
            &cached.ast,
            &cached.content,
            &entry.symbol,
            implementation,
        )?;

        // Track where we found the config class to determine the correct module
        let mut config_file_path: Option<PathBuf> = None;

        // Try to extract fields from the same file first
        let mut fields = Self::extract_config_fields_from_ast(&cached.ast, &config_name);
        if !fields.is_empty() {
            // Config class is in the same file as the function
            config_file_path = Some(source_path.to_path_buf());
        }

        // If no fields found in the same file, search the package using ast-grep
        if fields.is_empty() {
            if package_cache.is_none() {
                *package_cache = Some(PackageAstCache::build(discovery_root));
            }

            if let Some(cache) = package_cache.as_ref() {
                if let Some((path, config_content)) = cache.find_config_class_content(&config_name)
                {
                    fields = Self::extract_config_fields(config_content, &config_name);
                    if !fields.is_empty() {
                        config_file_path = Some(path.clone());
                    }
                }
            }
        }

        // If still no fields, try looking in common locations relative to source file
        if fields.is_empty() {
            if let Some((path, config_content)) = Self::find_config_in_common_locations_with_path(
                source_path,
                &config_name,
                file_cache,
            ) {
                fields = Self::extract_config_fields(&config_content, &config_name);
                if !fields.is_empty() {
                    config_file_path = Some(path);
                }
            }
        }

        // Determine the config module path
        let config_module = if let Some(ref path) = config_file_path {
            // Use the file path where we found the config class to infer its module
            let path_str = path.to_string_lossy();
            Self::infer_module_from_file_path(&path_str, discovery_root, package_name)
        } else {
            // Fallback: try to resolve from imports in the source file
            Self::resolve_config_module_from_imports(&cached.content, &config_name, &entry.module)
                .unwrap_or_else(|| entry.module.to_string())
        };

        Some(ConfigSpec {
            module: config_module,
            name: config_name,
            fields,
        })
    }

    /// Find config class in common locations and return the path where it was found
    fn find_config_in_common_locations_with_path(
        source_path: &Path,
        config_name: &str,
        file_cache: &mut HashMap<PathBuf, Arc<CachedFile>>,
    ) -> Option<(PathBuf, String)> {
        let parent = source_path.parent()?;
        let class_with_base = format!("class {}(", config_name);
        let class_no_base = format!("class {}:", config_name);

        let candidates = [
            "__init__.py",
            "config.py",
            "configs.py",
            "types.py",
            "plugin_config.py",
        ];

        for filename in candidates {
            let candidate = parent.join(filename);
            if let Some(cached) = Self::read_file_cached(file_cache, &candidate) {
                if cached.content.contains(&class_with_base)
                    || cached.content.contains(&class_no_base)
                {
                    return Some((candidate, cached.content.clone()));
                }
            }
        }

        None
    }

    /// Resolve config module from import statements in the source file
    fn resolve_config_module_from_imports(
        content: &str,
        config_name: &str,
        current_module: &str,
    ) -> Option<String> {
        for line in content.lines() {
            let trimmed = line.trim();

            // Match: from X import Y or from X import Y, Z, ...
            if let Some(rest) = trimmed.strip_prefix("from ") {
                if let Some(import_idx) = rest.find(" import ") {
                    let from_part = rest[..import_idx].trim();
                    let import_part = rest[import_idx + 8..].trim();

                    // Check if our config class is in the import list
                    let imports: Vec<&str> = import_part
                        .split(',')
                        .map(|s| s.trim().split(" as ").next().unwrap_or(s.trim()).trim())
                        .collect();

                    if imports.contains(&config_name) {
                        // Resolve relative imports
                        if from_part.starts_with('.') {
                            let dot_count = from_part.chars().take_while(|c| *c == '.').count();
                            let relative_path = &from_part[dot_count..];

                            let mut parts: Vec<&str> = current_module.split('.').collect();
                            // Go up dot_count levels (one dot means same package)
                            for _ in 0..dot_count {
                                parts.pop();
                            }

                            if !relative_path.is_empty() {
                                parts.push(relative_path);
                            }

                            return Some(parts.join("."));
                        }
                        return Some(from_part.to_string());
                    }
                }
            }
        }
        None
    }

    // =========================================================================
    // HELPER METHODS - Used by cached discovery methods
    // =========================================================================

    /// Find config class name from content (function param or class generic) using AST
    fn find_config_class_name(
        ast: &PythonAst,
        content: &str,
        symbol: &str,
        implementation: &ImplementationType,
    ) -> Option<String> {
        if matches!(implementation, ImplementationType::Function) {
            return Self::extract_config_type_from_function_text(content, symbol);
        }

        let class_pattern = format!("class {}($$$BASES): $$$BODY", symbol);

        for class_match in ast.root().find_all(class_pattern.as_str()) {
            // ast-grep's $$$BASES doesn't capture correctly for Python class bases,
            // so we find the argument_list child which contains "(Plugin[Config], ...)"
            let config = class_match
                .children()
                .find(|c| c.kind() == "argument_list")
                .and_then(|arg_list| Self::extract_plugin_generic(&arg_list.text()));

            if config.is_some() {
                return config;
            }
        }

        None
    }

    /// Extract config name from "Plugin[ConfigName]" in a base class list
    fn extract_plugin_generic(bases_text: &str) -> Option<String> {
        let start = bases_text.find("Plugin[")?;
        let rest = &bases_text[start + 7..];
        let end = rest.find(']')?;
        let config_name = rest[..end].trim();

        if config_name.is_empty() {
            None
        } else {
            Some(config_name.to_string())
        }
    }

    /// Extract config type from function definition in content
    /// Finds "def symbol(..., config: ConfigClass, ...)" and extracts "ConfigClass"
    fn extract_config_type_from_function_text(content: &str, symbol: &str) -> Option<String> {
        // Find "def symbol(" in content
        let search = format!("def {}(", symbol);
        let start = content.find(&search)?;
        let after_start = &content[start + search.len()..];

        // Find closing paren (handle nested parens)
        let paren_end = Self::find_matching_paren(after_start)?;
        let params_text = &after_start[..paren_end];

        // Look for "config:" pattern
        let config_start = params_text.find("config:")?;
        let rest = &params_text[config_start + 7..];

        // Find end of type annotation (comma or end of string)
        let type_end = rest.find(|c| [',', ')'].contains(&c)).unwrap_or(rest.len());
        let config_type = rest[..type_end].trim();

        // Verify it ends with "Config"
        if config_type.ends_with("Config") {
            Some(config_type.to_string())
        } else {
            None
        }
    }

    /// Find the position of matching closing paren, handling nested parens/brackets
    fn find_matching_paren(text: &str) -> Option<usize> {
        let mut depth = 0;
        for (i, ch) in text.char_indices() {
            match ch {
                '(' | '[' | '{' => depth += 1,
                ')' => {
                    if depth == 0 {
                        return Some(i);
                    }
                    depth -= 1;
                }
                ']' | '}' => depth -= 1,
                _ => {}
            }
        }
        None
    }

    fn ast_has_class(ast: &PythonAst, class_name: &str) -> bool {
        let root = ast.root();
        let pattern = format!("class {}($$$BASES): $$$BODY", class_name);
        let found = root.find_all(pattern.as_str()).next().is_some();
        found
    }

    fn ast_has_function(ast: &PythonAst, function_name: &str) -> bool {
        let root = ast.root();
        // Match decorated or undecorated function definitions
        let pattern = format!("def {}($$$PARAMS): $$$BODY", function_name);
        let found = root.find_all(pattern.as_str()).next().is_some();
        found
    }

    fn resolve_reexported_symbol(content: &str, base_module: &str, symbol: &str) -> Option<String> {
        for line in content.lines() {
            let trimmed = line.trim();
            if !trimmed.starts_with("from ") {
                continue;
            }

            let Some(rest) = trimmed.strip_prefix("from ") else {
                continue;
            };
            let Some((from_part, import_part)) = rest.split_once(" import ") else {
                continue;
            };
            let from_part = from_part.trim();

            let import_part = import_part
                .split('#')
                .next()
                .unwrap_or(import_part)
                .trim()
                .trim_start_matches('(')
                .trim_end_matches(')');

            for item in import_part.split(',') {
                let name = item.trim();
                if name.is_empty() {
                    continue;
                }
                let name = name.split_whitespace().next().unwrap_or(name);
                if name != symbol {
                    continue;
                }

                if from_part.starts_with('.') {
                    let dot_count = from_part.chars().take_while(|c| *c == '.').count();
                    let levels_up = dot_count.saturating_sub(1);
                    let rel = &from_part[dot_count..];
                    let mut base_parts: Vec<&str> = base_module.split('.').collect();
                    if levels_up > 0 && base_parts.len() >= levels_up {
                        base_parts.truncate(base_parts.len() - levels_up);
                    }
                    let base_prefix = base_parts.join(".");
                    if rel.is_empty() {
                        return Some(base_prefix);
                    }
                    if base_prefix.is_empty() {
                        return Some(rel.to_string());
                    }
                    return Some(format!("{}.{}", base_prefix, rel));
                }

                return Some(from_part.to_string());
            }
        }

        None
    }

    /// Extract __init__ parameters from a class definition
    fn extract_class_init_params(ast: &PythonAst, class_name: &str) -> Vec<ArgumentSpec> {
        let root = ast.root();

        // Find class definition - early return if not found
        let pattern = format!("class {}($$$BASES): $$$BODY", class_name);
        if root.find_all(pattern.as_str()).next().is_none() {
            return Vec::new();
        }

        // Look for __init__ method within the class
        let init_pattern = "def __init__(self, $$$PARAMS): $$$BODY";
        for init_match in root.find_all(init_pattern) {
            if let Some(params) = Self::extract_params_from_match(&init_match) {
                return params;
            }
        }

        Vec::new()
    }

    /// Extract parameters from a function definition using text-based parsing
    fn extract_function_params(content: &str, function_name: &str) -> Vec<ArgumentSpec> {
        // Find "def function_name(" in content
        let search = format!("def {}(", function_name);
        let Some(start) = content.find(&search) else {
            return Vec::new();
        };
        let after_start = &content[start + search.len()..];

        // Find closing paren
        let Some(paren_end) = Self::find_matching_paren(after_start) else {
            return Vec::new();
        };
        let params_text = &after_start[..paren_end];

        let mut params = Vec::new();

        // Split by comma, respecting nested brackets
        let mut depth = 0;
        let mut param_start = 0;

        for (i, ch) in params_text.char_indices() {
            match ch {
                '[' | '(' | '{' => depth += 1,
                ']' | ')' | '}' => depth -= 1,
                ',' if depth == 0 => {
                    if let Some(arg) = Self::parse_function_param(&params_text[param_start..i]) {
                        params.push(arg);
                    }
                    param_start = i + 1;
                }
                _ => {}
            }
        }

        // Don't forget the last parameter
        if param_start < params_text.len() {
            if let Some(arg) = Self::parse_function_param(&params_text[param_start..]) {
                params.push(arg);
            }
        }

        params
    }

    /// Check if a parameter name should be skipped
    fn is_skipped_param(name: &str) -> bool {
        name.is_empty()
            || name == "self"
            || name == "system"
            || name == "kwargs"
            || name.starts_with('_')
    }

    /// Parse a single function parameter string into ArgumentSpec
    fn parse_function_param(param_str: &str) -> Option<ArgumentSpec> {
        let param_str = param_str.trim();

        // Skip empty, self, *args, **kwargs
        if param_str.is_empty() || param_str == "self" || param_str.starts_with('*') {
            return None;
        }

        let (name, annotation, default) = Self::parse_param_text(param_str);

        if Self::is_skipped_param(&name) {
            return None;
        }

        Some(ArgumentSpec {
            name,
            annotation,
            required: default.is_none(),
            default,
        })
    }

    /// Extract parameters from an AST match
    fn extract_params_from_match(
        func_match: &ast_grep_core::matcher::NodeMatch<'_, ast_grep_core::source::StrDoc<Python>>,
    ) -> Option<Vec<ArgumentSpec>> {
        let env = func_match.get_env();
        let params_nodes = env.get_multiple_matches("$$$PARAMS");

        let params = params_nodes
            .into_iter()
            .filter_map(|param_node| {
                let param_text = param_node.text();

                // Skip self, *args, **kwargs
                if param_text == "self" || param_text.starts_with('*') {
                    return None;
                }

                let (name, annotation, default) = Self::parse_param_text(&param_text);

                if Self::is_skipped_param(&name) {
                    return None;
                }

                Some(ArgumentSpec {
                    name,
                    annotation,
                    required: default.is_none(),
                    default,
                })
            })
            .collect();

        Some(params)
    }

    /// Parse a parameter text into name, annotation, and default
    fn parse_param_text(text: &str) -> (String, Option<String>, Option<String>) {
        let text = text.trim();

        // Handle: name: type = default
        if let Some(eq_idx) = text.find('=') {
            let before_eq = text[..eq_idx].trim();
            let default = text[eq_idx + 1..].trim().to_string();

            if let Some(colon_idx) = before_eq.find(':') {
                let name = before_eq[..colon_idx].trim().to_string();
                let annotation = before_eq[colon_idx + 1..].trim().to_string();
                return (name, Some(annotation), Some(default));
            } else {
                return (before_eq.to_string(), None, Some(default));
            }
        }

        // Handle: name: type
        if let Some(colon_idx) = text.find(':') {
            let name = text[..colon_idx].trim().to_string();
            let annotation = text[colon_idx + 1..].trim().to_string();
            return (name, Some(annotation), None);
        }

        // Handle: just name
        (text.to_string(), None, None)
    }

    /// Extract fields from a config class definition
    fn extract_config_fields(content: &str, class_name: &str) -> Vec<ConfigField> {
        let ast = PythonAst::new(content, Python);
        let root = ast.root();

        Self::extract_config_fields_from_root(&root, class_name)
    }

    fn extract_config_fields_from_ast(ast: &PythonAst, class_name: &str) -> Vec<ConfigField> {
        let root = ast.root();
        Self::extract_config_fields_from_root(&root, class_name)
    }

    fn extract_config_fields_from_root(
        root: &ast_grep_core::Node<'_, ast_grep_core::source::StrDoc<Python>>,
        class_name: &str,
    ) -> Vec<ConfigField> {
        use schema_extractor::{extract_description_from_field, parse_union_types_from_annotation};

        // Find the class definition
        let class_pattern = format!("class {}($$$): $$$BODY", class_name);
        let Some(class_match) = root.find_all(class_pattern.as_str()).next() else {
            return Vec::new();
        };

        // Pattern for annotated assignment: name: Type = value or name: Type
        let matches: Vec<_> = class_match.find_all("$NAME: $TYPE").collect();

        let mut fields = Vec::new();
        for m in matches {
            let full_text = m.text();

            // Parse name and type from the match text
            let Some(colon_pos) = full_text.find(':') else {
                continue;
            };

            let name = full_text[..colon_pos].trim().to_string();

            // Skip private/magic attributes and non-identifier names
            if name.starts_with('_')
                || !name
                    .chars()
                    .next()
                    .map(|c| c.is_alphabetic())
                    .unwrap_or(false)
            {
                continue;
            }

            // Extract type annotation - everything after the colon until = or end
            let after_colon = &full_text[colon_pos + 1..];
            let type_text = if let Some(eq_pos) = after_colon.rfind(" = ") {
                after_colon[..eq_pos].trim().to_string()
            } else {
                after_colon.trim().to_string()
            };

            // Parse union types from annotation (handles Annotated[] and union types)
            let types = parse_union_types_from_annotation(&type_text);

            // Extract description from Field(description="...")
            let description = extract_description_from_field(&full_text);

            // Check if there's a default value
            let has_default = full_text.contains(" = ") || full_text.contains("default=");

            // Determine if required
            let required =
                !has_default && !type_text.contains("None") && !type_text.starts_with("Optional");

            // Try to extract default value
            let default = if has_default {
                Self::extract_default_value(&full_text)
            } else {
                None
            };

            fields.push(ConfigField {
                name,
                types,
                default,
                required,
                description,
            });
        }

        fields
    }

    /// Extract default value from field definition text
    fn extract_default_value(text: &str) -> Option<String> {
        // Look for = value after the type annotation
        if let Some(eq_pos) = text.rfind(" = ") {
            let value_part = text[eq_pos + 3..].trim();
            // Skip if it's a Field() call - we'll extract default from there
            if value_part.starts_with("Field(") {
                // Try to extract from Field(default=...)
                if let Some(start) = value_part.find("default=") {
                    let rest = &value_part[start + 8..];
                    // Find the end of the default value
                    let mut depth = 0;
                    let mut end = 0;
                    for (i, ch) in rest.char_indices() {
                        match ch {
                            '(' | '[' | '{' => depth += 1,
                            ')' | ']' | '}' => {
                                if depth == 0 {
                                    end = i;
                                    break;
                                }
                                depth -= 1;
                            }
                            ',' if depth == 0 => {
                                end = i;
                                break;
                            }
                            _ => {}
                        }
                    }
                    if end > 0 {
                        let default_str = rest[..end].trim();
                        return Some(Self::clean_default_value(default_str));
                    }
                }
                return None;
            }
            return Some(Self::clean_default_value(value_part));
        }
        None
    }

    /// Clean up default value string (remove surrounding quotes if present)
    fn clean_default_value(value: &str) -> String {
        let value = value.trim();
        // Remove surrounding quotes for string values
        if (value.starts_with('"') && value.ends_with('"'))
            || (value.starts_with('\'') && value.ends_with('\''))
        {
            value[1..value.len() - 1].to_string()
        } else {
            value.to_string()
        }
    }

    /// Convert an ArgumentSpec to a ConfigField for function parameter extraction
    fn argument_to_config_field(arg: &ArgumentSpec) -> ConfigField {
        use schema_extractor::parse_union_types_from_annotation;

        let types = arg
            .annotation
            .as_deref()
            .map(parse_union_types_from_annotation)
            .unwrap_or_else(|| vec!["Any".to_string()]);

        let default = arg.default.as_deref().map(Self::clean_default_value);
        let required = arg.required && !types.iter().any(|t| t == "None");

        ConfigField {
            name: arg.name.clone(),
            types,
            default,
            required,
            description: None,
        }
    }

    /// Build IO contract based on plugin kind
    fn io_contract_for_kind(kind: &PluginKind) -> IOContract {
        match kind {
            PluginKind::Parser => IOContract {
                consumes: vec![IOSlot::StoreFolder, IOSlot::ConfigFile],
                produces: vec![IOSlot::System],
            },
            PluginKind::Exporter => IOContract {
                consumes: vec![IOSlot::System, IOSlot::ConfigFile],
                produces: vec![IOSlot::Folder],
            },
            PluginKind::Modifier | PluginKind::Translation => IOContract {
                consumes: vec![IOSlot::System],
                produces: vec![IOSlot::System],
            },
            PluginKind::Upgrader | PluginKind::Utility => IOContract {
                consumes: Vec::new(),
                produces: Vec::new(),
            },
        }
    }
}

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

    #[test]
    fn test_parse_all_entry_points_r2x_plugin() {
        let content = r#"[r2x_plugin]
reeds = r2x_reeds:ReEDSParser
"#;
        let entries = AstDiscovery::parse_all_entry_points(content);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "reeds");
        assert_eq!(entries[0].module, "r2x_reeds");
        assert_eq!(entries[0].symbol, "ReEDSParser");
        assert_eq!(entries[0].section, "r2x_plugin");
    }

    #[test]
    fn test_parse_all_entry_points_multiple_sections() {
        let content = r#"[r2x_plugin]
reeds = r2x_reeds:ReEDSParser

[r2x.transforms]
add-pcm-defaults = r2x_reeds.sysmod.pcm_defaults:add_pcm_defaults
add-emission-cap = r2x_reeds.sysmod.emission_cap:add_emission_cap

[console_scripts]
some-cli = some_module:main
"#;
        let entries = AstDiscovery::parse_all_entry_points(content);
        assert_eq!(entries.len(), 3);

        // Check r2x_plugin entry
        assert_eq!(entries[0].name, "reeds");
        assert_eq!(entries[0].section, "r2x_plugin");

        // Check r2x.transforms entries
        assert_eq!(entries[1].name, "add-pcm-defaults");
        assert_eq!(entries[1].section, "r2x.transforms");
        assert_eq!(entries[1].module, "r2x_reeds.sysmod.pcm_defaults");
        assert_eq!(entries[1].symbol, "add_pcm_defaults");

        assert_eq!(entries[2].name, "add-emission-cap");
        assert_eq!(entries[2].section, "r2x.transforms");
    }

    #[test]
    fn test_parse_all_entry_points_ignores_non_r2x_sections() {
        let content = r#"[console_scripts]
some-cli = some_module:main

[gui_scripts]
some-gui = some_module:gui_main
"#;
        let entries = AstDiscovery::parse_all_entry_points(content);
        assert!(entries.is_empty());
    }

    #[test]
    fn test_is_r2x_section() {
        assert!(AstDiscovery::is_r2x_section("r2x_plugin"));
        assert!(AstDiscovery::is_r2x_section("r2x.transforms"));
        assert!(AstDiscovery::is_r2x_section("r2x.parsers"));
        assert!(AstDiscovery::is_r2x_section("r2x.exporters"));
        assert!(!AstDiscovery::is_r2x_section("console_scripts"));
        assert!(!AstDiscovery::is_r2x_section("gui_scripts"));
    }

    #[test]
    fn test_entry_point_info_is_class() {
        let class_entry = EntryPointInfo {
            name: "reeds".to_string(),
            module: "r2x_reeds".to_string(),
            symbol: "ReEDSParser".to_string(),
            section: "r2x_plugin".to_string(),
        };
        assert!(class_entry.is_class());

        let func_entry = EntryPointInfo {
            name: "add-pcm-defaults".to_string(),
            module: "r2x_reeds.sysmod".to_string(),
            symbol: "add_pcm_defaults".to_string(),
            section: "r2x.transforms".to_string(),
        };
        assert!(!func_entry.is_class());
    }

    #[test]
    fn test_entry_point_info_infer_kind() {
        let parser_entry = EntryPointInfo {
            name: "reeds".to_string(),
            module: "r2x_reeds".to_string(),
            symbol: "ReEDSParser".to_string(),
            section: "r2x_plugin".to_string(),
        };
        assert_eq!(parser_entry.infer_kind(), PluginKind::Parser);

        let modifier_entry = EntryPointInfo {
            name: "add-pcm-defaults".to_string(),
            module: "r2x_reeds.sysmod".to_string(),
            symbol: "add_pcm_defaults".to_string(),
            section: "r2x.transforms".to_string(),
        };
        assert_eq!(modifier_entry.infer_kind(), PluginKind::Modifier);
    }

    #[test]
    fn test_resolve_reexported_symbol() {
        let content = r#"
from .parser import ReEDSParser
from .plugin_config import ReEDSConfig
"#;
        let resolved = AstDiscovery::resolve_reexported_symbol(content, "r2x_reeds", "ReEDSParser");
        assert_eq!(resolved, Some("r2x_reeds.parser".to_string()));
    }

    #[test]
    fn test_plugin_extraction() {
        let plugin = DiscoveredPlugin {
            name: "test-parser".to_string(),
            kind: PluginKind::Parser,
            entry: "TestParser".to_string(),
            invocation: InvocationSpec {
                implementation: ImplementationType::Class,
                method: Some("build_system".to_string()),
                constructor: vec![],
                call: vec![],
            },
            io: IOContract {
                consumes: vec![IOSlot::StoreFolder, IOSlot::ConfigFile],
                produces: vec![IOSlot::System],
            },
            resources: None,
            upgrade: None,
            description: None,
            tags: vec![],
        };

        assert_eq!(plugin.name, "test-parser");
        assert_eq!(plugin.kind, PluginKind::Parser);
        assert_eq!(plugin.entry, "TestParser");
    }

    #[test]
    fn test_parse_param_text() {
        // Test name: type = default
        let (name, ann, def) = AstDiscovery::parse_param_text("config: MyConfig = None");
        assert_eq!(name, "config");
        assert_eq!(ann, Some("MyConfig".to_string()));
        assert_eq!(def, Some("None".to_string()));

        // Test name: type
        let (name, ann, def) = AstDiscovery::parse_param_text("system: System");
        assert_eq!(name, "system");
        assert_eq!(ann, Some("System".to_string()));
        assert!(def.is_none());

        // Test just name
        let (name, ann, def) = AstDiscovery::parse_param_text("data");
        assert_eq!(name, "data");
        assert!(ann.is_none());
        assert!(def.is_none());
    }

    #[test]
    fn test_find_config_class_name_from_function() {
        // Test single-line function with return type
        let source_single = r#"
def add_pcm_defaults(system: System, config: PCMDefaultsConfig) -> Result[System, str]:
    pass
"#;
        let config_name =
            AstDiscovery::extract_config_type_from_function_text(source_single, "add_pcm_defaults");
        assert_eq!(config_name, Some("PCMDefaultsConfig".to_string()));

        // Test multi-line function with return type
        let source_multi = r#"
def add_pcm_defaults(
    system: System,
    config: PCMDefaultsConfig,
) -> Result[System, str]:
    pass
"#;
        let config_name_multi =
            AstDiscovery::extract_config_type_from_function_text(source_multi, "add_pcm_defaults");
        assert_eq!(config_name_multi, Some("PCMDefaultsConfig".to_string()));

        // Test function without return type
        let source_no_ret = r#"
def add_pcm_defaults(system: System, config: PCMDefaultsConfig):
    pass
"#;
        let config_name_no_ret =
            AstDiscovery::extract_config_type_from_function_text(source_no_ret, "add_pcm_defaults");
        assert_eq!(config_name_no_ret, Some("PCMDefaultsConfig".to_string()));
    }

    #[test]
    fn test_extract_function_params_direct() {
        let source = r#"
def add_pcm_defaults(
    system: System,
    pcm_defaults_fpath: str | None = None,
    pcm_defaults_dict: dict | None = None,
    pcm_defaults_override: bool = False,
) -> System:
    pass
"#;
        let params = AstDiscovery::extract_function_params(source, "add_pcm_defaults");
        // system should be filtered out
        assert!(!params.iter().any(|p| p.name == "system"));
        // Should have the 3 params
        assert_eq!(params.len(), 3);

        let fpath = params
            .iter()
            .find(|p| p.name == "pcm_defaults_fpath")
            .unwrap();
        assert_eq!(fpath.annotation.as_deref(), Some("str | None"));
        assert_eq!(fpath.default.as_deref(), Some("None"));
        assert!(!fpath.required);

        let override_param = params
            .iter()
            .find(|p| p.name == "pcm_defaults_override")
            .unwrap();
        assert_eq!(override_param.annotation.as_deref(), Some("bool"));
        assert_eq!(override_param.default.as_deref(), Some("False"));
    }

    #[test]
    fn test_argument_to_config_field() {
        let arg = discovery_types::ArgumentSpec {
            name: "pcm_defaults_fpath".to_string(),
            annotation: Some("str | None".to_string()),
            default: Some("None".to_string()),
            required: false,
        };
        let field = AstDiscovery::argument_to_config_field(&arg);
        assert_eq!(field.name, "pcm_defaults_fpath");
        assert_eq!(field.types, vec!["str".to_string(), "None".to_string()]);
        assert_eq!(field.default, Some("None".to_string()));
        assert!(!field.required);
    }

    #[test]
    fn test_camel_to_kebab() {
        // Simple CamelCase
        assert_eq!(AstDiscovery::camel_to_kebab("MyParser"), "my-parser");
        assert_eq!(
            AstDiscovery::camel_to_kebab("SimplePlugin"),
            "simple-plugin"
        );
        assert_eq!(AstDiscovery::camel_to_kebab("MyExporter"), "my-exporter");

        // Acronyms (consecutive uppercase)
        assert_eq!(AstDiscovery::camel_to_kebab("ReEDSParser"), "reeds-parser");
        assert_eq!(AstDiscovery::camel_to_kebab("XMLParser"), "xml-parser");
        assert_eq!(AstDiscovery::camel_to_kebab("HTTPClient"), "http-client");

        // Single word
        assert_eq!(AstDiscovery::camel_to_kebab("Parser"), "parser");
        assert_eq!(AstDiscovery::camel_to_kebab("Reeds"), "reeds");

        // All uppercase acronym
        assert_eq!(AstDiscovery::camel_to_kebab("HTTP"), "http");
        assert_eq!(AstDiscovery::camel_to_kebab("API"), "api");
    }

    #[test]
    fn test_snake_to_kebab() {
        assert_eq!(
            AstDiscovery::snake_to_kebab("add_pcm_defaults"),
            "add-pcm-defaults"
        );
        assert_eq!(AstDiscovery::snake_to_kebab("break_gens"), "break-gens");
        assert_eq!(AstDiscovery::snake_to_kebab("simple"), "simple");
        assert_eq!(AstDiscovery::snake_to_kebab("a_b_c"), "a-b-c");
    }

    #[test]
    fn test_deduplicate_entries() {
        let entries = vec![
            EntryPointInfo {
                name: "reeds".to_string(),
                module: "r2x_reeds".to_string(),
                symbol: "ReEDSParser".to_string(),
                section: "r2x_plugin".to_string(),
            },
            EntryPointInfo {
                name: "reeds-parser".to_string(), // Different name and module, but same symbol
                module: "r2x_reeds.parser".to_string(),
                symbol: "ReEDSParser".to_string(),
                section: "r2x_plugin".to_string(),
            },
            EntryPointInfo {
                name: "add-pcm-defaults".to_string(),
                module: "r2x_reeds.sysmod".to_string(),
                symbol: "add_pcm_defaults".to_string(),
                section: "r2x.transforms".to_string(),
            },
        ];

        let deduped = AstDiscovery::deduplicate_entries(entries);
        assert_eq!(deduped.len(), 2);
        // First occurrence should be preserved (entry_points.txt has priority)
        assert_eq!(deduped[0].name, "reeds");
        assert_eq!(deduped[0].module, "r2x_reeds"); // Original module preserved
        assert_eq!(deduped[1].name, "add-pcm-defaults");
    }

    #[test]
    fn test_extract_function_name_from_text() {
        // Simple function
        let text = "@expose_plugin\ndef add_pcm_defaults(system: System): pass";
        assert_eq!(
            AstDiscovery::extract_function_name_from_text(text),
            Some("add_pcm_defaults".to_string())
        );

        // Multi-line function
        let text_multi = r#"@expose_plugin
def break_gens(
    system: System,
    config: BreakGensConfig,
) -> System:
    pass"#;
        assert_eq!(
            AstDiscovery::extract_function_name_from_text(text_multi),
            Some("break_gens".to_string())
        );

        // No def keyword
        let text_no_def = "@expose_plugin\nclass MyClass: pass";
        assert_eq!(
            AstDiscovery::extract_function_name_from_text(text_no_def),
            None
        );
    }

    #[test]
    fn test_extract_class_name_from_match() {
        assert_eq!(
            AstDiscovery::extract_class_name_from_match("class MyParser(Plugin[Config]): pass"),
            Some("MyParser".to_string())
        );
        assert_eq!(
            AstDiscovery::extract_class_name_from_match(
                "class ReEDSParser(Plugin[ReEDSConfig]): pass"
            ),
            Some("ReEDSParser".to_string())
        );
        assert_eq!(
            AstDiscovery::extract_class_name_from_match("def my_func(): pass"),
            None
        );
    }

    #[test]
    fn test_find_config_class_name_from_class() {
        // Test class with generic Plugin[Config] - simple single line
        let source_simple = r#"class MyParser(Plugin[MyConfig]):
    pass
"#;
        let ast = PythonAst::new(source_simple, Python);
        let config_name = AstDiscovery::find_config_class_name(
            &ast,
            source_simple,
            "MyParser",
            &ImplementationType::Class,
        );
        assert_eq!(config_name, Some("MyConfig".to_string()));

        // Test class with generic Plugin[Config] - realistic example
        let source_reeds = r#"from r2x.api import Plugin

class ReEDSParser(Plugin[ReEDSConfig]):
    """ReEDS parser implementation."""

    def run(self):
        pass
"#;
        let ast_reeds = PythonAst::new(source_reeds, Python);
        let config_name_reeds = AstDiscovery::find_config_class_name(
            &ast_reeds,
            source_reeds,
            "ReEDSParser",
            &ImplementationType::Class,
        );
        assert_eq!(config_name_reeds, Some("ReEDSConfig".to_string()));

        // Test class with multiple bases - Plugin[Config] should still be found
        let source_multi_base = r#"class MyExporter(SomeMixin, Plugin[ExporterConfig], AnotherMixin):
    pass
"#;
        let ast_multi = PythonAst::new(source_multi_base, Python);
        let config_name_multi = AstDiscovery::find_config_class_name(
            &ast_multi,
            source_multi_base,
            "MyExporter",
            &ImplementationType::Class,
        );
        assert_eq!(config_name_multi, Some("ExporterConfig".to_string()));

        // Test class without Plugin generic - should return None
        let source_no_plugin = r#"class RegularClass(BaseClass):
    pass
"#;
        let ast_no_plugin = PythonAst::new(source_no_plugin, Python);
        let config_name_none = AstDiscovery::find_config_class_name(
            &ast_no_plugin,
            source_no_plugin,
            "RegularClass",
            &ImplementationType::Class,
        );
        assert_eq!(config_name_none, None);
    }
}