cora-code 0.17.1

CLI-first AI code review — BYOK, diff/scan/branch, pre-commit hooks
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
//! Symbol extraction from source files.
//!
//! Uses regex-based extraction — same approach as `engine/context/extraction.rs`
//! but extracts definitions (not just references). No heavy AST parser needed.

use regex::Regex;
use std::sync::LazyLock;

use super::symbols::{IndexedSymbol, SymbolKind};

// ─── Rust ───

static RE_RUST_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)").unwrap());

static RE_RUST_STRUCT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?struct\s+(\w+)").unwrap());

static RE_RUST_ENUM: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?enum\s+(\w+)").unwrap());

static RE_RUST_TRAIT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?trait\s+(\w+)").unwrap());

static RE_RUST_TYPE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?type\s+(\w+)").unwrap());

static RE_RUST_CONST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?(?:const|static)\s+(\w+)").unwrap());

static RE_RUST_MOD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?mod\s+(\w+)").unwrap());

// RE_RUST_IMPL removed — not needed for symbol definitions

// ─── Python ───

static RE_PY_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:async\s+)?def\s+(\w+)").unwrap());

static RE_PY_CLASS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*class\s+(\w+)").unwrap());

// ─── TypeScript/JavaScript ───

static RE_TS_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)").unwrap());

static RE_TS_CLASS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:export\s+)?(?:abstract\s+)?class\s+(\w+)").unwrap());

static RE_TS_INTERFACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:export\s+)?interface\s+(\w+)").unwrap());

static RE_TS_TYPE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:export\s+)?type\s+(\w+)").unwrap());

static RE_TS_CONST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:export\s+)?const\s+(\w+)").unwrap());

// ─── Go ───

static RE_GO_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*func\s+(?:\([^)]+\)\s+)?(\w+)").unwrap());

static RE_GO_STRUCT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*type\s+(\w+)\s+struct").unwrap());

static RE_GO_INTERFACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*type\s+(\w+)\s+interface").unwrap());

static RE_GO_CONST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*const\s+(\w+)").unwrap());

// ─── Java/Kotlin ───

static RE_JAVA_CLASS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:public|private|protected)?\s*(?:abstract\s+)?class\s+(\w+)").unwrap()
});

static RE_JAVA_METHOD: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:public|private|protected)?\s*(?:static\s+)?[\w<>\[\]]+\s+(\w+)\s*\(")
        .unwrap()
});

// ─── C/C++ ───

static RE_C_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:static\s+)?[\w\*]+\s+(\w+)\s*\([^;]*\)\s*\{").unwrap());

static RE_C_STRUCT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:typedef\s+)?struct\s+(\w+)").unwrap());

// ─── Ruby ───

static RE_RB_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*def\s+(?:self\.)?(\w+)").unwrap());

static RE_RB_CLASS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:class|module)\s+(\w+)").unwrap());

// ─── PHP ───

static RE_PHP_FN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:public|private|protected)?\s*(?:static\s+)?function\s+(\w+)").unwrap()
});

static RE_PHP_CLASS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:abstract\s+)?(?:final\s+)?class\s+(\w+)").unwrap());

static RE_PHP_INTERFACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*interface\s+(\w+)").unwrap());

// ─── Swift ───

static RE_SW_FN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:public|private|internal|fileprivate)?\s*(?:static\s+)?func\s+(\w+)")
        .unwrap()
});

static RE_SW_TYPE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:public|internal|final|open)?\s*(?:class|struct|enum|protocol)\s+(\w+)")
        .unwrap()
});

// ─── Scala ───

static RE_SCALA_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:private|protected)?\s*def\s+(\w+)").unwrap());

static RE_SCALA_TYPE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:abstract\s+)?(?:sealed\s+)?(?:class|object|trait|case class)\s+(\w+)")
        .unwrap()
});

// ─── Lua ───

static RE_LUA_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:local\s+)?function\s+(?:[\w.:]+\.)?(\w+)").unwrap());

// ─── Zig ───

static RE_ZIG_FN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?fn\s+(\w+)").unwrap());

static RE_ZIG_CONST: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:pub\s+)?const\s+(\w+)").unwrap());

// ─── Dart ───

static RE_DART_CLASS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*(?:abstract\s+)?(?:class|mixin)\s+(\w+)").unwrap());

static RE_DART_ENUM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*enum\s+(\w+)").unwrap());

static RE_DART_EXTENDS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*extension\s+(?:type\s+)?(\w+)\s+on\s+\w+").unwrap());
static RE_DART_EXTENDS_UNNAMED: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*extension\s+(?:type\s+)?on\s+(\w+)").unwrap());

static RE_DART_FN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:static\s+)?(?:external\s+)?(?:@[\w()<>]+\s+)*(?:covariant\s+)?(?:late\s+)?(?:final\s+)?(?:const\s+)?(?:[A-Z]\w*\s+)?(?:Future<[^>]+>\s+)?(?:void|[A-Z]\w*<[^>]+>|[a-zA-Z]\w*(?:<[^>]+>)?)\s+(\w+)\s*\(").unwrap()
});

static RE_DART_TYPEDEF: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*typedef\s+(\w+)").unwrap());

static RE_DART_GETTER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:[A-Z]\w*\s+)?(?:[a-zA-Z]\w*(?:<[^>]+>)?)\s+get\s+(\w+)").unwrap()
});
// ─── Svelte ───

static RE_SVELTE_SCRIPT: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?s)<script(?:\s[^>]*)?>
?(.*?)
?</script>",
    )
    .unwrap()
});
static RE_SVELTE_EXPORT_PROP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*export\s+let\s+(\w+)").unwrap());
static RE_SVELTE_STATE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*let\s+(\w+)\s*=\s*\$state(?:<[^>]*>)?\s*\(").unwrap());
static RE_SVELTE_DERIVED: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*let\s+(\w+)\s*=\s*\$derived(?:<[^>]*>)?\s*\(").unwrap());
static RE_SVELTE_EFFECT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s*\$effect\s*\(\s*(?:async\s+)?\(\s*\)\s*=>").unwrap());

/// Extract symbols from source code.
///
/// When the `tree-sitter` feature is enabled, uses AST-based extraction for
/// supported languages (Rust, Go, Python, TypeScript/TSX). Falls back to
/// regex for all other languages.
pub fn extract_symbols(content: &str, language: &str, file_path: &str) -> Vec<ExtractedDef> {
    #[cfg(feature = "tree-sitter")]
    {
        use super::ast;
        if ast::get_language(language).is_some() || language == "svelte" {
            let (nodes, _edges) = ast::extract(content, language, file_path);
            return nodes.into_iter().map(Into::into).collect();
        }
    }

    // Regex fallback for unsupported languages or when feature is disabled
    let mut symbols = Vec::new();

    for (line_num, line) in content.lines().enumerate() {
        let line_no = (line_num + 1) as u32;

        match language {
            "rs" => extract_rust(line, line_no, file_path, line, &mut symbols),
            "py" | "pyi" => extract_python(line, line_no, file_path, line, &mut symbols),
            "ts" | "tsx" | "js" | "jsx" => {
                extract_typescript(line, line_no, file_path, line, &mut symbols)
            }
            "go" => extract_go(line, line_no, file_path, line, &mut symbols),
            "java" | "kt" => extract_java(line, line_no, file_path, line, &mut symbols),
            "c" | "cpp" | "cc" | "cxx" | "h" | "hpp" => {
                extract_c(line, line_no, file_path, line, &mut symbols)
            }
            "rb" => extract_ruby(line, line_no, file_path, line, &mut symbols),
            "php" => extract_php(line, line_no, file_path, line, &mut symbols),
            "swift" => extract_swift(line, line_no, file_path, line, &mut symbols),
            "scala" => extract_scala(line, line_no, file_path, line, &mut symbols),
            "lua" => extract_lua(line, line_no, file_path, line, &mut symbols),
            "zig" => extract_zig(line, line_no, file_path, line, &mut symbols),
            "dart" => extract_dart(line, line_no, file_path, line, &mut symbols),
            "svelte" => extract_svelte(content, file_path, &mut symbols),
            _ => {}
        }
    }

    // Deduplicate by (name, line) — regex may match multiple times
    symbols.dedup_by(|a, b| a.name == b.name && a.line == b.line);

    symbols
}

/// A symbol definition extracted from source code.
#[derive(Debug, Clone)]
pub struct ExtractedDef {
    pub name: String,
    pub kind: SymbolKind,
    pub file: String,
    pub line: u32,
    pub signature: String,
}

impl From<&ExtractedDef> for IndexedSymbol {
    fn from(d: &ExtractedDef) -> Self {
        Self {
            id: 0,
            name: d.name.clone(),
            kind: d.kind.clone(),
            file: d.file.clone(),
            line: d.line,
            signature: d.signature.clone(),
            language: String::new(),
        }
    }
}

// ─── Per-language extractors ───

fn extract_rust(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_RUST_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_STRUCT.captures(line) {
        out.push(def(cap, SymbolKind::Struct, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_ENUM.captures(line) {
        out.push(def(cap, SymbolKind::Enum, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_TRAIT.captures(line) {
        out.push(def(cap, SymbolKind::Trait, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_TYPE.captures(line) {
        out.push(def(cap, SymbolKind::TypeAlias, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_CONST.captures(line) {
        out.push(def(cap, SymbolKind::Constant, line_no, file, raw));
    }
    if let Some(cap) = RE_RUST_MOD.captures(line) {
        out.push(def(cap, SymbolKind::Module, line_no, file, raw));
    }
}

fn extract_python(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_PY_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_PY_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
}

fn extract_typescript(
    line: &str,
    line_no: u32,
    file: &str,
    raw: &str,
    out: &mut Vec<ExtractedDef>,
) {
    if let Some(cap) = RE_TS_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_TS_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
    if let Some(cap) = RE_TS_INTERFACE.captures(line) {
        out.push(def(cap, SymbolKind::Interface, line_no, file, raw));
    }
    if let Some(cap) = RE_TS_TYPE.captures(line) {
        out.push(def(cap, SymbolKind::TypeAlias, line_no, file, raw));
    }
    if let Some(cap) = RE_TS_CONST.captures(line) {
        out.push(def(cap, SymbolKind::Constant, line_no, file, raw));
    }
}

fn extract_go(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_GO_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_GO_STRUCT.captures(line) {
        out.push(def(cap, SymbolKind::Struct, line_no, file, raw));
    }
    if let Some(cap) = RE_GO_INTERFACE.captures(line) {
        out.push(def(cap, SymbolKind::Interface, line_no, file, raw));
    }
    if let Some(cap) = RE_GO_CONST.captures(line) {
        out.push(def(cap, SymbolKind::Constant, line_no, file, raw));
    }
}

fn extract_java(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_JAVA_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
    if let Some(cap) = RE_JAVA_METHOD.captures(line) {
        out.push(def(cap, SymbolKind::Method, line_no, file, raw));
    }
}

fn extract_c(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_C_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_C_STRUCT.captures(line) {
        out.push(def(cap, SymbolKind::Struct, line_no, file, raw));
    }
}

fn extract_ruby(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_RB_FN.captures(line) {
        out.push(def(cap, SymbolKind::Method, line_no, file, raw));
    }
    if let Some(cap) = RE_RB_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
}

fn extract_php(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_PHP_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_PHP_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
    if let Some(cap) = RE_PHP_INTERFACE.captures(line) {
        out.push(def(cap, SymbolKind::Interface, line_no, file, raw));
    }
}

fn extract_swift(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_SW_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_SW_TYPE.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
}

fn extract_scala(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_SCALA_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_SCALA_TYPE.captures(line) {
        out.push(def(cap, SymbolKind::Class, line_no, file, raw));
    }
}

fn extract_lua(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_LUA_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
}

fn extract_zig(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_ZIG_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_ZIG_CONST.captures(line) {
        out.push(def(cap, SymbolKind::Constant, line_no, file, raw));
    }
}

fn extract_dart(line: &str, line_no: u32, file: &str, raw: &str, out: &mut Vec<ExtractedDef>) {
    if let Some(cap) = RE_DART_CLASS.captures(line) {
        out.push(def(cap, SymbolKind::Struct, line_no, file, raw));
    }
    if let Some(cap) = RE_DART_ENUM.captures(line) {
        out.push(def(cap, SymbolKind::Enum, line_no, file, raw));
    }
    if let Some(cap) = RE_DART_EXTENDS.captures(line) {
        out.push(def(cap, SymbolKind::Trait, line_no, file, raw));
    } else if let Some(cap) = RE_DART_EXTENDS_UNNAMED.captures(line) {
        out.push(def(cap, SymbolKind::Trait, line_no, file, raw));
    }
    if let Some(cap) = RE_DART_FN.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
    if let Some(cap) = RE_DART_TYPEDEF.captures(line) {
        out.push(def(cap, SymbolKind::TypeAlias, line_no, file, raw));
    }
    if let Some(cap) = RE_DART_GETTER.captures(line) {
        out.push(def(cap, SymbolKind::Function, line_no, file, raw));
    }
}

/// Extract Svelte symbols:
/// 1. Derive component name from filename (PascalCase or kebab → PascalCase)
/// 2. Strip `<script>` blocks and delegate to TS/JS extractor
/// 3. Extract Svelte-specific: export props, $state, $derived
fn extract_svelte(content: &str, file: &str, out: &mut Vec<ExtractedDef>) {
    // 1. Component name from filename
    let component_name = std::path::Path::new(file)
        .file_stem()
        .and_then(|s| s.to_str())
        .map(|s| {
            let mut result = String::new();
            let mut capitalize_next = true;
            for ch in s.chars() {
                if ch == '-' || ch == '_' {
                    capitalize_next = true;
                } else if capitalize_next {
                    result.push(ch.to_ascii_uppercase());
                    capitalize_next = false;
                } else {
                    result.push(ch);
                }
            }
            result
        })
        .unwrap_or_default();

    if !component_name.is_empty() {
        out.push(ExtractedDef {
            name: component_name.clone(),
            kind: SymbolKind::Struct,
            file: file.to_string(),
            line: 1,
            signature: format!("<!-- {} component -->", component_name),
        });
    }

    // 2. Extract <script> content and delegate to TS/JS extractor
    if let Some(cap) = RE_SVELTE_SCRIPT.captures(content) {
        let script_content = cap.get(1).map(|m| m.as_str()).unwrap_or("");

        for (line_num, line) in script_content.lines().enumerate() {
            let line_no = (line_num + 1) as u32;
            extract_typescript(line, line_no, file, line, out);

            if let Some(cap) = RE_SVELTE_EXPORT_PROP.captures(line) {
                out.push(def(cap, SymbolKind::Variable, line_no, file, line));
            }
            if let Some(cap) = RE_SVELTE_STATE.captures(line) {
                out.push(def(cap, SymbolKind::Variable, line_no, file, line));
            }
            if let Some(cap) = RE_SVELTE_DERIVED.captures(line) {
                out.push(def(cap, SymbolKind::Variable, line_no, file, line));
            }
            if RE_SVELTE_EFFECT.is_match(line) {
                out.push(ExtractedDef {
                    name: "$effect".to_string(),
                    kind: SymbolKind::Function,
                    file: file.to_string(),
                    line: line_no,
                    signature: line.trim().to_string(),
                });
            }
        }

        // Dedup: TS extractor may produce duplicates for Svelte-specific symbols
        let mut seen = std::collections::HashSet::new();
        out.retain(|s| {
            let key = (s.name.clone(), s.line);
            seen.insert(key)
        });
    }
}

/// Extract function call sites from source code.
///
/// When the `tree-sitter` feature is enabled, uses AST-based extraction for
/// supported languages. Falls back to regex-based scope tracking for others.
#[allow(dead_code)]
pub fn extract_calls(content: &str, language: &str, file_path: &str) -> Vec<CallSite> {
    #[cfg(feature = "tree-sitter")]
    {
        use super::ast;
        if ast::get_language(language).is_some() || language == "svelte" {
            let (_nodes, edges) = ast::extract(content, language, file_path);
            return edges
                .into_iter()
                .filter(|e| e.kind == ast::EdgeKind::Calls)
                .map(Into::into)
                .collect();
        }
    }

    // Regex fallback
    use crate::engine::context::extraction as ctx_extract;
    use crate::engine::context::types::SymbolKind as CtxSymbolKind;

    let lines: Vec<&str> = content.lines().collect();
    let mut current_fn: Option<String> = None;
    let mut brace_depth: i32 = 0;
    let mut calls = Vec::new();

    for (i, line) in lines.iter().enumerate() {
        let line_no = (i + 1) as u32;

        // Track current function scope for Rust/Go/C/Java
        if language == "rs"
            || language == "go"
            || language == "c"
            || language == "cpp"
            || language == "java"
            || language == "kt"
            || language == "dart"
        {
            // Check if we're entering a function
            if let Some(fn_name) = detect_function_entry(line, language) {
                current_fn = Some(fn_name);
                brace_depth = 0;
            }
        }

        // Track brace depth for scope
        brace_depth += line.chars().filter(|&c| c == '{').count() as i32
            - line.chars().filter(|&c| c == '}').count() as i32;
        if brace_depth <= 0 && current_fn.is_some() {
            current_fn = None;
        }

        // Extract function calls from this line
        let symbols = ctx_extract::extract_symbols_from_line(line, language);
        for sym in symbols {
            if let CtxSymbolKind::FunctionCall(name) = sym {
                // Skip self-references and builtins
                if name == current_fn.as_deref().unwrap_or("") {
                    continue;
                }
                if is_builtin(&name) {
                    continue;
                }
                if let Some(caller) = &current_fn {
                    calls.push(CallSite {
                        caller: caller.clone(),
                        callee: name,
                        file: file_path.to_string(),
                        line: line_no,
                    });
                }
            }
        }
    }

    calls
}

/// Extract all graph edges from source code (calls, imports, implements, inherits).
///
/// Only available with the `tree-sitter` feature. Returns empty for unsupported languages.
#[cfg(feature = "tree-sitter")]
#[allow(dead_code)]
pub fn extract_edges(
    content: &str,
    language: &str,
    file_path: &str,
) -> Vec<crate::index::ast::AstEdge> {
    use super::ast;
    if ast::get_language(language).is_some() || language == "svelte" {
        let (_nodes, edges) = ast::extract(content, language, file_path);
        return edges;
    }
    Vec::new()
}

/// Detect HTTP route definitions from source code using regex heuristics.
///
/// Catches common route registration patterns across frameworks:
/// - **Rust (axum):** `.route("/path", get(handler))`
/// - **Rust (actix-web):** `.route("/path", web::get().to(handler))`
/// - **Rust (warp):** `path("/api")` + `.and(then(handler))`
/// - **Go:** `http.HandleFunc("/path", handler)` or `r.GET("/path", handler)`
/// - **TypeScript/JS (express):** `app.get("/path", handler)`
/// - **TypeScript/JS (fastify):** `fastify.get("/path", handler)`
/// - **Python (flask):** `@app.route("/path")`
/// - **Python (fastapi):** `@app.get("/path")`
///
/// Returns `AstEdge` with `EdgeKind::Route` where `source` = handler name,
/// `target` = HTTP method + path (e.g., `GET /api/users`).
pub fn detect_routes(
    content: &str,
    language: &str,
    file_path: &str,
) -> Vec<crate::index::ast::AstEdge> {
    use crate::index::ast::{AstEdge, EdgeKind};
    use regex::Regex;

    let mut edges = Vec::new();

    let patterns: &[(&str, &str)] = match language {
        "rs" => &[
            // axum: .route("/path", get(handler_fn))
            (
                r#"(?:\w+\.)?route\(\s*"([^"]+)"\s*,\s*(?:\w+::)?(\w+)\(([\w:]+)"#,
                "route_method_handler",
            ),
            // actix-web: .route("/path", web::get().to(handler))
            (
                r#"\.route\(\s*"([^"]+)"\s*,\s*\w+::(\w+)\(\)\.to\(([\w:]+)"#,
                "route_method_to_handler",
            ),
        ],
        "go" => &[
            // net/http: http.HandleFunc("/path", handler)
            (r#"HandleFunc\(\s*"([^"]+)"\s*,\s*(\w+)"#, "handle_func"),
            // chi: r.Get("/path", handler)
            (r#"\w+\.\w+\(\s*"([^"]+)"\s*,\s*(\w+)"#, "router_method"),
        ],
        "ts" | "tsx" | "javascript" | "jsx" => &[
            // express/fastify: app.get("/path", handler)
            (
                r#"(?:app|router|fastify)\.\w+\(\s*['"]([^'"]+)['"]\s*,\s*(\w+)"#,
                "express_route",
            ),
        ],
        "python" => &[
            // flask: @app.route("/path")
            (r#"@\w+\.route\(\s*['"]([^'"]+)['"]"#, "flask_decorator"),
            // fastapi: @app.get("/path")
            (r#"@\w+\.\w+\(\s*['"]([^'"]+)['"]"#, "fastapi_decorator"),
        ],
        _ => &[],
    };

    for (pattern, label) in patterns {
        let re = Regex::new(pattern).unwrap();
        for cap in re.captures_iter(content) {
            let full_match = cap.get(0).unwrap();
            let line_no = content[..full_match.start()]
                .matches('\n')
                .count()
                .saturating_add(1);

            // Resolve (path, method, handler) per pattern label. Each framework's
            // regex captures groups in a different order, so dispatch on the label.
            // axum/actix capture the method fn in group 2 (e.g. `get`, `post`);
            // go/express capture only path + handler.
            let (path, method, handler): (String, String, Option<String>) = match *label {
                "route_method_handler" | "route_method_to_handler" => (
                    cap[1].to_string(),
                    cap[2].to_ascii_uppercase(),
                    // Handler may be a fully-qualified path like
                    // `routes::health::health_check` — keep only the final segment
                    // so it matches the indexed function symbol.
                    Some(cap[3].rsplit("::").next().unwrap_or(&cap[3]).to_string()),
                ),
                "handle_func" | "router_method" | "express_route" => {
                    (cap[1].to_string(), String::new(), Some(cap[2].to_string()))
                }
                "flask_decorator" | "fastapi_decorator" => {
                    (cap[1].to_string(), String::new(), None)
                }
                _ => (
                    cap.get(1)
                        .map(|m| m.as_str().to_string())
                        .unwrap_or_default(),
                    String::new(),
                    cap.get(2).map(|m| m.as_str().to_string()),
                ),
            };

            // Build the route target string: "METHOD /path" (or just "/path")
            let target = if method.is_empty() {
                path
            } else {
                format!("{} {}", method, path)
            };
            let source = handler.unwrap_or_else(|| format!("route_line_{}", line_no));

            edges.push(AstEdge {
                source,
                kind: EdgeKind::Route,
                target,
                file: file_path.to_string(),
                line: line_no as u32,
            });
        }
    }

    edges
}

/// Detect function entry from a line (returns function name).
fn detect_function_entry(line: &str, language: &str) -> Option<String> {
    let trimmed = line.trim();

    match language {
        "rs" => {
            static RE: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*[(<]").unwrap());
            RE.captures(trimmed)
                .map(|c| c.get(1).unwrap().as_str().to_string())
        }
        "go" => {
            static RE: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"func\s+(?:\([^)]+\)\s+)?(\w+)\s*\(").unwrap());
            RE.captures(trimmed)
                .map(|c| c.get(1).unwrap().as_str().to_string())
        }
        "c" | "cpp" | "h" | "hpp" => {
            static RE: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"[\w:*]+\s+(\w+)\s*\([^;]*\)\s*\{").unwrap());
            RE.captures(trimmed)
                .map(|c| c.get(1).unwrap().as_str().to_string())
        }
        "java" | "kt" | "dart" => {
            static RE: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"\b(\w+)\s*\([^)]*\)\s*\{").unwrap());
            RE.captures(trimmed)
                .map(|c| c.get(1).unwrap().as_str().to_string())
        }
        "py" => {
            static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"def\s+(\w+)").unwrap());
            RE.captures(trimmed)
                .map(|c| c.get(1).unwrap().as_str().to_string())
        }
        _ => None,
    }
}

/// Check if a name is a builtin/keyword to skip.
fn is_builtin(name: &str) -> bool {
    matches!(
        name,
        "if" | "for"
            | "while"
            | "match"
            | "return"
            | "break"
            | "continue"
            | "print"
            | "println"
            | "eprintln"
            | "format"
            | "write"
            | "writeln"
            | "vec"
            | "Box"
            | "Some"
            | "None"
            | "Ok"
            | "Err"
            | "Result"
            | "Option"
            | "String"
            | "str"
            | "Vec"
            | "HashMap"
            | "HashSet"
            | "dbg"
            | "todo"
            | "unimplemented"
            | "unreachable"
            | "panic"
            | "assert"
            | "assert_eq"
            | "assert_ne"
            | "len"
            | "is_empty"
            | "push"
            | "pop"
            | "insert"
            | "remove"
            | "get"
            | "set"
            | "new"
            | "default"
            | "clone"
            | "into"
            | "from"
            | "iter"
            | "collect"
            | "map"
            | "filter"
            | "fold"
            | "next"
            | "unwrap"
            | "expect"
            | "as_ref"
            | "as_mut"
            | "as_str"
            | "to_string"
            | "to_owned"
            | "to_vec"
            | "drop"
            | "copy"
            | "send"
            | "sync"
            | "main"
            // Dart builtins
            | "debugPrint"
            | "throw"
            | "rethrow"
            | "late"
            | "required"
            | "covariant"
            | "show"
            | "hide"
            | "Future"
            | "Stream"
            | "Completer"
            | "List"
            | "Map"
            | "Set"
            | "int"
            | "double"
            | "num"
            | "bool"
            | "dynamic"
            | "Object"
            | "Null"
            | "Never"
    )
}

/// All extracted data from a single file (symbols + calls + kg edges).
/// Used by bulk indexing to parse tree-sitter only once.
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct ExtractedAll {
    pub symbols: Vec<ExtractedDef>,
    pub calls: Vec<CallSite>,
    pub kg_edges: Vec<KgEdge>,
}

/// A knowledge-graph edge (calls, imports, implements, inherits, etc.).
#[cfg(feature = "tree-sitter")]
pub type KgEdge = crate::index::ast::AstEdge;

/// A knowledge-graph edge stub when tree-sitter is disabled (never used).
#[cfg(not(feature = "tree-sitter"))]
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct KgEdge {
    pub source: String,
    pub kind: String,
    pub target: String,
    pub file: String,
    pub line: u32,
}

/// Extract everything from a file in a single pass.
/// When tree-sitter is available, this parses the source only once and returns
/// all three outputs (symbols, call graph edges, knowledge graph edges).
/// For unsupported languages, falls back to regex-based extraction.
pub fn extract_all(content: &str, language: &str, file_path: &str) -> ExtractedAll {
    #[cfg(feature = "tree-sitter")]
    {
        use super::ast;
        if ast::get_language(language).is_some() || language == "svelte" {
            let (nodes, edges) = ast::extract(content, language, file_path);
            let calls: Vec<CallSite> = edges
                .iter()
                .filter(|e| e.kind == ast::EdgeKind::Calls)
                .cloned()
                .map(Into::into)
                .collect();
            let kg_edges: Vec<_> = edges
                .into_iter()
                .filter(|e| e.kind != ast::EdgeKind::Calls)
                .collect();
            let symbols = nodes.into_iter().map(Into::into).collect();
            return ExtractedAll {
                symbols,
                calls,
                kg_edges,
            };
        }
    }

    // Regex fallback
    let symbols = extract_symbols(content, language, file_path);
    let calls = {
        // For regex path, we need calls without re-parsing via tree-sitter
        // Call the regex fallback directly
        #[cfg(feature = "tree-sitter")]
        {
            // When tree-sitter is compiled but language is unsupported,
            // extract_calls will also fall through to regex path.
            // We already have symbols, just get calls.
            use crate::engine::context::extraction as ctx_extract;
            use crate::engine::context::types::SymbolKind as CtxSymbolKind;

            let lines: Vec<&str> = content.lines().collect();
            let mut current_fn: Option<String> = None;
            let mut brace_depth: i32 = 0;
            let mut calls = Vec::new();

            for (i, line) in lines.iter().enumerate() {
                let line_no = (i + 1) as u32;
                if language == "rs"
                    || language == "go"
                    || language == "c"
                    || language == "cpp"
                    || language == "java"
                    || language == "kt"
                    || language == "dart"
                {
                    if let Some(fn_name) = detect_function_entry(line, language) {
                        current_fn = Some(fn_name);
                        brace_depth = 0;
                    }
                }
                brace_depth += line.chars().filter(|&c| c == '{').count() as i32
                    - line.chars().filter(|&c| c == '}').count() as i32;
                if brace_depth <= 0 && current_fn.is_some() {
                    current_fn = None;
                }
                let syms = ctx_extract::extract_symbols_from_line(line, language);
                for sym in syms {
                    if let CtxSymbolKind::FunctionCall(name) = sym {
                        if name == current_fn.as_deref().unwrap_or("") {
                            continue;
                        }
                        if is_builtin(&name) {
                            continue;
                        }
                        if let Some(caller) = &current_fn {
                            calls.push(CallSite {
                                caller: caller.clone(),
                                callee: name,
                                file: file_path.to_string(),
                                line: line_no,
                            });
                        }
                    }
                }
            }
            calls
        }
        #[cfg(not(feature = "tree-sitter"))]
        {
            // Without tree-sitter, extract_calls uses regex fallback anyway
            extract_calls(content, language, file_path)
        }
    };

    ExtractedAll {
        symbols,
        calls,
        kg_edges: Vec::new(),
    }
}

/// A function call site extracted from source code.
#[derive(Debug, Clone)]
pub struct CallSite {
    pub caller: String,
    pub callee: String,
    pub file: String,
    pub line: u32,
}

fn def(cap: regex::Captures, kind: SymbolKind, line: u32, file: &str, raw: &str) -> ExtractedDef {
    ExtractedDef {
        name: cap
            .get(1)
            .map(|m| m.as_str().to_string())
            .unwrap_or_default(),
        kind,
        line,
        file: file.to_string(),
        signature: raw.trim().to_string(),
    }
}

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

    #[test]
    fn test_extract_rust() {
        let code = r#"
pub struct Cache {
    inner: HashMap<String, String>,
}

impl Cache {
    pub fn new() -> Self {
        Self {}
    }

    pub fn get(&self, key: &str) -> Option<&String> {
        self.inner.get(key)
    }
}

enum Status {
    Active,
    Inactive,
}

const MAX_SIZE: usize = 100;
"#;
        let symbols = extract_symbols(code, "rs", "src/cache.rs");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        eprintln!(
            "GO symbols: {:?}",
            symbols
                .iter()
                .map(|s| (&s.kind, &s.name))
                .collect::<Vec<_>>()
        );

        assert!(names.contains(&"Cache"));
        assert!(names.contains(&"new"));
        assert!(names.contains(&"get"));
        assert!(names.contains(&"Status"));
        assert!(names.contains(&"MAX_SIZE"));
    }

    #[test]
    fn test_extract_python() {
        let code = r#"
class AuthService:
    def __init__(self):
        self.secret = ""

    async def validate(self, token: str) -> bool:
        return False
"#;
        let symbols = extract_symbols(code, "py", "auth.py");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"AuthService"));
        assert!(names.contains(&"validate"));
    }

    #[test]
    fn test_extract_typescript() {
        let code = r#"
export interface User {
    id: string;
    name: string;
}

export class UserService {
    async getUser(id: string): Promise<User> {
        return {} as User;
    }
}

export type Status = 'active' | 'inactive';

export const DEFAULT_TIMEOUT = 5000;
"#;
        let symbols = extract_symbols(code, "ts", "user.ts");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"User"));
        assert!(names.contains(&"UserService"));
        assert!(names.contains(&"Status"));
        assert!(names.contains(&"DEFAULT_TIMEOUT"));
    }

    #[test]
    fn test_extract_go() {
        let code = r#"
type Server struct {
    port int
}

func (s *Server) Start() error {
    return nil
}

func NewServer(port int) *Server {
    return &Server{port: port}
}

const DefaultPort = 8080
"#;
        let symbols = extract_symbols(code, "go", "server.go");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(names.contains(&"Server"));
        assert!(names.contains(&"Start"));
        assert!(names.contains(&"NewServer"));
        assert!(names.contains(&"DefaultPort"));
    }

    #[test]
    fn test_extract_unknown_language() {
        let symbols = extract_symbols("fn test() {}", "unknown", "test.txt");
        assert!(symbols.is_empty());
    }

    #[test]
    fn test_extract_empty() {
        let symbols = extract_symbols("", "rs", "empty.rs");
        assert!(symbols.is_empty());
    }

    #[test]
    fn test_extract_ruby() {
        let code = r#"
class ApplicationController
  def authenticate_user
    @current_user
  end
end

module Auth
  def validate_token(token)
    false
  end
end
"#;
        let symbols = extract_symbols(code, "rb", "app.rb");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(
            names.contains(&"ApplicationController"),
            "missing ApplicationController, got: {names:?}"
        );
        assert!(
            names.contains(&"authenticate_user"),
            "missing authenticate_user, got: {names:?}"
        );
        assert!(names.contains(&"Auth"), "missing Auth, got: {names:?}");
    }

    #[test]
    fn test_extract_php() {
        let code = r#"
<?php
class UserController {
    public function show($id) {
        return $this->find($id);
    }
}

interface Repository {
    public function find($id);
}
"#;
        let symbols = extract_symbols(code, "php", "user.php");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"UserController"));
        assert!(names.contains(&"show"));
        assert!(names.contains(&"Repository"));
    }

    #[test]
    fn test_extract_swift() {
        let code = r#"
public struct User {
    var id: String
}

func authenticate(token: String) -> Bool {
    return false
}

enum AuthError: Error {
    case invalidToken
}
"#;
        let symbols = extract_symbols(code, "swift", "auth.swift");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"User"));
        assert!(names.contains(&"authenticate"));
    }

    #[test]
    fn test_extract_lua() {
        let code = r#"
local function validate(input)
    return true
end

function M.handler(req)
    return validate(req.body)
end
"#;
        let symbols = extract_symbols(code, "lua", "handler.lua");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"validate"));
        assert!(names.contains(&"handler"));
    }

    #[test]
    fn test_extract_zig() {
        let code = r#"
pub fn main() !void {
    try run();
}

const MAX_RETRIES: u32 = 3;
"#;
        let symbols = extract_symbols(code, "zig", "main.zig");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"main"));
        assert!(names.contains(&"MAX_RETRIES"));
    }

    #[test]
    fn test_extract_dart() {
        let code = r#"
class UserService {
  String? name;
  void login(String email) {
    print(email);
  }

  static Future<void> fetchData() async {
    return Future.value();
  }

  String get displayName => name ?? '';

  set displayName(String value) {}
}

enum Status { active, inactive }

extension UserServiceHelpers on UserService {
  String greet() => "Hello";
}

typedef UserCallback = void Function(User);

mixin Validator {
  bool validate(String input) => true;
}

abstract class Shape {
  double area();
}
"#;
        let symbols = extract_symbols(code, "dart", "lib/models/user.dart");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        let kinds: Vec<(String, &str)> = symbols
            .iter()
            .map(|s| (s.name.clone(), s.kind.as_str()))
            .collect();
        eprintln!("Dart symbols: {:?}", kinds);

        assert!(names.contains(&"UserService"), "UserService class");
        assert!(names.contains(&"Shape"), "Shape abstract class");
        assert!(names.contains(&"Validator"), "Validator mixin");
        assert!(names.contains(&"login"), "login method");
        assert!(names.contains(&"fetchData"), "fetchData async method");
        assert!(names.contains(&"displayName"), "displayName getter");
        assert!(names.contains(&"greet"), "extension method greet");
        assert!(names.contains(&"validate"), "mixin method validate");
        assert!(names.contains(&"area"), "abstract method area");
        assert!(names.contains(&"Status"), "Status enum");
        assert!(
            names.contains(&"UserServiceHelpers"),
            "extension on UserService"
        );
        assert!(names.contains(&"UserCallback"), "typedef UserCallback");
    }

    #[test]
    fn test_extract_dart_issue_373_repro() {
        let code = r#"class UserService {
  String? name;
  void login(String email) {
    print(email);
  }
}

Future<void> fetchData() async {
  return Future.value();
}

enum Status { active, inactive }"#;
        let symbols = extract_symbols(code, "dart", "sample.dart");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();

        assert!(!symbols.is_empty(), "Should extract at least 1 Dart symbol");
        assert!(names.contains(&"UserService"), "UserService class");
        assert!(names.contains(&"login"), "login method");
        assert!(names.contains(&"fetchData"), "fetchData function");
        assert!(names.contains(&"Status"), "Status enum");
    }

    #[test]
    fn test_detect_routes_axum_fully_qualified_handler() {
        // Real-world axum: handlers are often fully-qualified module paths like
        // `routes::health::health_check`. The handler symbol we store must be the
        // final segment (`health_check`) so it matches the indexed function.
        let content = r#"
            .route("/api/health", get(routes::health::health_check))
            .route("/api/progress", post(routes::progress::submit_progress))
        "#;
        let edges = detect_routes(content, "rs", "src/lib.rs");
        assert_eq!(edges.len(), 2);
        let by_handler: std::collections::HashMap<&str, &str> = edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
            .collect();
        assert_eq!(by_handler.get("health_check"), Some(&"GET /api/health"));
        assert_eq!(
            by_handler.get("submit_progress"),
            Some(&"POST /api/progress")
        );
        // Module prefixes must NOT leak into the handler name.
        assert!(!by_handler.contains_key("routes"));
        assert!(!by_handler.contains_key("health"));
        assert!(!by_handler.contains_key("progress"));
    }

    #[test]
    fn test_detect_routes_axum_handler_and_method() {
        // Axum: .route("/path", get(handler))  — handler is group 3, method group 2.
        // Verifies the bug fix where `get` (the method fn) was wrongly used as the
        // handler name, and the method was dropped from the target.
        let content = r#"
            .route("/api/health", get(health_check))
            .route("/api/auth/login", post(login))
            .route("/api/users/:id", get(get_user))
        "#;
        let edges = detect_routes(content, "rs", "src/lib.rs");
        assert_eq!(edges.len(), 3, "expected 3 axum routes");

        // Each edge: source = handler, target = "METHOD /path"
        let by_handler: std::collections::HashMap<&str, &str> = edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
            .collect();
        assert_eq!(by_handler.get("health_check"), Some(&"GET /api/health"));
        assert_eq!(by_handler.get("login"), Some(&"POST /api/auth/login"));
        assert_eq!(by_handler.get("get_user"), Some(&"GET /api/users/:id"));

        // The method fn name `get`/`post` must NOT appear as a handler.
        assert!(!by_handler.contains_key("get"));
        assert!(!by_handler.contains_key("post"));
    }

    #[test]
    fn test_detect_routes_actix() {
        let content = r#".route("/api/items", web::get().to(list_items)).route("/api/items", web::post().to(create_item))"#;
        let edges = detect_routes(content, "rs", "src/routes.rs");
        assert_eq!(edges.len(), 2);
        let by_handler: std::collections::HashMap<&str, &str> = edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
            .collect();
        assert_eq!(by_handler.get("list_items"), Some(&"GET /api/items"));
        assert_eq!(by_handler.get("create_item"), Some(&"POST /api/items"));
    }

    #[test]
    fn test_detect_routes_express() {
        let content = r#"
            app.get('/api/health', healthHandler);
            router.post('/api/login', loginHandler);
        "#;
        let edges = detect_routes(content, "ts", "src/server.ts");
        // express pattern captures method + path + handler (3 groups) but current
        // resolution maps express_route to (path, "", handler) — method empty.
        assert_eq!(edges.len(), 2);
        let by_handler: std::collections::HashMap<&str, &str> = edges
            .iter()
            .map(|e| (e.source.as_str(), e.target.as_str()))
            .collect();
        assert_eq!(by_handler.get("healthHandler"), Some(&"/api/health"));
        assert_eq!(by_handler.get("loginHandler"), Some(&"/api/login"));
    }

    #[test]
    fn test_detect_routes_no_routes() {
        let content = "fn main() { do_stuff() }\n";
        let edges = detect_routes(content, "rs", "src/main.rs");
        assert!(edges.is_empty(), "plain code should yield no routes");
    }

    #[test]
    fn test_detect_routes_unknown_language() {
        let content = "app.get('/x', h)";
        let edges = detect_routes(content, "ruby", "src/app.rb");
        assert!(edges.is_empty());
    }

    #[test]
    fn test_extract_svelte() {
        let content = r#"<script lang="ts">
  import { onMount } from 'svelte';
  export let name: string = 'world';
  export let count: number = 0;
  let doubled = $derived(count * 2);
  let items = $state<string[]>([]);

  function handleClick(): void {
    count++;
  }

  async function fetchData(): Promise<void> {
    const res = await fetch('/api');
  }

  onMount(() => {
    console.log('mounted');
  });
</script>

<button onclick={handleClick}>
  {name} — count: {count}
</button>

{#if count > 0}
  <p>Counting!</p>
{/if}

<style>
  button { padding: 8px; }
</style>
"#;

        let symbols = extract_symbols(content, "svelte", "src/lib/Counter.svelte");
        let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
        println!("Svelte symbols: {:?}", names);

        // AST-based extraction captures function declarations and arrow functions
        // from <script> blocks. Svelte-specific syntax ($state, $derived, props)
        // is NOT captured by the TS grammar — that's expected.
        assert!(
            names.contains(&"handleClick"),
            "missing function: handleClick"
        );
        assert!(names.contains(&"fetchData"), "missing function: fetchData");
    }
}