scribe-selection 0.5.1

Intelligent code selection and context extraction for Scribe
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
//! Tree-sitter based AST parsing for accurate code analysis
//!
//! This module replaces regex-based parsing with proper syntax-aware analysis
//! using tree-sitter parsers for multiple programming languages.

use scribe_core::tokenization::{utils as token_utils, TokenCounter};
use scribe_core::{Result, ScribeError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tree_sitter::{Language, Node, Parser, Query, QueryCursor, Tree};

/// Supported programming languages for AST parsing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AstLanguage {
    Python,
    JavaScript,
    TypeScript,
    Go,
    Rust,
}

impl AstLanguage {
    /// Get the tree-sitter language for this language
    pub fn tree_sitter_language(&self) -> Language {
        match self {
            AstLanguage::Python => tree_sitter_python::language(),
            AstLanguage::JavaScript => tree_sitter_javascript::language(),
            AstLanguage::TypeScript => tree_sitter_typescript::language_typescript(),
            AstLanguage::Go => tree_sitter_go::language(),
            AstLanguage::Rust => tree_sitter_rust::language(),
        }
    }

    /// Detect language from file extension
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext.to_lowercase().as_str() {
            "py" | "pyi" | "pyw" => Some(AstLanguage::Python),
            "js" | "mjs" | "cjs" => Some(AstLanguage::JavaScript),
            "ts" | "mts" | "cts" => Some(AstLanguage::TypeScript),
            "go" => Some(AstLanguage::Go),
            "rs" => Some(AstLanguage::Rust),
            _ => None,
        }
    }
}

/// Import information extracted from AST
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AstImport {
    /// The module being imported
    pub module: String,
    /// Optional alias for the import
    pub alias: Option<String>,
    /// Specific items being imported (for from-imports)
    pub items: Vec<String>,
    /// Line number where the import appears
    pub line_number: usize,
    /// Whether this is a relative import
    pub is_relative: bool,
}

/// A parsed code chunk with semantic information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AstChunk {
    /// The text content of this chunk
    pub content: String,
    /// Type of the chunk (function, class, import, etc.)
    pub chunk_type: String,
    /// Start line (1-indexed)
    pub start_line: usize,
    /// End line (1-indexed)  
    pub end_line: usize,
    /// Start byte offset
    pub start_byte: usize,
    /// End byte offset
    pub end_byte: usize,
    /// Semantic importance score (0.0-1.0)
    pub importance_score: f64,
    /// Estimated token count
    pub estimated_tokens: usize,
    /// Dependencies (other chunks this depends on)
    pub dependencies: Vec<String>,
    /// Name/identifier of this chunk (if applicable)
    pub name: Option<String>,
    /// Whether this is publicly visible
    pub is_public: bool,
    /// Whether this has documentation
    pub has_documentation: bool,
}

/// Extracted signature information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AstSignature {
    /// The signature text
    pub signature: String,
    /// Type of signature (function, class, interface, etc.)
    pub signature_type: String,
    /// Name/identifier
    pub name: String,
    /// Parameters (for functions/methods)
    pub parameters: Vec<String>,
    /// Return type (if available)
    pub return_type: Option<String>,
    /// Whether this is public/exported
    pub is_public: bool,
    /// Line number
    pub line: usize,
}

/// Tree-sitter based AST parser and analyzer
pub struct AstParser {
    parsers: HashMap<AstLanguage, Parser>,
}

impl AstParser {
    /// Create a new AST parser with support for all languages
    pub fn new() -> Result<Self> {
        let mut parsers = HashMap::new();

        for language in [
            AstLanguage::Python,
            AstLanguage::JavaScript,
            AstLanguage::TypeScript,
            AstLanguage::Go,
            AstLanguage::Rust,
        ] {
            let mut parser = Parser::new();
            parser
                .set_language(language.tree_sitter_language())
                .map_err(|e| {
                    ScribeError::parse(format!("Failed to set tree-sitter language: {}", e))
                })?;
            parsers.insert(language, parser);
        }

        Ok(Self { parsers })
    }

    /// Parse code into chunks using tree-sitter AST
    pub fn parse_chunks(&mut self, content: &str, file_path: &str) -> Result<Vec<AstChunk>> {
        let language = self.detect_language(file_path)?;
        let parser = self
            .parsers
            .get_mut(&language)
            .ok_or_else(|| ScribeError::parse(format!("No parser for language: {:?}", language)))?;

        let tree = parser
            .parse(content, None)
            .ok_or_else(|| ScribeError::parse("Failed to parse source code".to_string()))?;

        let chunks = match language {
            AstLanguage::Python => self.parse_python_chunks(content, &tree)?,
            AstLanguage::JavaScript => self.parse_javascript_chunks(content, &tree)?,
            AstLanguage::TypeScript => self.parse_typescript_chunks(content, &tree)?,
            AstLanguage::Go => self.parse_go_chunks(content, &tree)?,
            AstLanguage::Rust => self.parse_rust_chunks(content, &tree)?,
        };

        Ok(chunks)
    }

    /// Extract signatures using tree-sitter AST
    /// Extract imports from the given content using optimized tree-sitter traversal
    pub fn extract_imports(&self, content: &str, language: AstLanguage) -> Result<Vec<AstImport>> {
        // Create a fresh parser for this operation to avoid mutable borrow issues
        let mut parser = Parser::new();
        parser
            .set_language(language.tree_sitter_language())
            .map_err(|e| ScribeError::parse(format!("Failed to set language: {}", e)))?;

        let tree = parser
            .parse(content, None)
            .ok_or_else(|| ScribeError::parse("Failed to parse content"))?;

        let mut imports = Vec::new();

        // Use TreeCursor for efficient traversal
        let mut cursor = tree.walk();
        self.extract_imports_with_cursor(&mut cursor, content, language, &mut imports)?;

        Ok(imports)
    }

    /// Extract imports using TreeCursor for optimal performance
    fn extract_imports_with_cursor(
        &self,
        cursor: &mut tree_sitter::TreeCursor,
        content: &str,
        language: AstLanguage,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        let node = cursor.node();

        // Fast filter: skip nodes that can't contain imports
        if !self.node_can_contain_imports(node.kind()) {
            return Ok(());
        }

        // Process current node if it's an import
        if self.is_import_node(node.kind()) {
            self.extract_import_from_node(node, content, language, imports)?;
        }

        // Traverse children using cursor (much faster than child(i) loops)
        if cursor.goto_first_child() {
            loop {
                self.extract_imports_with_cursor(cursor, content, language, imports)?;
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
            cursor.goto_parent();
        }

        Ok(())
    }

    /// Check if a node type can contain imports (fast filter)
    fn node_can_contain_imports(&self, kind: &str) -> bool {
        matches!(
            kind,
            "import_statement"
                | "import_from_statement"
                | "use_declaration"
                | "import_declaration"
                | "import_spec"
                | "source_file"
                | "module"
                | "program"
                | "translation_unit"
                | "block"
                | "statement_block"
        ) || kind.contains("import")
            || kind.contains("use")
    }

    /// Check if a node is an import statement
    fn is_import_node(&self, kind: &str) -> bool {
        matches!(
            kind,
            "import_statement"
                | "import_from_statement"
                | "use_declaration"
                | "import_declaration"
                | "import_spec"
        )
    }

    /// Extract import from a specific node (no recursion needed)
    fn extract_import_from_node(
        &self,
        node: Node,
        content: &str,
        language: AstLanguage,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        match language {
            AstLanguage::Python => {
                self.extract_python_import_node(node, content, imports)?;
            }
            AstLanguage::JavaScript | AstLanguage::TypeScript => {
                self.extract_js_ts_import_node(node, content, imports)?;
            }
            AstLanguage::Go => {
                self.extract_go_import_node(node, content, imports)?;
            }
            AstLanguage::Rust => {
                self.extract_rust_import_node(node, content, imports)?;
            }
        }
        Ok(())
    }

    pub fn extract_signatures(
        &mut self,
        content: &str,
        file_path: &str,
    ) -> Result<Vec<AstSignature>> {
        let language = self.detect_language(file_path)?;
        let parser = self
            .parsers
            .get_mut(&language)
            .ok_or_else(|| ScribeError::parse(format!("No parser for language: {:?}", language)))?;

        let tree = parser
            .parse(content, None)
            .ok_or_else(|| ScribeError::parse("Failed to parse source code".to_string()))?;

        let signatures = match language {
            AstLanguage::Python => self.extract_python_signatures(content, &tree)?,
            AstLanguage::JavaScript => self.extract_javascript_signatures(content, &tree)?,
            AstLanguage::TypeScript => self.extract_typescript_signatures(content, &tree)?,
            AstLanguage::Go => self.extract_go_signatures(content, &tree)?,
            AstLanguage::Rust => self.extract_rust_signatures(content, &tree)?,
        };

        Ok(signatures)
    }

    /// Detect language from file path
    fn detect_language(&self, file_path: &str) -> Result<AstLanguage> {
        let extension = std::path::Path::new(file_path)
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("");

        AstLanguage::from_extension(extension)
            .ok_or_else(|| ScribeError::parse(format!("Unsupported file extension: {}", extension)))
    }

    /// Parse Python code chunks using tree-sitter
    fn parse_python_chunks(&self, content: &str, tree: &Tree) -> Result<Vec<AstChunk>> {
        let mut chunks = Vec::new();
        let root_node = tree.root_node();

        // Query for Python constructs
        let query_str = r#"
            (import_statement) @import
            (import_from_statement) @import_from
            (function_definition) @function
            (class_definition) @class
            (assignment 
                left: (identifier) @const_name
                right: (_) @const_value
                (#match? @const_name "^[A-Z_][A-Z0-9_]*$")
            ) @constant
        "#;

        let query = Query::new(AstLanguage::Python.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Python query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            for capture in match_.captures {
                let node = capture.node;
                let chunk_type = &query.capture_names()[capture.index as usize];

                let chunk =
                    self.create_chunk_from_node(content, node, chunk_type, &AstLanguage::Python)?;
                chunks.push(chunk);
            }
        }

        // Sort by start position
        chunks.sort_by_key(|c| c.start_byte);
        Ok(chunks)
    }

    /// Parse JavaScript code chunks using tree-sitter
    fn parse_javascript_chunks(&self, content: &str, tree: &Tree) -> Result<Vec<AstChunk>> {
        let mut chunks = Vec::new();
        let root_node = tree.root_node();

        let query_str = r#"
            (import_statement) @import
            (export_statement) @export
            (function_declaration) @function
            (arrow_function) @arrow_function
            (class_declaration) @class
            (interface_declaration) @interface
            (type_alias_declaration) @type_alias
            (variable_declaration
                declarations: (variable_declarator
                    name: (identifier) @const_name
                    value: (_) @const_value
                ) @const_declarator
                (#match? @const_name "^[A-Z_][A-Z0-9_]*$")
            ) @constant
        "#;

        let query = Query::new(AstLanguage::JavaScript.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid JavaScript query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            for capture in match_.captures {
                let node = capture.node;
                let chunk_type = &query.capture_names()[capture.index as usize];

                let chunk = self.create_chunk_from_node(
                    content,
                    node,
                    chunk_type,
                    &AstLanguage::JavaScript,
                )?;
                chunks.push(chunk);
            }
        }

        chunks.sort_by_key(|c| c.start_byte);
        Ok(chunks)
    }

    /// Parse TypeScript code chunks using tree-sitter
    fn parse_typescript_chunks(&self, content: &str, tree: &Tree) -> Result<Vec<AstChunk>> {
        let mut chunks = Vec::new();
        let root_node = tree.root_node();

        let query_str = r#"
            (import_statement) @import
            (export_statement) @export
            (function_declaration) @function
            (arrow_function) @arrow_function
            (class_declaration) @class
            (interface_declaration) @interface
            (type_alias_declaration) @type_alias
            (enum_declaration) @enum
            (module_declaration) @module
            (variable_declaration
                declarations: (variable_declarator
                    name: (identifier) @const_name
                    value: (_) @const_value
                ) @const_declarator
                (#match? @const_name "^[A-Z_][A-Z0-9_]*$")
            ) @constant
        "#;

        let query = Query::new(AstLanguage::TypeScript.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid TypeScript query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            for capture in match_.captures {
                let node = capture.node;
                let chunk_type = &query.capture_names()[capture.index as usize];

                let chunk = self.create_chunk_from_node(
                    content,
                    node,
                    chunk_type,
                    &AstLanguage::TypeScript,
                )?;
                chunks.push(chunk);
            }
        }

        chunks.sort_by_key(|c| c.start_byte);
        Ok(chunks)
    }

    /// Parse Go code chunks using tree-sitter
    fn parse_go_chunks(&self, content: &str, tree: &Tree) -> Result<Vec<AstChunk>> {
        let mut chunks = Vec::new();
        let root_node = tree.root_node();

        let query_str = r#"
            (package_clause) @package
            (import_declaration) @import
            (function_declaration) @function
            (method_declaration) @method
            (type_declaration) @type
            (const_declaration) @const
            (var_declaration) @var
        "#;

        let query = Query::new(AstLanguage::Go.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Go query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            for capture in match_.captures {
                let node = capture.node;
                let chunk_type = &query.capture_names()[capture.index as usize];

                let chunk =
                    self.create_chunk_from_node(content, node, chunk_type, &AstLanguage::Go)?;
                chunks.push(chunk);
            }
        }

        chunks.sort_by_key(|c| c.start_byte);
        Ok(chunks)
    }

    /// Parse Rust code chunks using tree-sitter
    fn parse_rust_chunks(&self, content: &str, tree: &Tree) -> Result<Vec<AstChunk>> {
        let mut chunks = Vec::new();
        let root_node = tree.root_node();

        let query_str = r#"
            (use_declaration) @use
            (mod_item) @mod
            (struct_item) @struct
            (enum_item) @enum
            (trait_item) @trait
            (impl_item) @impl
            (function_item) @function
            (const_item) @const
            (static_item) @static
            (type_item) @type_alias
        "#;

        let query = Query::new(AstLanguage::Rust.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Rust query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            for capture in match_.captures {
                let node = capture.node;
                let chunk_type = &query.capture_names()[capture.index as usize];

                let chunk =
                    self.create_chunk_from_node(content, node, chunk_type, &AstLanguage::Rust)?;
                chunks.push(chunk);
            }
        }

        chunks.sort_by_key(|c| c.start_byte);
        Ok(chunks)
    }

    /// Create a chunk from a tree-sitter node
    fn create_chunk_from_node(
        &self,
        content: &str,
        node: Node,
        chunk_type: &str,
        language: &AstLanguage,
    ) -> Result<AstChunk> {
        let start_byte = node.start_byte();
        let end_byte = node.end_byte();
        let start_position = node.start_position();
        let end_position = node.end_position();

        let chunk_content = &content[start_byte..end_byte];
        let estimated_tokens = TokenCounter::global()
            .count_tokens(chunk_content)
            .unwrap_or_else(|_| token_utils::estimate_tokens_legacy(chunk_content));

        // Calculate importance score based on chunk type and language
        let importance_score = self.calculate_importance_score(chunk_type, language, node, content);

        // Extract name if available
        let name = self.extract_name_from_node(node, content);

        // Check if public/exported
        let is_public = self.is_node_public(node, content);

        // Check for documentation
        let has_documentation = self.has_documentation(node, content);

        // Extract dependencies (simplified for now)
        let dependencies = self.extract_dependencies(node, content);

        Ok(AstChunk {
            content: chunk_content.to_string(),
            chunk_type: chunk_type.to_string(),
            start_line: start_position.row + 1,
            end_line: end_position.row + 1,
            start_byte,
            end_byte,
            importance_score,
            estimated_tokens,
            dependencies,
            name,
            is_public,
            has_documentation,
        })
    }

    /// Calculate importance score based on AST analysis
    fn calculate_importance_score(
        &self,
        chunk_type: &str,
        language: &AstLanguage,
        node: Node,
        content: &str,
    ) -> f64 {
        let mut score: f64 = match chunk_type {
            "import" | "import_from" | "use" => 0.9, // Imports are crucial
            "package" => 0.95,                       // Package declarations are essential
            "class" | "struct_item" | "trait_item" => 0.85, // Type definitions
            "interface" | "type_alias" | "enum" => 0.8, // Type definitions
            "function" | "method" => 0.75,           // Functions
            "const" | "constant" | "static" => 0.6,  // Constants
            "export" => 0.7,                         // Exports
            "mod" | "module" => 0.65,                // Modules
            _ => 0.5,                                // Default
        };

        // Boost score for public/exported items
        if self.is_node_public(node, content) {
            score += 0.1;
        }

        // Boost score for documented items
        if self.has_documentation(node, content) {
            score += 0.05;
        }

        // Language-specific adjustments
        match language {
            AstLanguage::Rust => {
                // Rust impl blocks are very important
                if chunk_type == "impl" {
                    score = 0.85;
                }
            }
            AstLanguage::TypeScript => {
                // TypeScript interfaces are crucial
                if chunk_type == "interface" {
                    score = 0.9;
                }
            }
            _ => {}
        }

        score.min(1.0)
    }

    /// Extract name/identifier from a node
    fn extract_name_from_node(&self, node: Node, content: &str) -> Option<String> {
        // Look for name field in node
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if child.kind() == "identifier" || child.kind() == "type_identifier" {
                    let name_bytes = &content.as_bytes()[child.start_byte()..child.end_byte()];
                    if let Ok(name) = std::str::from_utf8(name_bytes) {
                        return Some(name.to_string());
                    }
                }
            }
        }
        None
    }

    /// Check if a node represents a public/exported item
    fn is_node_public(&self, node: Node, content: &str) -> bool {
        // Check for pub keyword in Rust
        if let Some(parent) = node.parent() {
            for i in 0..parent.child_count() {
                if let Some(child) = parent.child(i) {
                    if child.kind() == "visibility_modifier" {
                        let vis_bytes = &content.as_bytes()[child.start_byte()..child.end_byte()];
                        if let Ok(vis) = std::str::from_utf8(vis_bytes) {
                            return vis.contains("pub");
                        }
                    }
                }
            }
        }

        // Check for export in JS/TS
        let node_text = &content[node.start_byte()..node.end_byte()];
        node_text.starts_with("export") || node_text.contains("export")
    }

    /// Check if a node has associated documentation
    fn has_documentation(&self, node: Node, content: &str) -> bool {
        // Look for comments before the node
        if let Some(prev_sibling) = node.prev_sibling() {
            if prev_sibling.kind() == "comment" {
                return true;
            }
        }

        // Look for docstrings in Python
        if node.kind() == "function_definition" || node.kind() == "class_definition" {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "expression_statement" {
                        if let Some(grandchild) = child.child(0) {
                            if grandchild.kind() == "string" {
                                let string_content =
                                    &content[grandchild.start_byte()..grandchild.end_byte()];
                                if string_content.starts_with("\"\"\"")
                                    || string_content.starts_with("'''")
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }

        false
    }

    /// Extract dependencies from a node (simplified implementation)
    fn extract_dependencies(&self, node: Node, content: &str) -> Vec<String> {
        let mut dependencies = Vec::new();

        // For import nodes, extract the imported modules
        if node.kind() == "import_statement"
            || node.kind() == "import_from_statement"
            || node.kind() == "use_declaration"
        {
            // This is a simplified implementation
            // In a full implementation, we'd parse the specific import syntax
            let import_text = &content[node.start_byte()..node.end_byte()];

            // Extract quoted strings as module names
            let mut in_quote = false;
            let mut quote_char = '"';
            let mut current_module = String::new();

            for ch in import_text.chars() {
                if ch == '"' || ch == '\'' {
                    if !in_quote {
                        in_quote = true;
                        quote_char = ch;
                    } else if ch == quote_char {
                        in_quote = false;
                        if !current_module.is_empty() {
                            dependencies.push(current_module.clone());
                            current_module.clear();
                        }
                    }
                } else if in_quote {
                    current_module.push(ch);
                }
            }
        }

        dependencies
    }

    /// Extract signatures for Python
    fn extract_python_signatures(&self, content: &str, tree: &Tree) -> Result<Vec<AstSignature>> {
        let mut signatures = Vec::new();
        let root_node = tree.root_node();

        let query_str = r#"
            (function_definition 
                name: (identifier) @func_name
                parameters: (parameters) @func_params
            ) @function
            (class_definition 
                name: (identifier) @class_name
            ) @class
            (import_statement) @import
            (import_from_statement) @import_from
        "#;

        let query = Query::new(AstLanguage::Python.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Python signature query: {}", e)))?;

        let mut cursor = QueryCursor::new();
        let captures = cursor.matches(&query, root_node, content.as_bytes());

        for match_ in captures {
            let signature = self.extract_signature_from_match(content, &match_, &query)?;
            signatures.push(signature);
        }

        Ok(signatures)
    }

    /// Extract signatures for other languages (similar pattern)
    fn extract_javascript_signatures(
        &self,
        content: &str,
        tree: &Tree,
    ) -> Result<Vec<AstSignature>> {
        let query_str = r#"
            (function_declaration
                name: (identifier) @name
            ) @function

            (arrow_function) @function

            (class_declaration
                name: (identifier) @name
            ) @class

            (import_statement) @import
            (export_statement) @export
        "#;

        let query =
            Query::new(AstLanguage::JavaScript.tree_sitter_language(), query_str).map_err(|e| {
                ScribeError::parse(format!("Invalid JavaScript signature query: {}", e))
            })?;

        let root_node = tree.root_node();
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&query, root_node, content.as_bytes());

        let mut signatures = Vec::new();
        for match_ in matches {
            let signature = self.extract_signature_from_match(content, &match_, &query)?;
            signatures.push(signature);
        }

        Ok(signatures)
    }

    fn extract_typescript_signatures(
        &self,
        content: &str,
        tree: &Tree,
    ) -> Result<Vec<AstSignature>> {
        let query_str = r#"
            (function_declaration
                name: (identifier) @name
            ) @function

            (interface_declaration
                name: (type_identifier) @name
            ) @interface

            (type_alias_declaration
                name: (type_identifier) @name
            ) @type

            (class_declaration
                name: (identifier) @name
            ) @class

            (import_statement) @import
            (export_statement) @export
        "#;

        let query =
            Query::new(AstLanguage::TypeScript.tree_sitter_language(), query_str).map_err(|e| {
                ScribeError::parse(format!("Invalid TypeScript signature query: {}", e))
            })?;

        let root_node = tree.root_node();
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&query, root_node, content.as_bytes());

        let mut signatures = Vec::new();
        for match_ in matches {
            let signature = self.extract_signature_from_match(content, &match_, &query)?;
            signatures.push(signature);
        }

        Ok(signatures)
    }

    fn extract_go_signatures(&self, content: &str, tree: &Tree) -> Result<Vec<AstSignature>> {
        let query_str = r#"
            (function_declaration
                name: (identifier) @name
            ) @function

            (type_declaration
                (type_spec
                    name: (type_identifier) @name
                )
            ) @type

            (import_declaration) @import
            (package_clause) @package
        "#;

        let query = Query::new(AstLanguage::Go.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Go signature query: {}", e)))?;

        let root_node = tree.root_node();
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&query, root_node, content.as_bytes());

        let mut signatures = Vec::new();
        for match_ in matches {
            let signature = self.extract_signature_from_match(content, &match_, &query)?;
            signatures.push(signature);
        }

        Ok(signatures)
    }

    fn extract_rust_signatures(&self, content: &str, tree: &Tree) -> Result<Vec<AstSignature>> {
        let query_str = r#"
            (function_item
                name: (identifier) @name
            ) @function

            (impl_item
                type: (type_identifier) @type_name
            ) @impl

            (struct_item
                name: (type_identifier) @name
            ) @struct

            (enum_item
                name: (type_identifier) @name
            ) @enum

            (trait_item
                name: (type_identifier) @name
            ) @trait

            (mod_item
                name: (identifier) @name
            ) @module

            (use_declaration) @use
        "#;

        let query = Query::new(AstLanguage::Rust.tree_sitter_language(), query_str)
            .map_err(|e| ScribeError::parse(format!("Invalid Rust signature query: {}", e)))?;

        let root_node = tree.root_node();
        let mut cursor = tree_sitter::QueryCursor::new();
        let matches = cursor.matches(&query, root_node, content.as_bytes());

        let mut signatures = Vec::new();
        for match_ in matches {
            let signature = self.extract_signature_from_match(content, &match_, &query)?;
            signatures.push(signature);
        }

        Ok(signatures)
    }

    /// Extract signature from a query match
    fn extract_signature_from_match(
        &self,
        content: &str,
        match_: &tree_sitter::QueryMatch,
        query: &Query,
    ) -> Result<AstSignature> {
        let mut signature_text = String::new();
        let mut signature_type = String::new();
        let mut name = String::new();
        let mut line = 0;

        for capture in match_.captures {
            let capture_name = &query.capture_names()[capture.index as usize];
            let node = capture.node;
            let node_text = &content[node.start_byte()..node.end_byte()];

            match capture_name.as_str() {
                "function" | "class" | "import" | "import_from" => {
                    signature_text = node_text.lines().next().unwrap_or("").to_string();
                    signature_type = capture_name.to_string();
                    line = node.start_position().row + 1;
                }
                "func_name" | "class_name" => {
                    name = node_text.to_string();
                }
                _ => {}
            }
        }

        Ok(AstSignature {
            signature: signature_text,
            signature_type,
            name,
            parameters: Vec::new(), // Simplified
            return_type: None,      // Simplified
            is_public: false,       // Simplified
            line,
        })
    }

    /// Extract Python import from a single node (optimized, no recursion)
    fn extract_python_import_node(
        &self,
        node: Node,
        content: &str,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        // Look for import_statement and import_from_statement nodes
        if node.kind() == "import_statement" {
            // Handle import statements like "import os" or "import sys as system"
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "aliased_import" {
                        // Handle "import sys as system"
                        if let Some(name_node) = child.child_by_field_name("name") {
                            let module = self.node_text(name_node, content);
                            let alias = child
                                .child_by_field_name("alias")
                                .map(|alias_node| self.node_text(alias_node, content));
                            let line_number = name_node.start_position().row + 1;

                            imports.push(AstImport {
                                module,
                                alias,
                                items: vec![],
                                line_number,
                                is_relative: false,
                            });
                        }
                    } else if child.kind() == "dotted_as_name" {
                        // Handle dotted imports with alias like "import package.module as mod"
                        if let Some(name_node) = child.child_by_field_name("name") {
                            let module = self.node_text(name_node, content);
                            let alias = child
                                .child_by_field_name("alias")
                                .map(|alias_node| self.node_text(alias_node, content));
                            let line_number = name_node.start_position().row + 1;

                            imports.push(AstImport {
                                module,
                                alias,
                                items: vec![],
                                line_number,
                                is_relative: false,
                            });
                        }
                    } else if child.kind() == "dotted_name" || child.kind() == "identifier" {
                        // Handle simple "import os"
                        let module = self.node_text(child, content);
                        let line_number = child.start_position().row + 1;

                        imports.push(AstImport {
                            module,
                            alias: None,
                            items: vec![],
                            line_number,
                            is_relative: false,
                        });
                    }
                }
            }
        } else if node.kind() == "import_from_statement" {
            let mut module = String::new();
            let mut items = Vec::new();
            let mut is_relative = false;

            if let Some(module_node) = node.child_by_field_name("module_name") {
                module = self.node_text(module_node, content);
                is_relative = module.starts_with('.');
            }

            // Get imported items
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "import_list" {
                        for j in 0..child.child_count() {
                            if let Some(item) = child.child(j) {
                                if item.kind() == "dotted_name" || item.kind() == "identifier" {
                                    items.push(self.node_text(item, content));
                                }
                            }
                        }
                    }
                }
            }

            let line_number = node.start_position().row + 1;
            imports.push(AstImport {
                module,
                alias: None,
                items,
                line_number,
                is_relative,
            });
        }

        Ok(())
    }

    /// Extract JavaScript/TypeScript import from a single node (optimized, no recursion)
    fn extract_js_ts_import_node(
        &self,
        node: Node,
        content: &str,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        if node.kind() == "import_statement" {
            let mut module = String::new();
            let items = Vec::new();

            // Find the source
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "string" {
                        module = self.node_text(child, content);
                        // Remove quotes
                        module = module.trim_matches('"').trim_matches('\'').to_string();
                        break;
                    }
                }
            }

            let line_number = node.start_position().row + 1;
            imports.push(AstImport {
                module,
                alias: None,
                items,
                line_number,
                is_relative: false,
            });
        }
        Ok(())
    }

    /// Extract Go import from a single node (optimized, no recursion)
    fn extract_go_import_node(
        &self,
        node: Node,
        content: &str,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        if node.kind() == "import_spec" {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "interpreted_string_literal" {
                        let module = self.node_text(child, content);
                        let module = module.trim_matches('"').to_string();
                        let line_number = child.start_position().row + 1;

                        imports.push(AstImport {
                            module,
                            alias: None,
                            items: vec![],
                            line_number,
                            is_relative: false,
                        });
                    }
                }
            }
        }
        Ok(())
    }

    /// Extract Rust import from a single node (optimized, no recursion)
    fn extract_rust_import_node(
        &self,
        node: Node,
        content: &str,
        imports: &mut Vec<AstImport>,
    ) -> Result<()> {
        if node.kind() == "use_declaration" {
            if let Some(use_tree) = node.child_by_field_name("argument") {
                let module = self.node_text(use_tree, content);
                let line_number = node.start_position().row + 1;

                imports.push(AstImport {
                    module,
                    alias: None,
                    items: vec![],
                    line_number,
                    is_relative: false,
                });
            }
        }
        Ok(())
    }

    /// Helper to extract text from a node
    fn node_text(&self, node: Node, content: &str) -> String {
        content[node.start_byte()..node.end_byte()].to_string()
    }

    /// Search for entities (functions, classes, etc.) by name within parsed content
    ///
    /// Returns locations of all matching entities across the provided content.
    pub fn find_entities(
        &mut self,
        content: &str,
        file_path: &str,
        query: &EntityQuery,
    ) -> Result<Vec<EntityLocation>> {
        let chunks = self.parse_chunks(content, file_path)?;
        let mut locations = Vec::new();

        for chunk in chunks {
            if self.matches_query(&chunk, query) {
                locations.push(EntityLocation {
                    file_path: file_path.to_string(),
                    entity_type: chunk.chunk_type.clone(),
                    entity_name: chunk.name.clone().unwrap_or_default(),
                    start_line: chunk.start_line,
                    end_line: chunk.end_line,
                    is_public: chunk.is_public,
                    content: chunk.content.clone(),
                });
            }
        }

        Ok(locations)
    }

    /// Check if a chunk matches the entity query
    fn matches_query(&self, chunk: &AstChunk, query: &EntityQuery) -> bool {
        // Match by entity type if specified
        if let Some(ref entity_type) = query.entity_type {
            if !self.chunk_type_matches(entity_type, &chunk.chunk_type) {
                return false;
            }
        }

        // Match by name if specified
        if let Some(ref name_pattern) = query.name_pattern {
            let chunk_name = chunk.name.as_deref().unwrap_or("");
            if query.exact_match {
                if chunk_name != name_pattern {
                    return false;
                }
            } else {
                // Case-insensitive substring match
                if !chunk_name.to_lowercase().contains(&name_pattern.to_lowercase()) {
                    return false;
                }
            }
        }

        // Match by visibility if specified
        if let Some(public_only) = query.public_only {
            if public_only && !chunk.is_public {
                return false;
            }
        }

        true
    }

    /// Check if chunk type matches the requested entity type
    fn chunk_type_matches(&self, requested: &EntityType, chunk_type: &str) -> bool {
        match requested {
            EntityType::Function => matches!(chunk_type, "function" | "method"),
            EntityType::Class => matches!(chunk_type, "class" | "struct_item" | "trait_item"),
            EntityType::Module => matches!(chunk_type, "mod" | "module" | "package"),
            EntityType::Interface => matches!(chunk_type, "interface" | "trait_item"),
            EntityType::Constant => matches!(chunk_type, "const" | "constant" | "static"),
            EntityType::Any => true,
        }
    }
}

/// Entity type for search queries
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum EntityType {
    Function,
    Class,
    Module,
    Interface,
    Constant,
    Any,
}

/// Query for finding entities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityQuery {
    /// Type of entity to search for (None means any type)
    pub entity_type: Option<EntityType>,
    /// Name pattern to match (None means any name)
    pub name_pattern: Option<String>,
    /// Whether to match name exactly (vs substring)
    pub exact_match: bool,
    /// Only return public/exported entities
    pub public_only: Option<bool>,
}

impl EntityQuery {
    /// Create a query for any entity with a specific name
    pub fn by_name(name: &str) -> Self {
        Self {
            entity_type: None,
            name_pattern: Some(name.to_string()),
            exact_match: false,
            public_only: None,
        }
    }

    /// Create a query for a specific entity type
    pub fn by_type(entity_type: EntityType) -> Self {
        Self {
            entity_type: Some(entity_type),
            name_pattern: None,
            exact_match: false,
            public_only: None,
        }
    }

    /// Create a query for a specific function by name
    pub fn function(name: &str) -> Self {
        Self {
            entity_type: Some(EntityType::Function),
            name_pattern: Some(name.to_string()),
            exact_match: false,
            public_only: None,
        }
    }

    /// Create a query for a specific class/struct by name
    pub fn class(name: &str) -> Self {
        Self {
            entity_type: Some(EntityType::Class),
            name_pattern: Some(name.to_string()),
            exact_match: false,
            public_only: None,
        }
    }

    /// Create a query for a specific module by path
    pub fn module(path: &str) -> Self {
        Self {
            entity_type: Some(EntityType::Module),
            name_pattern: Some(path.to_string()),
            exact_match: false,
            public_only: None,
        }
    }

    /// Set whether to match exactly
    pub fn exact(mut self) -> Self {
        self.exact_match = true;
        self
    }

    /// Only match public/exported entities
    pub fn public(mut self) -> Self {
        self.public_only = Some(true);
        self
    }
}

/// Location of an entity in the codebase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityLocation {
    /// File path containing the entity
    pub file_path: String,
    /// Type of entity (function, class, etc.)
    pub entity_type: String,
    /// Name of the entity
    pub entity_name: String,
    /// Start line number (1-indexed)
    pub start_line: usize,
    /// End line number (1-indexed)
    pub end_line: usize,
    /// Whether this entity is public/exported
    pub is_public: bool,
    /// Full content of the entity
    pub content: String,
}

impl EntityLocation {
    /// Get a unique identifier for this entity
    pub fn identifier(&self) -> String {
        format!("{}::{}", self.file_path, self.entity_name)
    }
}

impl Default for AstParser {
    fn default() -> Self {
        Self::new().expect("Failed to create AstParser")
    }
}

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

    #[test]
    fn test_ast_parser_creation() {
        let parser = AstParser::new();
        assert!(parser.is_ok());
    }

    #[test]
    fn test_language_detection() {
        assert_eq!(AstLanguage::from_extension("py"), Some(AstLanguage::Python));
        assert_eq!(
            AstLanguage::from_extension("js"),
            Some(AstLanguage::JavaScript)
        );
        assert_eq!(
            AstLanguage::from_extension("ts"),
            Some(AstLanguage::TypeScript)
        );
        assert_eq!(AstLanguage::from_extension("go"), Some(AstLanguage::Go));
        assert_eq!(AstLanguage::from_extension("rs"), Some(AstLanguage::Rust));
        assert_eq!(AstLanguage::from_extension("unknown"), None);
    }

    #[test]
    fn test_python_parsing() {
        let mut parser = AstParser::new().unwrap();
        let content = r#"
import os
import sys

def hello_world():
    """A simple function."""
    print("Hello, world!")

class Calculator:
    """A simple calculator."""
    
    def add(self, a, b):
        return a + b
"#;

        let chunks = parser.parse_chunks(content, "test.py").unwrap();
        assert!(!chunks.is_empty());

        // Should find imports, function, and class
        let chunk_types: Vec<&str> = chunks.iter().map(|c| c.chunk_type.as_str()).collect();
        assert!(chunk_types.contains(&"import"));
        assert!(chunk_types.contains(&"function"));
        assert!(chunk_types.contains(&"class"));
    }

    #[test]
    fn test_rust_parsing() {
        let mut parser = AstParser::new().unwrap();
        let content = r#"
use std::collections::HashMap;

pub struct DataProcessor {
    data: HashMap<String, i32>,
}

impl DataProcessor {
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
        }
    }
}
"#;

        let chunks = parser.parse_chunks(content, "test.rs").unwrap();
        assert!(!chunks.is_empty());

        let chunk_types: Vec<&str> = chunks.iter().map(|c| c.chunk_type.as_str()).collect();
        assert!(chunk_types.contains(&"use"));
        assert!(chunk_types.contains(&"struct"));
        assert!(chunk_types.contains(&"impl"));
    }

    #[test]
    fn test_signature_extraction() {
        let mut parser = AstParser::new().unwrap();
        let content = r#"
def calculate(a: int, b: int) -> int:
    return a + b

class Calculator:
    def multiply(self, x, y):
        return x * y
"#;

        let signatures = parser.extract_signatures(content, "test.py").unwrap();
        assert!(!signatures.is_empty());
    }
}