maproom 0.1.0

Semantic code search powered by embeddings and SQLite
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
//! C# parser for extracting symbol chunks from C# source code.
//!
//! This module implements chunk extraction for C# using the tree-sitter-c-sharp grammar (version 0.21.3).
//! It extracts 10 types of C# constructs: namespaces, classes, interfaces, structs, enums, methods,
//! constructors, properties, events, and delegates.
//!
//! ## Extraction Scope
//!
//! **Container types (recursively extracted):**
//! - `namespace` - Both block-scoped (`namespace Foo { }`) and file-scoped (`namespace Foo;`)
//! - `class` - Including generic type parameters, base classes, and interfaces
//! - `interface` - Including generic type parameters and base interfaces
//! - `struct` - Including generic type parameters and interfaces
//!
//! **Type declarations (extracted, not recursed into):**
//! - `enum` - Including base type (e.g., `enum Color : byte`)
//! - `delegate` - Including generic type parameters and method signatures
//!
//! **Member declarations (extracted from within container types):**
//! - `method` - Including generic type parameters, constraint clauses, expression-bodied methods
//! - `constructor` - Including parameters and initializers
//! - `property` - Including auto-properties, read-only properties, expression-bodied properties
//! - `event` - Event declarations with explicit add/remove accessors
//!
//! ## NOT Extracted
//!
//! The following C# constructs are intentionally not extracted:
//! - **Fields** - Too low-level for semantic search (local variable granularity)
//! - **Indexers** - Special case of properties, deferred to future enhancement
//! - **Operators** - Operator overloads, deferred to future enhancement
//! - **Records** - C# 9+ feature, deferred to follow-up ticket
//! - **Field-like events** - Events declared without explicit accessors (e.g., `public event EventHandler Click;`)
//!
//! ## Recursion Strategy
//!
//! The parser walks the AST recursively using `walk_csharp_decls()`:
//! - **Container types** (namespace, class, interface, struct) recurse into their body declarations
//! - **Member declarations** (method, constructor, property, event) do NOT recurse into their bodies
//! - **Type declarations** (enum, delegate) are leaf nodes (no body to recurse into)
//!
//! This strategy ensures we extract the declaration signatures without descending into implementation details.
//!
//! ## Documentation Comments
//!
//! C# uses XML documentation comments with `///` syntax. The parser extracts these by walking
//! backward from the declaration to collect all contiguous `///` lines, preserving XML tags for search.
//! Blank lines between comment blocks are allowed.
//!
//! ## Import Aggregation
//!
//! All `using` directives in a file are aggregated into a single `__imports__` chunk with kind `"imports"`.
//! This includes:
//! - Regular using directives (`using System;`)
//! - Static using directives (`using static System.Math;`)
//! - Using aliases (`using Json = System.Text.Json;`)
//! - Global using directives (`global using System;`)
//!
//! ## Grammar Compatibility
//!
//! This parser requires `tree-sitter-c-sharp = "0.21.3"` which is compatible with `tree-sitter = "0.22"`.
//! The grammar version is pinned to ensure AST node structure stability. Field names like `name`, `body`,
//! `parameters`, `type` are assumed to match the 0.21.3 grammar structure.
//!
//! ## Example
//!
//! ```csharp
//! namespace MyApp {
//!     /// <summary>Manages user authentication.</summary>
//!     public class AuthService {
//!         /// <summary>Authenticates a user.</summary>
//!         public bool Login(string username, string password) { ... }
//!     }
//! }
//! ```
//!
//! Extracts:
//! - 1 namespace chunk: `MyApp`
//! - 1 class chunk: `AuthService` with doc comment
//! - 1 method chunk: `Login(string username, string password) : bool` with doc comment

use tree_sitter::{Node, Parser};

use super::common::{extract_visibility_from_modifiers, lang_csharp};
use crate::indexer::SymbolChunk;

/// Maximum recursion depth for AST walking to prevent stack overflow.
/// Real C# code rarely exceeds 10 nesting levels. 100 provides safety margin.
const MAX_RECURSION_DEPTH: usize = 100;

pub(super) fn extract_csharp_chunks(source: &str) -> Vec<SymbolChunk> {
    let mut parser = Parser::new();
    parser
        .set_language(&lang_csharp())
        .expect("Failed to set C# language");

    let tree = parser.parse(source, None);

    // Debug logging for parse errors (helpful for troubleshooting)
    if let Some(ref tree) = tree {
        if tree.root_node().has_error() {
            tracing::debug!("C# parse produced error nodes, extraction may be partial");
        }
    }

    let mut chunks = Vec::new();

    if let Some(tree) = tree {
        let root = tree.root_node();
        let mut imports = Vec::new();
        walk_csharp_decls(source, root, &mut chunks, &mut imports, 0);

        // Create __imports__ chunk if we collected any imports
        if !imports.is_empty() {
            chunks.push(SymbolChunk {
                symbol_name: Some("__imports__".to_string()),
                kind: "imports".to_string(),
                signature: None,
                docstring: None,
                start_line: 1,
                end_line: 1,
                metadata: Some(serde_json::json!(imports)),
            });
        }
    }

    chunks
}

fn walk_csharp_decls(
    source: &str,
    node: Node,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    // Prevent stack overflow on pathological input (deeply nested types)
    if depth >= MAX_RECURSION_DEPTH {
        tracing::debug!(
            "Recursion depth limit ({}) reached, stopping AST walk",
            MAX_RECURSION_DEPTH
        );
        return;
    }

    match node.kind() {
        "class_declaration" => extract_csharp_class(source, node, chunks, imports, depth),
        "interface_declaration" => extract_csharp_interface(source, node, chunks, imports, depth),
        "struct_declaration" => extract_csharp_struct(source, node, chunks, imports, depth),
        "enum_declaration" => extract_csharp_enum(source, node, chunks),
        "delegate_declaration" => extract_csharp_delegate(source, node, chunks),
        "namespace_declaration" | "file_scoped_namespace_declaration" => {
            extract_csharp_namespace(source, node, chunks, imports, depth)
        }
        "method_declaration" => extract_csharp_method(source, node, chunks),
        "constructor_declaration" => extract_csharp_constructor(source, node, chunks),
        "property_declaration" => extract_csharp_property(source, node, chunks),
        "event_declaration" => extract_csharp_event(source, node, chunks),
        "event_field_declaration" => extract_csharp_event_field(source, node, chunks),
        "using_directive" => collect_csharp_using(source, node, imports),
        _ => {
            // Recurse into children for unhandled node types
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                walk_csharp_decls(source, child, chunks, imports, depth + 1);
            }
        }
    }
}

/// Find first child node with the given kind (for nodes not registered as fields)
#[allow(clippy::manual_find)]
fn find_child_by_kind<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == kind {
            return Some(child);
        }
    }
    None
}

/// Helper function for extracting type declarations (class, interface, struct).
///
/// Handles common logic shared by class, interface, and struct extractors:
/// name extraction, visibility, modifiers, generics, base list, doc comment,
/// signature building, chunk creation, and body recursion.
///
/// The `kind` parameter determines the chunk kind ("class", "interface", "struct")
/// and also controls which modifier flags are included in metadata:
/// - `"class"`: `is_abstract`, `is_static`, `is_partial`
/// - `"interface"`: `is_partial`
/// - `"struct"`: `is_static`, `is_partial`
fn extract_type_declaration(
    source: &str,
    node: Node,
    kind: &str,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    // Extract name from 'name' field
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    // Extract visibility and modifiers
    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );
    let modifiers = extract_csharp_modifiers(node, source);

    // Extract generics from 'type_parameter_list'
    let generics = find_child_by_kind(node, "type_parameter_list")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract base types from 'base_list'
    let base_list =
        find_child_by_kind(node, "base_list").and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract doc comment
    let docstring = extract_csharp_doc_comment(source, node);

    // Build signature
    let mut signature = String::new();
    if let Some(generics_str) = generics {
        signature.push_str(generics_str);
    }
    if let Some(base_str) = base_list {
        if !signature.is_empty() {
            signature.push(' ');
        }
        signature.push_str(base_str);
    }

    // Build metadata with kind-specific modifier flags
    let metadata = match kind {
        "class" => serde_json::json!({
            "visibility": visibility,
            "base_types": base_list,
            "is_abstract": modifiers.contains(&"abstract".to_string()),
            "is_static": modifiers.contains(&"static".to_string()),
            "is_partial": modifiers.contains(&"partial".to_string()),
        }),
        "interface" => serde_json::json!({
            "visibility": visibility,
            "base_types": base_list,
            "is_partial": modifiers.contains(&"partial".to_string()),
        }),
        "struct" => serde_json::json!({
            "visibility": visibility,
            "base_types": base_list,
            "is_static": modifiers.contains(&"static".to_string()),
            "is_partial": modifiers.contains(&"partial".to_string()),
        }),
        _ => serde_json::json!({
            "visibility": visibility,
            "base_types": base_list,
        }),
    };

    // Push chunk
    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: kind.to_string(),
            signature: if signature.is_empty() {
                None
            } else {
                Some(signature)
            },
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }

    // Recurse into body for nested members
    if let Some(body) = node.child_by_field_name("body") {
        let mut cursor = body.walk();
        for child in body.children(&mut cursor) {
            walk_csharp_decls(source, child, chunks, imports, depth + 1);
        }
    }
}

fn extract_csharp_class(
    source: &str,
    node: Node,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    extract_type_declaration(source, node, "class", chunks, imports, depth);
}

fn extract_csharp_interface(
    source: &str,
    node: Node,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    extract_type_declaration(source, node, "interface", chunks, imports, depth);
}

fn extract_csharp_struct(
    source: &str,
    node: Node,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    extract_type_declaration(source, node, "struct", chunks, imports, depth);
}

fn extract_csharp_enum(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );

    // Extract underlying type from base_list (e.g., ": byte")
    let base_list =
        find_child_by_kind(node, "base_list").and_then(|n| n.utf8_text(source.as_bytes()).ok());

    let docstring = extract_csharp_doc_comment(source, node);

    let metadata = serde_json::json!({
        "visibility": visibility,
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "enum".to_string(),
            signature: base_list.map(|s| s.to_string()),
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }

    // Do NOT recurse into enum body (members are not standalone symbols)
}

fn extract_csharp_delegate(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );

    // Extract return type
    let return_type = node
        .child_by_field_name("type")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract parameters
    let parameters = node
        .child_by_field_name("parameters")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract generics
    let generics = find_child_by_kind(node, "type_parameter_list")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    let docstring = extract_csharp_doc_comment(source, node);

    // Build signature: <T>(int x, string y) : ReturnType
    let mut signature = String::new();
    if let Some(g) = generics {
        signature.push_str(g);
    }
    if let Some(p) = parameters {
        signature.push_str(p);
    }
    if let Some(rt) = return_type {
        if !signature.is_empty() {
            signature.push_str(" : ");
        }
        signature.push_str(rt);
    }

    let metadata = serde_json::json!({
        "visibility": visibility,
        "return_type": return_type,
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "delegate".to_string(),
            signature: if signature.is_empty() {
                None
            } else {
                Some(signature)
            },
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }
}

// Stub functions - to be implemented in later tasks

fn extract_csharp_method(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );
    let modifiers = extract_csharp_modifiers(node, source);

    // Extract return type using field access (O(1) lookup)
    // tree-sitter-c-sharp grammar exposes return type as field('returns', $.type)
    let return_type = node
        .child_by_field_name("returns")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract parameters
    let parameters = node
        .child_by_field_name("parameters")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract generics - use child_by_field_name for type_parameters field
    let type_params = node
        .child_by_field_name("type_parameters")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract type parameter constraints (where clauses)
    let mut constraints = Vec::new();
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "type_parameter_constraints_clause" {
            if let Ok(constraint_text) = child.utf8_text(source.as_bytes()) {
                constraints.push(constraint_text.to_string());
            }
        }
    }

    let docstring = extract_csharp_doc_comment(source, node);

    // Build signature: <T>(int x, string y) : ReturnType where T : IComparable
    let mut signature = String::new();
    if let Some(tp) = type_params {
        signature.push_str(tp);
    }
    if let Some(p) = parameters {
        signature.push_str(p);
    }
    if let Some(rt) = return_type {
        // Always add return type with : separator
        signature.push_str(" : ");
        signature.push_str(rt);
    }
    if !constraints.is_empty() {
        signature.push(' ');
        signature.push_str(&constraints.join(" "));
    }

    let metadata = serde_json::json!({
        "visibility": visibility,
        "return_type": return_type,
        "is_static": modifiers.contains(&"static".to_string()),
        "is_async": modifiers.contains(&"async".to_string()),
        "is_virtual": modifiers.contains(&"virtual".to_string()),
        "is_override": modifiers.contains(&"override".to_string()),
        "is_abstract": modifiers.contains(&"abstract".to_string()),
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "method".to_string(),
            signature: if signature.is_empty() {
                None
            } else {
                Some(signature)
            },
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }

    // Do NOT recurse into method body
}

fn extract_csharp_constructor(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );

    // Extract parameters
    let parameters = node
        .child_by_field_name("parameters")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    // Extract constructor initializer (: base(...) or : this(...))
    // Note: constructor_initializer is a child node kind, not a field
    let initializer = find_child_by_kind(node, "constructor_initializer")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    let docstring = extract_csharp_doc_comment(source, node);

    // Signature is just the parameters
    let signature = parameters.map(|s| s.to_string());

    let metadata = serde_json::json!({
        "visibility": visibility,
        "initializer": initializer,
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "constructor".to_string(),
            signature,
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }

    // Do NOT recurse into constructor body
}

fn extract_csharp_property(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );

    // Extract type
    let prop_type = node
        .child_by_field_name("type")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    let docstring = extract_csharp_doc_comment(source, node);

    // Determine accessor pattern
    let mut signature = String::new();
    if let Some(pt) = prop_type {
        signature.push_str(pt);
        signature.push(' ');
    }

    // Check for accessor list (get/set/init)
    // Note: accessor_list is a child node kind, not a field
    if let Some(accessor_list) = find_child_by_kind(node, "accessor_list") {
        if let Ok(accessor_text) = accessor_list.utf8_text(source.as_bytes()) {
            signature.push_str(accessor_text);
        }
    } else {
        // Expression-bodied property (=> expr)
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "arrow_expression_clause" {
                signature.push_str("=> ...");
                break;
            }
        }
    }

    let metadata = serde_json::json!({
        "visibility": visibility,
        "type": prop_type,
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "property".to_string(),
            signature: if signature.is_empty() {
                None
            } else {
                Some(signature)
            },
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }
}

fn extract_csharp_event(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );

    // Extract type (event handler type)
    let event_type = node
        .child_by_field_name("type")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok());

    let docstring = extract_csharp_doc_comment(source, node);

    let signature = event_type.map(|s| s.to_string());

    let metadata = serde_json::json!({
        "visibility": visibility,
        "type": event_type,
    });

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "event".to_string(),
            signature,
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(metadata),
        });
    }
}

fn extract_csharp_event_field(source: &str, node: Node, chunks: &mut Vec<SymbolChunk>) {
    // Event field declarations can have multiple declarators
    let visibility = extract_visibility_from_modifiers(
        &node,
        source,
        &["public", "private", "protected", "internal"],
        "private",
    );
    let docstring = extract_csharp_doc_comment(source, node);

    // Extract type - it's in the variable_declaration child
    let event_type = if let Some(var_decl_node) = node
        .children(&mut node.walk())
        .find(|n| n.kind() == "variable_declaration")
    {
        var_decl_node
            .child_by_field_name("type")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
    } else {
        node.child_by_field_name("type")
            .and_then(|n| n.utf8_text(source.as_bytes()).ok())
    };

    // Event fields can declare multiple events in one statement
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "variable_declaration" {
            // variable_declaration contains variable_declarator children
            let mut var_cursor = child.walk();
            for var_child in child.children(&mut var_cursor) {
                if var_child.kind() == "variable_declarator" {
                    if let Some(name_node) = var_child.child_by_field_name("name") {
                        if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                            let signature = event_type.map(|s| s.to_string());

                            let metadata = serde_json::json!({
                                "visibility": visibility,
                                "type": event_type,
                            });

                            chunks.push(SymbolChunk {
                                symbol_name: Some(name.to_string()),
                                kind: "event".to_string(),
                                signature,
                                docstring: docstring.clone(),
                                start_line: (var_child.start_position().row + 1) as i32,
                                end_line: (var_child.end_position().row + 1) as i32,
                                metadata: Some(metadata),
                            });
                        }
                    }
                }
            }
        }
    }
}

fn extract_csharp_namespace(
    source: &str,
    node: Node,
    chunks: &mut Vec<SymbolChunk>,
    imports: &mut Vec<serde_json::Value>,
    depth: usize,
) {
    // Extract qualified name (e.g., "MyCompany.MyProduct")
    let name = node
        .child_by_field_name("name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string());

    let docstring = extract_csharp_doc_comment(source, node);

    if let Some(name) = name {
        chunks.push(SymbolChunk {
            symbol_name: Some(name),
            kind: "namespace".to_string(),
            signature: None,
            docstring,
            start_line: (node.start_position().row + 1) as i32,
            end_line: (node.end_position().row + 1) as i32,
            metadata: Some(serde_json::json!({})),
        });
    }

    // Recurse into namespace body
    if node.kind() == "namespace_declaration" {
        // Block-scoped namespace: recurse into body
        if let Some(body) = node.child_by_field_name("body") {
            for child in body.children(&mut body.walk()) {
                walk_csharp_decls(source, child, chunks, imports, depth + 1);
            }
        }
    } else if node.kind() == "file_scoped_namespace_declaration" {
        // File-scoped namespace: types are siblings, not children
        // Walk all siblings following this namespace declaration
        if let Some(parent) = node.parent() {
            let mut start_walking = false;
            for sibling in parent.children(&mut parent.walk()) {
                if sibling.id() == node.id() {
                    start_walking = true;
                    continue;
                }
                if start_walking {
                    walk_csharp_decls(source, sibling, chunks, imports, depth + 1);
                }
            }
        }
    }
}

fn collect_csharp_using(source: &str, node: Node, imports: &mut Vec<serde_json::Value>) {
    // Using directives can be:
    // - Regular: using System.Collections.Generic;
    // - Static: using static Math;
    // - Global: global using System;
    // - Alias: using Alias = Namespace.Type;

    let mut using_type = "regular";
    let mut target = String::new();

    // Check for 'global' modifier
    let has_global = node
        .children(&mut node.walk())
        .any(|c| c.kind() == "global");

    if has_global {
        using_type = "global";
    }

    // Check for 'static' keyword
    let has_static = node
        .children(&mut node.walk())
        .any(|c| c.kind() == "static");

    if has_static {
        using_type = if has_global {
            "global_static"
        } else {
            "static"
        };
    }

    // Check for alias (presence of '=' child)
    let has_equals = node.children(&mut node.walk()).any(|c| c.kind() == "=");

    if has_equals {
        using_type = "alias";
        // Collect all identifier and qualified_name children
        // First identifier is the alias, subsequent ones are the target
        let mut found_alias = false;
        for child in node.children(&mut node.walk()) {
            if child.kind() == "identifier" && !found_alias {
                // First identifier is the alias name
                if let Ok(text) = child.utf8_text(source.as_bytes()) {
                    target.push_str(text);
                    target.push_str(" = ");
                    found_alias = true;
                }
            } else if child.kind() == "qualified_name"
                || (child.kind() == "identifier" && found_alias)
            {
                // Target type
                if let Ok(text) = child.utf8_text(source.as_bytes()) {
                    target.push_str(text);
                    break;
                }
            }
        }
    } else {
        // Extract target namespace/type
        // The target is either an identifier or qualified_name child
        for child in node.children(&mut node.walk()) {
            if child.kind() == "identifier" || child.kind() == "qualified_name" {
                if let Ok(text) = child.utf8_text(source.as_bytes()) {
                    target.push_str(text);
                    break;
                }
            }
        }
    }

    if !target.is_empty() {
        imports.push(serde_json::json!({
            "type": using_type,
            "target": target,
        }));
    }
}

fn extract_csharp_doc_comment(source: &str, node: Node) -> Option<String> {
    let start_row = node.start_position().row;
    if start_row == 0 {
        return None;
    }

    let lines: Vec<&str> = source.lines().collect();
    let mut doc_lines = Vec::new();

    // Walk backward from the line before the node
    for i in (0..start_row).rev() {
        let line = lines[i].trim();

        if line.starts_with("///") {
            // Doc comment line - strip prefix and collect
            let content = line.strip_prefix("///").unwrap_or("");
            let content = content.strip_prefix(' ').unwrap_or(content);
            doc_lines.push(content.to_string());
        } else if line.is_empty() {
            // Blank line - continue searching
            continue;
        } else if line.starts_with("//") {
            // Regular comment - stop searching
            break;
        } else {
            // Non-comment line - stop searching
            break;
        }
    }

    if doc_lines.is_empty() {
        return None;
    }

    // Reverse to get original order
    doc_lines.reverse();
    Some(doc_lines.join("\n"))
}

fn extract_csharp_modifiers(node: Node, source: &str) -> Vec<String> {
    let mut modifiers = Vec::new();

    for child in node.children(&mut node.walk()) {
        if child.kind() == "modifier" {
            if let Ok(modifier_text) = child.utf8_text(source.as_bytes()) {
                modifiers.push(modifier_text.to_string());
            }
        }
    }

    modifiers
}

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

    #[test]
    fn test_extract_class() {
        let source = r#"
public class MyClass<T> : BaseClass, IInterface {
    public void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].kind, "class");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("MyClass"));

        // Verify visibility is extracted correctly
        let metadata = chunks[0].metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "public");
    }

    #[test]
    fn test_extract_interface() {
        let source = r#"
interface IMyInterface<T> : IBase {
    void Method();
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].kind, "interface");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("IMyInterface"));
    }

    #[test]
    fn test_extract_struct() {
        let source = r#"
public struct MyStruct : IInterface {
    public int Value;
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].kind, "struct");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("MyStruct"));
    }

    #[test]
    fn test_extract_enum() {
        let source = r#"
public enum Color : byte {
    Red,
    Green,
    Blue
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].kind, "enum");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("Color"));
        assert!(chunks[0].signature.as_deref().unwrap().contains("byte"));
    }

    #[test]
    fn test_extract_delegate() {
        let source = r#"
public delegate void MyDelegate<T>(int x, string y);
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(!chunks.is_empty());
        assert_eq!(chunks[0].kind, "delegate");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("MyDelegate"));
    }

    #[test]
    fn test_nested_types() {
        let source = r#"
public class OuterClass {
    public class InnerClass {
        public void Method() {}
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(chunks.len() >= 2);
        assert_eq!(chunks[0].kind, "class");
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("OuterClass"));
        assert_eq!(chunks[1].kind, "class");
        assert_eq!(chunks[1].symbol_name.as_deref(), Some("InnerClass"));
    }

    #[test]
    fn test_enum_no_recursion() {
        let source = r#"
public enum Status {
    Active,
    Inactive
}
"#;
        let chunks = extract_csharp_chunks(source);
        // Should only have the enum itself, not the members
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].kind, "enum");
    }

    // Member extractor tests (task 2002)

    #[test]
    fn test_extract_method_basic() {
        let source = r#"
class MyClass {
    public void DoSomething(int x, string y) {
        // body
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(chunks.len() >= 2);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("DoSomething"));
        assert!(method
            .signature
            .as_ref()
            .unwrap()
            .contains("(int x, string y)"));
        assert!(method.signature.as_ref().unwrap().contains("void"));
    }

    #[test]
    fn test_extract_method_with_generics() {
        let source = r#"
class MyClass {
    public T Get<T>(string key) {
        return default(T);
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("Get"));
        assert!(method.signature.as_ref().unwrap().contains("<T>"));
        assert!(method.signature.as_ref().unwrap().contains("(string key)"));
        assert!(method.signature.as_ref().unwrap().contains(": T"));
    }

    #[test]
    fn test_extract_method_with_constraints() {
        let source = r#"
class MyClass {
    public T Process<T>(T item) where T : IComparable {
        return item;
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("Process"));
        let sig = method.signature.as_ref().unwrap();
        assert!(sig.contains("<T>"));
        assert!(sig.contains("where T : IComparable"));
    }

    #[test]
    fn test_extract_method_async() {
        let source = r#"
class MyClass {
    public async Task<int> FetchAsync() {
        return 42;
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("FetchAsync"));
        // is_async should now be true after implementing modifiers
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_async"], true);
        assert_eq!(metadata["visibility"], "public");
    }

    #[test]
    fn test_extract_method_static_virtual_override() {
        let source = r#"
class MyClass {
    public static void StaticMethod() {}
    public virtual void VirtualMethod() {}
    public override void OverrideMethod() {}
    public abstract void AbstractMethod();
}
"#;
        let chunks = extract_csharp_chunks(source);
        let methods: Vec<_> = chunks.iter().filter(|c| c.kind == "method").collect();
        assert!(methods.len() >= 4);

        // Modifiers should now be extracted correctly
        let static_method = methods
            .iter()
            .find(|m| m.symbol_name.as_deref() == Some("StaticMethod"))
            .unwrap();
        assert_eq!(static_method.metadata.as_ref().unwrap()["is_static"], true);
        assert_eq!(
            static_method.metadata.as_ref().unwrap()["visibility"],
            "public"
        );

        let virtual_method = methods
            .iter()
            .find(|m| m.symbol_name.as_deref() == Some("VirtualMethod"))
            .unwrap();
        assert_eq!(
            virtual_method.metadata.as_ref().unwrap()["is_virtual"],
            true
        );

        let override_method = methods
            .iter()
            .find(|m| m.symbol_name.as_deref() == Some("OverrideMethod"))
            .unwrap();
        assert_eq!(
            override_method.metadata.as_ref().unwrap()["is_override"],
            true
        );

        let abstract_method = methods
            .iter()
            .find(|m| m.symbol_name.as_deref() == Some("AbstractMethod"))
            .unwrap();
        assert_eq!(
            abstract_method.metadata.as_ref().unwrap()["is_abstract"],
            true
        );
    }

    #[test]
    fn test_extract_constructor_basic() {
        let source = r#"
class MyClass {
    public MyClass(int x) {
        // body
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let constructor = chunks.iter().find(|c| c.kind == "constructor").unwrap();
        assert_eq!(constructor.symbol_name.as_deref(), Some("MyClass"));
        assert!(constructor.signature.as_ref().unwrap().contains("(int x)"));
    }

    #[test]
    fn test_extract_constructor_with_initializer() {
        let source = r#"
class MyClass {
    public MyClass(int x) : base(x) {
        // body
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let constructor = chunks.iter().find(|c| c.kind == "constructor").unwrap();
        assert_eq!(constructor.symbol_name.as_deref(), Some("MyClass"));
        let metadata = constructor.metadata.as_ref().unwrap();
        assert!(metadata["initializer"]
            .as_str()
            .unwrap()
            .contains(": base(x)"));
    }

    #[test]
    fn test_extract_property_auto() {
        let source = r#"
class MyClass {
    public string Name { get; set; }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let property = chunks.iter().find(|c| c.kind == "property").unwrap();
        assert_eq!(property.symbol_name.as_deref(), Some("Name"));
        let sig = property.signature.as_ref().unwrap();
        assert!(sig.contains("string"));
        assert!(sig.contains("get") && sig.contains("set"));
    }

    #[test]
    fn test_extract_property_get_only() {
        let source = r#"
class MyClass {
    public int Count { get; }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let property = chunks.iter().find(|c| c.kind == "property").unwrap();
        assert_eq!(property.symbol_name.as_deref(), Some("Count"));
        let sig = property.signature.as_ref().unwrap();
        assert!(sig.contains("int"));
        assert!(sig.contains("get"));
        assert!(!sig.contains("set"));
    }

    #[test]
    fn test_extract_property_expression_bodied() {
        let source = r#"
class MyClass {
    public string FullName => $"{First} {Last}";
}
"#;
        let chunks = extract_csharp_chunks(source);
        let property = chunks.iter().find(|c| c.kind == "property").unwrap();
        assert_eq!(property.symbol_name.as_deref(), Some("FullName"));
        let sig = property.signature.as_ref().unwrap();
        assert!(sig.contains("string"));
        assert!(sig.contains("=>"));
    }

    #[test]
    fn test_extract_event_declaration() {
        let source = r#"
class MyClass {
    public event EventHandler MyEvent {
        add { }
        remove { }
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let event = chunks.iter().find(|c| c.kind == "event").unwrap();
        assert_eq!(event.symbol_name.as_deref(), Some("MyEvent"));
        assert_eq!(
            event.signature.as_deref(),
            Some("EventHandler"),
            "Event signature should be the type"
        );
    }

    #[test]
    fn test_extract_event_field() {
        let source = r#"
class MyClass {
    public event EventHandler OnClick, OnHover;
}
"#;
        let chunks = extract_csharp_chunks(source);
        let events: Vec<_> = chunks.iter().filter(|c| c.kind == "event").collect();
        assert_eq!(events.len(), 2);

        let onclick = events
            .iter()
            .find(|e| e.symbol_name.as_deref() == Some("OnClick"))
            .unwrap();
        assert_eq!(onclick.signature.as_deref(), Some("EventHandler"));

        let onhover = events
            .iter()
            .find(|e| e.symbol_name.as_deref() == Some("OnHover"))
            .unwrap();
        assert_eq!(onhover.signature.as_deref(), Some("EventHandler"));
    }

    #[test]
    fn test_method_no_recursion() {
        let source = r#"
class MyClass {
    public void Outer() {
        void LocalFunction() {
            // local function
        }
    }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let methods: Vec<_> = chunks.iter().filter(|c| c.kind == "method").collect();
        // Should only extract Outer, not LocalFunction (no recursion into body)
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].symbol_name.as_deref(), Some("Outer"));
    }

    #[test]
    fn test_class_with_members() {
        let source = r#"
class MyClass {
    public MyClass() {}
    public void Method() {}
    public string Name { get; set; }
    public event EventHandler OnEvent;
}
"#;
        let chunks = extract_csharp_chunks(source);
        assert!(chunks.len() >= 5); // class + constructor + method + property + event

        assert!(chunks.iter().any(|c| c.kind == "class"));
        assert!(chunks.iter().any(|c| c.kind == "constructor"));
        assert!(chunks.iter().any(|c| c.kind == "method"));
        assert!(chunks.iter().any(|c| c.kind == "property"));
        assert!(chunks.iter().any(|c| c.kind == "event"));
    }

    // Namespace and using directive tests (task 2003)

    #[test]
    fn test_extract_block_scoped_namespace() {
        let source = r#"
namespace MyCompany.MyProduct {
    public class MyClass {
        public void Method() {}
    }
}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should have namespace + class + method
        let namespace = chunks.iter().find(|c| c.kind == "namespace").unwrap();
        assert_eq!(
            namespace.symbol_name.as_deref(),
            Some("MyCompany.MyProduct")
        );
        assert_eq!(namespace.kind, "namespace");

        // Class should be extracted from namespace body
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert_eq!(class.symbol_name.as_deref(), Some("MyClass"));

        // Method should be extracted from class body
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("Method"));
    }

    #[test]
    fn test_extract_file_scoped_namespace() {
        let source = r#"
namespace MyCompany.MyProduct;

public class MyClass {
    public void Method() {}
}

public interface IMyInterface {
}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should have namespace + class + method + interface
        let namespace = chunks.iter().find(|c| c.kind == "namespace").unwrap();
        assert_eq!(
            namespace.symbol_name.as_deref(),
            Some("MyCompany.MyProduct")
        );
        assert_eq!(namespace.kind, "namespace");

        // Class should be extracted (sibling to namespace)
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert_eq!(class.symbol_name.as_deref(), Some("MyClass"));

        // Interface should be extracted (sibling to namespace)
        let interface = chunks.iter().find(|c| c.kind == "interface").unwrap();
        assert_eq!(interface.symbol_name.as_deref(), Some("IMyInterface"));

        // Method should be extracted from class body
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(method.symbol_name.as_deref(), Some("Method"));
    }

    #[test]
    fn test_nested_namespaces() {
        let source = r#"
namespace Outer {
    namespace Inner {
        public class MyClass {}
    }
}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should extract both namespaces
        let namespaces: Vec<_> = chunks.iter().filter(|c| c.kind == "namespace").collect();
        assert_eq!(namespaces.len(), 2);

        // Find outer namespace
        let outer = namespaces
            .iter()
            .find(|n| n.symbol_name.as_deref() == Some("Outer"))
            .unwrap();
        assert_eq!(outer.kind, "namespace");

        // Find inner namespace
        let inner = namespaces
            .iter()
            .find(|n| n.symbol_name.as_deref() == Some("Inner"))
            .unwrap();
        assert_eq!(inner.kind, "namespace");

        // Class should be extracted
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert_eq!(class.symbol_name.as_deref(), Some("MyClass"));
    }

    #[test]
    fn test_using_directive_regular() {
        let source = r#"
using System;
using System.Collections.Generic;

class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should have __imports__ chunk
        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        assert_eq!(imports.symbol_name.as_deref(), Some("__imports__"));

        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();
        assert_eq!(imports_array.len(), 2);

        // Check first using
        assert_eq!(imports_array[0]["type"], "regular");
        assert_eq!(imports_array[0]["target"], "System");

        // Check second using
        assert_eq!(imports_array[1]["type"], "regular");
        assert_eq!(imports_array[1]["target"], "System.Collections.Generic");
    }

    #[test]
    fn test_using_directive_static() {
        let source = r#"
using static System.Math;

class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();

        assert_eq!(imports_array.len(), 1);
        assert_eq!(imports_array[0]["type"], "static");
        assert_eq!(imports_array[0]["target"], "System.Math");
    }

    #[test]
    fn test_using_directive_global() {
        let source = r#"
global using System;

class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();

        assert_eq!(imports_array.len(), 1);
        assert_eq!(imports_array[0]["type"], "global");
        assert_eq!(imports_array[0]["target"], "System");
    }

    #[test]
    fn test_using_directive_global_static() {
        let source = r#"
global using static System.Math;

class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();

        assert_eq!(imports_array.len(), 1);
        assert_eq!(imports_array[0]["type"], "global_static");
        assert_eq!(imports_array[0]["target"], "System.Math");
    }

    #[test]
    fn test_using_directive_alias() {
        let source = r#"
using StringList = System.Collections.Generic.List<string>;

class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();

        assert_eq!(imports_array.len(), 1);
        assert_eq!(imports_array[0]["type"], "alias");
        assert_eq!(
            imports_array[0]["target"],
            "StringList = System.Collections.Generic.List<string>"
        );
    }

    #[test]
    fn test_no_imports_chunk_when_empty() {
        let source = r#"
class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should NOT have __imports__ chunk
        assert!(chunks.iter().all(|c| c.kind != "imports"));
    }

    #[test]
    fn test_namespace_and_using_combined() {
        let source = r#"
using System;
using System.Collections.Generic;

namespace MyCompany.MyProduct {
    public class MyClass {
        public void Method() {}
    }
}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should have __imports__, namespace, class, and method
        assert!(chunks.iter().any(|c| c.kind == "imports"));
        assert!(chunks.iter().any(|c| c.kind == "namespace"));
        assert!(chunks.iter().any(|c| c.kind == "class"));
        assert!(chunks.iter().any(|c| c.kind == "method"));

        // Verify imports
        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let metadata = imports.metadata.as_ref().unwrap();
        let imports_array = metadata.as_array().unwrap();
        assert_eq!(imports_array.len(), 2);
    }

    #[test]
    fn test_file_scoped_namespace_with_using() {
        let source = r#"
using System;

namespace MyCompany.MyProduct;

public class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);

        // Should have __imports__, namespace, and class
        let imports = chunks.iter().find(|c| c.kind == "imports").unwrap();
        let namespace = chunks.iter().find(|c| c.kind == "namespace").unwrap();
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();

        assert_eq!(imports.symbol_name.as_deref(), Some("__imports__"));
        assert_eq!(
            namespace.symbol_name.as_deref(),
            Some("MyCompany.MyProduct")
        );
        assert_eq!(class.symbol_name.as_deref(), Some("MyClass"));
    }

    // Utility function tests (task 2004)

    #[test]
    fn test_doc_comment_single_line() {
        let source = r#"
class MyClass {
    /// Does something important
    public void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        assert_eq!(
            method.docstring.as_deref(),
            Some("Does something important")
        );
    }

    #[test]
    fn test_doc_comment_multi_line() {
        let source = r#"
class MyClass {
    /// <summary>
    /// Does something important
    /// </summary>
    /// <param name="x">The parameter</param>
    /// <returns>The result</returns>
    public int DoSomething(int x) { return x; }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let docstring = method.docstring.as_ref().unwrap();
        assert!(docstring.contains("<summary>"));
        assert!(docstring.contains("Does something important"));
        assert!(docstring.contains("<param name=\"x\">"));
        assert!(docstring.contains("<returns>"));
    }

    #[test]
    fn test_doc_comment_with_blank_line() {
        let source = r#"
/// Doc comment

public class Foo { }
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert_eq!(class.docstring.as_deref(), Some("Doc comment"));
    }

    #[test]
    fn test_doc_comment_stops_at_regular_comment() {
        let source = r#"
// Regular comment
/// Doc comment
public class Foo { }
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        // Should only capture the doc comment, not the regular comment
        assert_eq!(class.docstring.as_deref(), Some("Doc comment"));
    }

    #[test]
    fn test_doc_comment_stops_at_code() {
        let source = r#"
int x = 5;
/// Doc comment
public class Foo { }
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        // Should only capture the doc comment, not preceding code
        assert_eq!(class.docstring.as_deref(), Some("Doc comment"));
    }

    #[test]
    fn test_doc_comment_none_when_missing() {
        let source = r#"
public class Foo { }
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert!(class.docstring.is_none());
    }

    #[test]
    fn test_doc_comment_at_start_of_file() {
        let source = r#"public class Foo { }
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        assert!(class.docstring.is_none());
    }

    #[test]
    fn test_visibility_public() {
        let source = r#"
public class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        let metadata = class.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "public");
    }

    #[test]
    fn test_visibility_private() {
        let source = r#"
class MyClass {
    private void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "private");
    }

    #[test]
    fn test_visibility_protected() {
        let source = r#"
class MyClass {
    protected void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "protected");
    }

    #[test]
    fn test_visibility_internal() {
        let source = r#"
internal class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        let metadata = class.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "internal");
    }

    #[test]
    fn test_visibility_protected_internal() {
        let source = r#"
class MyClass {
    protected internal void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "protected internal");
    }

    #[test]
    fn test_visibility_default_private() {
        let source = r#"
class MyClass {
    void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "private");
    }

    #[test]
    fn test_modifiers_abstract() {
        let source = r#"
public abstract class MyClass {
    public abstract void Method();
}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        let metadata = class.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_abstract"], true);

        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_abstract"], true);
    }

    #[test]
    fn test_modifiers_static() {
        let source = r#"
public static class MyClass {
    public static void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        let metadata = class.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_static"], true);

        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_static"], true);
    }

    #[test]
    fn test_modifiers_sealed() {
        let source = r#"
public sealed class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        // Note: sealed is not tracked in metadata for class currently
        // This test just verifies the modifier is extracted without error
        assert_eq!(class.symbol_name.as_deref(), Some("MyClass"));
    }

    #[test]
    fn test_modifiers_partial() {
        let source = r#"
public partial class MyClass {}
"#;
        let chunks = extract_csharp_chunks(source);
        let class = chunks.iter().find(|c| c.kind == "class").unwrap();
        let metadata = class.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_partial"], true);
    }

    #[test]
    fn test_modifiers_virtual() {
        let source = r#"
class MyClass {
    public virtual void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_virtual"], true);
    }

    #[test]
    fn test_modifiers_override() {
        let source = r#"
class MyClass {
    public override void Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_override"], true);
    }

    #[test]
    fn test_modifiers_async() {
        let source = r#"
class MyClass {
    public async Task Method() {}
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["is_async"], true);
    }

    #[test]
    fn test_modifiers_combined() {
        let source = r#"
class MyClass {
    public static async Task<int> Method() { return 42; }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let metadata = method.metadata.as_ref().unwrap();
        assert_eq!(metadata["visibility"], "public");
        assert_eq!(metadata["is_static"], true);
        assert_eq!(metadata["is_async"], true);
    }

    #[test]
    fn test_doc_comment_preserves_xml_tags() {
        let source = r#"
class MyClass {
    /// <summary>
    /// Processes the <paramref name="input"/> and returns the result.
    /// </summary>
    /// <param name="input">The input to process</param>
    /// <returns>A <see cref="Result"/> object</returns>
    public Result Process(string input) { return null; }
}
"#;
        let chunks = extract_csharp_chunks(source);
        let method = chunks.iter().find(|c| c.kind == "method").unwrap();
        let docstring = method.docstring.as_ref().unwrap();

        // Verify all XML tags are preserved
        assert!(docstring.contains("<summary>"));
        assert!(docstring.contains("</summary>"));
        assert!(docstring.contains("<paramref name=\"input\"/>"));
        assert!(docstring.contains("<param name=\"input\">"));
        assert!(docstring.contains("<returns>"));
        assert!(docstring.contains("<see cref=\"Result\"/>"));
    }

    #[test]
    fn test_parse_error_detection() {
        // Initialize tracing for this test (ignore if already initialized)
        let _ = tracing_subscriber::fmt()
            .with_test_writer()
            .with_env_filter(
                tracing_subscriber::EnvFilter::from_default_env()
                    .add_directive("maproom::indexer::parser::csharp=debug".parse().unwrap()),
            )
            .try_init();

        let source = r#"
public class Broken {
    public void Method(
    // Missing closing paren and brace
"#;

        // This should trigger the debug log
        let _chunks = extract_csharp_chunks(source);
        // The key is that the log appears when RUST_LOG=debug is set
        // This test verifies the code doesn't panic on syntax errors
    }
}