vera2-core 0.12.16-aristoddle.1

Core engine for Vera: parsing, indexing, retrieval, storage, and embedding
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
//! Symbol-aware chunking and Tier 0 fallback.
//!
//! Converts extracted AST symbols into [`Chunk`]s. Handles:
//! - Symbol → chunk mapping with metadata
//! - Large symbol splitting (>configured threshold)
//! - Gap chunks for inter-symbol code (imports, module-level statements)
//! - Tier 0 fallback: sliding-window line-based chunking for unknown languages

use crate::chunk_text::file_name;
use crate::config::IndexingConfig;
use crate::types::{Chunk, Language, SymbolType};

use super::extractor::RawSymbol;

/// Default sliding-window size for Tier 0 fallback (lines).
const TIER0_WINDOW_SIZE: u32 = 50;
/// Default overlap for Tier 0 sliding-window (lines).
const TIER0_OVERLAP: u32 = 10;

/// Line comment markers per language family. Used to recognise doc comments.
fn comment_prefixes(language: Language) -> &'static [&'static str] {
    match language {
        Language::Python
        | Language::Ruby
        | Language::Bash
        | Language::Yaml
        | Language::Toml
        | Language::Perl
        | Language::R
        | Language::Julia
        | Language::Elixir
        | Language::Dockerfile
        | Language::Nix
        | Language::Hcl
        | Language::Makefile
        | Language::CMake
        | Language::PowerShell => &["#"],
        Language::Lua | Language::Sql | Language::Haskell => &["--"],
        Language::Html | Language::Vue | Language::Astro | Language::Svelte => &["<!--"],
        _ => &["//"],
    }
}

/// Is this (trimmed) source line part of a comment in `language`? Block
/// comment interiors ("* ...") and terminators count for C-family languages.
fn is_comment_line(line: &str, language: Language) -> bool {
    if comment_prefixes(language)
        .iter()
        .any(|prefix| line.starts_with(prefix))
    {
        return true;
    }
    // C-family block comment interior/end lines.
    comment_prefixes(language).first() == Some(&"//")
        && (line.starts_with("/*") || line.starts_with('*') || line.starts_with("*/"))
}

/// Create chunks from extracted symbols (Tier 1A: symbol-aware chunking).
///
/// Produces one chunk per symbol. Large symbols exceeding `max_chunk_lines`
/// are split into sub-chunks with no content gaps. Inter-symbol gaps
/// (imports, blank lines, module-level code) are captured as gap chunks.
pub fn chunks_from_symbols(
    symbols: &[RawSymbol],
    source: &str,
    file_path: &str,
    language: Language,
    config: &IndexingConfig,
) -> Vec<Chunk> {
    let lines: Vec<&str> = source.lines().collect();
    let total_lines = lines.len() as u32;
    let mut chunks = Vec::new();
    let mut chunk_index: u32 = 0;

    // Track coverage to identify gaps
    let mut covered_end_row: u32 = 0;

    for symbol in symbols {
        let mut sym_start = symbol.start_row as u32;
        let sym_end = symbol.end_row as u32;
        let has_nested_symbol = language == Language::Bash
            && symbols.iter().any(|child| {
                child.start_byte > symbol.start_byte
                    && child.end_byte <= symbol.end_byte
                    && child.end_byte > child.start_byte
            });

        // A documentation comment documents the symbol below it; attaching it
        // to the symbol chunk keeps the topical prose, the signature, and the
        // symbol metadata in one retrievable unit instead of stranding the
        // doc text in a symbol-less gap chunk.
        let mut attach_start = sym_start;
        let mut row = sym_start;
        while row > covered_end_row {
            let line = lines[(row - 1) as usize].trim_start();
            if line.is_empty() {
                break; // blank line: the comment above is not attached
            }
            if is_comment_line(line, language) {
                attach_start = row - 1;
                row -= 1;
            } else {
                break;
            }
        }
        sym_start = attach_start;

        let sym_lines = sym_end.saturating_sub(sym_start) + 1;

        // Capture gap before this symbol (imports, blank lines, etc.)
        if sym_start > covered_end_row {
            let gap_content = join_lines(&lines, covered_end_row, sym_start.saturating_sub(1));
            if !gap_content.trim().is_empty() {
                chunks.push(Chunk {
                    id: format!("{file_path}:{chunk_index}"),
                    file_path: file_path.to_string(),
                    line_start: covered_end_row + 1, // 1-based
                    line_end: sym_start,             // 1-based
                    content: gap_content,
                    language,
                    symbol_type: Some(SymbolType::Block),
                    symbol_name: None,
                });
                chunk_index += 1;
            }
        }

        // Split large symbols into sub-chunks
        if sym_lines > config.max_chunk_lines && !has_nested_symbol {
            let sub_chunks = split_large_symbol(
                symbol,
                sym_start,
                &lines,
                file_path,
                language,
                config.max_chunk_lines,
                &mut chunk_index,
            );
            chunks.extend(sub_chunks);
        } else {
            let content = join_lines(&lines, sym_start, sym_end);
            chunks.push(Chunk {
                id: format!("{file_path}:{chunk_index}"),
                file_path: file_path.to_string(),
                line_start: sym_start + 1, // 1-based
                line_end: sym_end + 1,     // 1-based
                content,
                language,
                symbol_type: Some(symbol.symbol_type),
                symbol_name: symbol.name.clone(),
            });
            chunk_index += 1;
        }

        // Extractors emit a parent (impl, class, namespace) alongside its
        // children, and symbols are sorted by start byte, so the parent is
        // seen first. Advancing monotonically stops a child from rewinding
        // coverage back inside the parent, which would make every span
        // between children look like an uncovered gap.
        covered_end_row = covered_end_row.max(sym_end + 1);
    }

    // Trailing gap after last symbol
    if covered_end_row < total_lines {
        let gap_content = join_lines(&lines, covered_end_row, total_lines.saturating_sub(1));
        if !gap_content.trim().is_empty() {
            chunks.push(Chunk {
                id: format!("{file_path}:{chunk_index}"),
                file_path: file_path.to_string(),
                line_start: covered_end_row + 1, // 1-based
                line_end: total_lines,           // 1-based
                content: gap_content,
                language,
                symbol_type: Some(SymbolType::Block),
                symbol_name: None,
            });
        }
    }

    chunks
}

/// Create a single whole-file chunk.
///
/// Used for config and document-like files where the filename and full file
/// context are more important than symbol-level segmentation.
pub fn whole_file_chunk(source: &str, file_path: &str, language: Language) -> Vec<Chunk> {
    if source.trim().is_empty() {
        return Vec::new();
    }

    vec![Chunk {
        id: format!("{file_path}:0"),
        file_path: file_path.to_string(),
        line_start: 1,
        line_end: source.lines().count().max(1) as u32,
        content: source.to_string(),
        language,
        symbol_type: Some(SymbolType::Block),
        symbol_name: Some(file_name(file_path).to_string()),
    }]
}

/// Split a large symbol into sub-chunks of at most `max_lines` lines.
///
/// Uses smart boundary detection: prefers splitting after closing braces (`}`),
/// semicolons, or blank lines rather than at arbitrary line counts. Falls back
/// to the hard `max_lines` limit when no good boundary exists nearby.
fn split_large_symbol(
    symbol: &RawSymbol,
    start_row: u32,
    lines: &[&str],
    file_path: &str,
    language: Language,
    max_lines: u32,
    chunk_index: &mut u32,
) -> Vec<Chunk> {
    let mut chunks = Vec::new();
    let start = start_row;
    let end = symbol.end_row as u32;
    let mut current = start;
    let mut part = 1u32;

    while current <= end {
        let ideal_end = (current + max_lines - 1).min(end);
        let chunk_end = if ideal_end >= end {
            end
        } else {
            find_split_boundary(lines, current, ideal_end, max_lines)
        };
        let content = join_lines(lines, current, chunk_end);
        let sub_name = symbol.name.as_ref().map(|n| format!("{n} (part {part})"));

        chunks.push(Chunk {
            id: format!("{file_path}:{}", *chunk_index),
            file_path: file_path.to_string(),
            line_start: current + 1, // 1-based
            line_end: chunk_end + 1, // 1-based
            content,
            language,
            symbol_type: Some(symbol.symbol_type),
            symbol_name: sub_name,
        });

        *chunk_index += 1;
        part += 1;
        current = chunk_end + 1;
    }

    chunks
}

/// Find the best line to split at, searching backward from `ideal_end`.
///
/// Looks for (in priority order): closing brace on its own line, semicolon at
/// end of line, blank line. Searches up to 30% of `max_lines` backward. If no
/// good boundary is found, returns `ideal_end` (hard split).
fn find_split_boundary(lines: &[&str], start: u32, ideal_end: u32, max_lines: u32) -> u32 {
    let lookback = (max_lines * 3 / 10).max(3).min(ideal_end - start);
    let search_start = ideal_end.saturating_sub(lookback);

    // Pass 1: closing brace alone on a line (strongest boundary).
    for row in (search_start..=ideal_end).rev() {
        let trimmed = lines.get(row as usize).map(|l| l.trim()).unwrap_or("");
        if trimmed == "}" || trimmed == "};" || trimmed == "}," {
            return row;
        }
    }

    // Pass 2: line ending with semicolon or blank line.
    for row in (search_start..=ideal_end).rev() {
        let trimmed = lines.get(row as usize).map(|l| l.trim()).unwrap_or("");
        if trimmed.is_empty() || trimmed.ends_with(';') {
            return row;
        }
    }

    ideal_end
}

/// A Markdown fenced code block marker and its minimum closing length.
#[derive(Clone, Copy)]
struct MarkdownFence {
    marker: char,
    length: usize,
}

fn markdown_fence(line: &str) -> Option<MarkdownFence> {
    let indentation = line.bytes().take_while(|byte| *byte == b' ').count();
    if indentation > 3 {
        return None;
    }

    let rest = &line[indentation..];
    let marker = rest.chars().next()?;
    if marker != '`' && marker != '~' {
        return None;
    }

    let length = rest
        .chars()
        .take_while(|character| *character == marker)
        .count();
    (length >= 3).then_some(MarkdownFence { marker, length })
}

fn markdown_fence_closes(line: &str, fence: MarkdownFence) -> bool {
    let indentation = line.bytes().take_while(|byte| *byte == b' ').count();
    if indentation > 3 {
        return false;
    }

    let rest = &line[indentation..];
    let marker_count = rest
        .chars()
        .take_while(|character| *character == fence.marker)
        .count();
    marker_count >= fence.length && rest.chars().skip(marker_count).all(char::is_whitespace)
}

/// Split a markdown file into section-based chunks.
///
/// Each heading (# through ######) starts a new chunk. Content before the
/// first heading becomes a chunk named after the file. This produces better
/// search results than whole-file chunking because each section has a
/// focused topic and heading as its symbol name.
pub fn markdown_section_chunks(source: &str, file_path: &str) -> Vec<Chunk> {
    if source.trim().is_empty() {
        return Vec::new();
    }

    let lines: Vec<&str> = source.lines().collect();
    let mut chunks = Vec::new();
    let mut chunk_index: u32 = 0;

    // Track current section
    let mut section_start: usize = 0;
    let mut section_name: Option<String> = None;
    let mut fence: Option<MarkdownFence> = None;

    for (i, line) in lines.iter().enumerate() {
        if let Some(active_fence) = fence {
            if markdown_fence_closes(line, active_fence) {
                fence = None;
            }
            continue;
        }

        if let Some(opening_fence) = markdown_fence(line) {
            fence = Some(opening_fence);
            continue;
        }

        let trimmed = line.trim_start();
        if trimmed.starts_with('#') {
            // Extract heading text (strip leading #s and whitespace)
            let heading = trimmed.trim_start_matches('#').trim();
            if heading.is_empty() && !trimmed.contains(' ') {
                // Not a real heading (e.g., just "###" with no text)
                continue;
            }

            // Flush previous section
            if i > section_start {
                let content = join_lines(&lines, section_start as u32, (i - 1) as u32);
                if !content.trim().is_empty() {
                    let name = section_name
                        .take()
                        .unwrap_or_else(|| file_name(file_path).to_string());
                    chunks.push(Chunk {
                        id: format!("{file_path}:{chunk_index}"),
                        file_path: file_path.to_string(),
                        line_start: section_start as u32 + 1,
                        line_end: i as u32,
                        content,
                        language: Language::Markdown,
                        symbol_type: Some(SymbolType::Block),
                        symbol_name: Some(name),
                    });
                    chunk_index += 1;
                }
            }

            section_start = i;
            section_name = Some(heading.to_string());
        }
    }

    // Flush final section
    let content = join_lines(&lines, section_start as u32, (lines.len() - 1) as u32);
    if !content.trim().is_empty() {
        let name = section_name.unwrap_or_else(|| file_name(file_path).to_string());
        chunks.push(Chunk {
            id: format!("{file_path}:{chunk_index}"),
            file_path: file_path.to_string(),
            line_start: section_start as u32 + 1,
            line_end: lines.len() as u32,
            content,
            language: Language::Markdown,
            symbol_type: Some(SymbolType::Block),
            symbol_name: Some(name),
        });
    }

    // If no headings found, fall back to single whole-file chunk
    if chunks.is_empty() {
        return whole_file_chunk(source, file_path, Language::Markdown);
    }

    chunks
}

/// Split an RST file into heading-based chunks.
///
/// `headings` is expected to come from tree-sitter title nodes as
/// `(start_row, title_text)` pairs (0-based rows).
pub fn rst_section_chunks(source: &str, file_path: &str, headings: &[(u32, String)]) -> Vec<Chunk> {
    if source.trim().is_empty() {
        return Vec::new();
    }

    let lines: Vec<&str> = source.lines().collect();
    if lines.is_empty() {
        return Vec::new();
    }

    let mut sections: Vec<(usize, String)> = headings
        .iter()
        .filter_map(|(row, title)| {
            let row = *row as usize;
            if row >= lines.len() {
                return None;
            }
            let normalized = title.split_whitespace().collect::<Vec<_>>().join(" ");
            if normalized.is_empty() {
                return None;
            }
            Some((row, normalized))
        })
        .collect();

    sections.sort_by_key(|(row, _)| *row);
    sections.dedup_by(|a, b| a.0 == b.0);

    if sections.is_empty() {
        return whole_file_chunk(source, file_path, Language::Rst);
    }

    let mut chunks = Vec::new();
    let mut chunk_index: u32 = 0;

    let first_start = sections[0].0 as u32;
    if first_start > 0 {
        let preface = join_lines(&lines, 0, first_start.saturating_sub(1));
        if !preface.trim().is_empty() {
            chunks.push(Chunk {
                id: format!("{file_path}:{chunk_index}"),
                file_path: file_path.to_string(),
                line_start: 1,
                line_end: first_start,
                content: preface,
                language: Language::Rst,
                symbol_type: Some(SymbolType::Block),
                symbol_name: Some(file_name(file_path).to_string()),
            });
            chunk_index += 1;
        }
    }

    for (idx, (start_row, title)) in sections.iter().enumerate() {
        let end_row = if idx + 1 < sections.len() {
            sections[idx + 1].0.saturating_sub(1)
        } else {
            lines.len().saturating_sub(1)
        };

        if end_row < *start_row {
            continue;
        }

        let content = join_lines(&lines, *start_row as u32, end_row as u32);
        if content.trim().is_empty() {
            continue;
        }

        chunks.push(Chunk {
            id: format!("{file_path}:{chunk_index}"),
            file_path: file_path.to_string(),
            line_start: *start_row as u32 + 1,
            line_end: end_row as u32 + 1,
            content,
            language: Language::Rst,
            symbol_type: Some(SymbolType::Block),
            symbol_name: Some(title.clone()),
        });
        chunk_index += 1;
    }

    if chunks.is_empty() {
        return whole_file_chunk(source, file_path, Language::Rst);
    }

    chunks
}

/// Tier 0 fallback: sliding-window line-based chunking.
///
/// Used for files with no tree-sitter grammar support. Produces overlapping
/// chunks of `TIER0_WINDOW_SIZE` lines with `TIER0_OVERLAP` overlap.
pub fn tier0_line_chunks(source: &str, file_path: &str, language: Language) -> Vec<Chunk> {
    let lines: Vec<&str> = source.lines().collect();
    let total = lines.len() as u32;

    if total == 0 {
        return Vec::new();
    }

    let mut chunks = Vec::new();
    let mut start: u32 = 0;
    let mut chunk_index: u32 = 0;
    let step = TIER0_WINDOW_SIZE.saturating_sub(TIER0_OVERLAP);

    while start < total {
        let end = (start + TIER0_WINDOW_SIZE - 1).min(total - 1);
        let content = join_lines(&lines, start, end);

        if !content.trim().is_empty() {
            chunks.push(Chunk {
                id: format!("{file_path}:{chunk_index}"),
                file_path: file_path.to_string(),
                line_start: start + 1, // 1-based
                line_end: end + 1,     // 1-based
                content,
                language,
                symbol_type: Some(SymbolType::Block),
                symbol_name: None,
            });
            chunk_index += 1;
        }

        // Avoid infinite loop when step is 0
        if step == 0 {
            break;
        }
        start += step;
    }

    chunks
}

/// Split chunks that exceed `max_bytes` into smaller sub-chunks at line boundaries.
///
/// Uses a byte-length pre-filter: chunks already under the limit are passed
/// through untouched (the common case for ~70-80% of chunks). Oversized chunks
/// are split at natural boundaries using `find_split_boundary`.
pub fn split_oversized_chunks(chunks: Vec<Chunk>, max_bytes: usize) -> Vec<Chunk> {
    if max_bytes == 0 {
        return chunks;
    }

    let mut result = Vec::with_capacity(chunks.len());
    for chunk in chunks {
        if chunk.content.len() <= max_bytes {
            result.push(chunk);
            continue;
        }

        let lines: Vec<&str> = chunk.content.lines().collect();
        let total = lines.len() as u32;
        let mut current: u32 = 0;
        let mut part = 1u32;

        while current < total {
            // Binary search for the largest end line that fits within max_bytes.
            let mut lo = current;
            let mut hi = (total - 1).min(current + 500); // cap search range
            while lo < hi {
                let mid = lo + (hi - lo).div_ceil(2);
                let candidate: usize = lines[current as usize..=mid as usize]
                    .iter()
                    .map(|l| l.len() + 1)
                    .sum();
                if candidate <= max_bytes {
                    lo = mid;
                } else {
                    hi = mid - 1;
                }
            }

            // Ensure at least one line per sub-chunk.
            let end = lo.max(current);
            let sub_content = lines[current as usize..=end as usize].join("\n");
            let sub_name = chunk
                .symbol_name
                .as_ref()
                .map(|n| format!("{n} (part {part})"));

            result.push(Chunk {
                id: format!("{}:{part}", chunk.id),
                file_path: chunk.file_path.clone(),
                line_start: chunk.line_start + current,
                line_end: chunk.line_start + end,
                content: sub_content,
                language: chunk.language,
                symbol_type: chunk.symbol_type,
                symbol_name: if part == 1 && end + 1 >= total {
                    chunk.symbol_name.clone()
                } else {
                    sub_name
                },
            });

            part += 1;
            current = end + 1;
        }
    }
    result
}

/// Join lines from `start_row` to `end_row` (inclusive, 0-based) into a string.
fn join_lines(lines: &[&str], start_row: u32, end_row: u32) -> String {
    let start = start_row as usize;
    let end = (end_row as usize).min(lines.len().saturating_sub(1));
    if start > end || start >= lines.len() {
        return String::new();
    }
    lines[start..=end].join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsing::extractor::RawSymbol;
    use crate::types::SymbolType;

    fn default_config() -> IndexingConfig {
        IndexingConfig {
            max_chunk_lines: 200,
            ..Default::default()
        }
    }

    #[test]
    fn single_symbol_becomes_one_chunk() {
        let source = "fn hello() {\n    println!(\"hi\");\n}\n";
        let symbols = vec![RawSymbol {
            name: Some("hello".to_string()),
            symbol_type: SymbolType::Function,
            start_byte: 0,
            end_byte: source.len(),
            start_row: 0,
            end_row: 2,
        }];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "test.rs",
            Language::Rust,
            &default_config(),
        );
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].symbol_name, Some("hello".to_string()));
        assert_eq!(chunks[0].symbol_type, Some(SymbolType::Function));
        assert_eq!(chunks[0].line_start, 1);
        assert_eq!(chunks[0].line_end, 3);
    }

    #[test]
    fn gap_between_symbols_captured() {
        let source = "use std::io;\n\nfn hello() {\n}\n\nfn world() {\n}\n";
        let symbols = vec![
            RawSymbol {
                name: Some("hello".to_string()),
                symbol_type: SymbolType::Function,
                start_byte: 0,
                end_byte: 0,
                start_row: 2,
                end_row: 3,
            },
            RawSymbol {
                name: Some("world".to_string()),
                symbol_type: SymbolType::Function,
                start_byte: 0,
                end_byte: 0,
                start_row: 5,
                end_row: 6,
            },
        ];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "test.rs",
            Language::Rust,
            &default_config(),
        );
        // Should have: gap (imports), hello, world
        assert!(
            chunks.len() >= 2,
            "expected >= 2 chunks, got {}",
            chunks.len()
        );
        // First chunk should be the gap (imports)
        assert_eq!(chunks[0].symbol_type, Some(SymbolType::Block));
        assert!(chunks[0].content.contains("use std::io"));
    }

    #[test]
    fn nested_children_emit_no_gap_chunks() {
        // Extractors push the `impl` and each of its methods, sorted by start
        // byte. The span between two methods and the impl's closing brace are
        // already inside the parent chunk and must not be emitted again.
        let source = "impl Token {\n    /// Create a token.\n    fn new() -> Self {\n        Self\n    }\n\n    /// Cancel the token.\n    fn cancel(&self) {}\n}\n";
        let symbols = vec![
            RawSymbol {
                name: Some("Token".to_string()),
                symbol_type: SymbolType::Block,
                start_byte: 0,
                end_byte: source.len(),
                start_row: 0,
                end_row: 8,
            },
            RawSymbol {
                name: Some("new".to_string()),
                symbol_type: SymbolType::Method,
                start_byte: 40,
                end_byte: 80,
                start_row: 2,
                end_row: 4,
            },
            RawSymbol {
                name: Some("cancel".to_string()),
                symbol_type: SymbolType::Method,
                start_byte: 110,
                end_byte: 130,
                start_row: 7,
                end_row: 7,
            },
        ];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "token.rs",
            Language::Rust,
            &default_config(),
        );

        let names: Vec<_> = chunks.iter().map(|c| c.symbol_name.clone()).collect();
        assert_eq!(
            names,
            vec![
                Some("Token".to_string()),
                Some("new".to_string()),
                Some("cancel".to_string()),
            ],
            "only the parent and its two children should be chunked, got {chunks:?}"
        );
        assert!(
            !chunks.iter().any(|c| c.content.trim() == "}"),
            "the parent's closing brace must not become its own chunk"
        );
    }

    #[test]
    fn large_bash_dispatcher_keeps_parent_whole_and_emits_case_chunks() {
        let source = r#"function nvm() {
  case "$1" in
    use)
      echo use
      ;;
    deactivate)
      echo deactivate
      ;;
    install)
      echo install
      ;;
    *)
      echo other
      ;;
  esac
}"#;
        let grammar = crate::parsing::languages::tree_sitter_grammar(Language::Bash).unwrap();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&grammar).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let symbols =
            crate::parsing::extractor::extract_symbols(&tree, source.as_bytes(), Language::Bash);
        let config = IndexingConfig {
            max_chunk_lines: 4,
            ..Default::default()
        };
        let chunks = chunks_from_symbols(&symbols, source, "nvm.sh", Language::Bash, &config);

        let names: Vec<_> = chunks
            .iter()
            .map(|chunk| chunk.symbol_name.as_deref())
            .collect();
        assert_eq!(
            names,
            vec![
                Some("nvm"),
                Some("nvm use"),
                Some("nvm deactivate"),
                Some("nvm install"),
                Some("nvm *"),
            ]
        );
        assert_eq!((chunks[0].line_start, chunks[0].line_end), (1, 16));
        assert_eq!((chunks[1].line_start, chunks[1].line_end), (3, 5));
        assert_eq!((chunks[2].line_start, chunks[2].line_end), (6, 8));
        assert_eq!((chunks[3].line_start, chunks[3].line_end), (9, 11));
        assert_eq!((chunks[4].line_start, chunks[4].line_end), (12, 14));
        assert!(chunks[0].content.contains("esac"));
        assert!(chunks.iter().all(|chunk| {
            !chunk
                .symbol_name
                .as_deref()
                .unwrap_or_default()
                .contains("part")
        }));
    }

    #[test]
    fn gap_after_nested_parent_still_captured() {
        // Monotonic coverage must not swallow real code that follows the
        // parent, only the spans the parent already covers.
        let source = "impl Token {\n    fn new() -> Self {\n        Self\n    }\n}\n\nstatic REGISTRY: &str = \"tokens\";\n";
        let symbols = vec![
            RawSymbol {
                name: Some("Token".to_string()),
                symbol_type: SymbolType::Block,
                start_byte: 0,
                end_byte: 60,
                start_row: 0,
                end_row: 4,
            },
            RawSymbol {
                name: Some("new".to_string()),
                symbol_type: SymbolType::Method,
                start_byte: 17,
                end_byte: 55,
                start_row: 1,
                end_row: 3,
            },
        ];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "token.rs",
            Language::Rust,
            &default_config(),
        );

        let names: Vec<_> = chunks.iter().map(|c| c.symbol_name.clone()).collect();
        assert_eq!(
            names,
            vec![Some("Token".to_string()), Some("new".to_string()), None],
            "the parent and its child must still be chunked before the trailing gap, got {chunks:?}"
        );

        let trailing = chunks
            .iter()
            .find(|c| c.symbol_name.is_none())
            .expect("trailing top-level code should still produce a gap chunk");
        assert_eq!(trailing.symbol_type, Some(SymbolType::Block));
        assert_eq!(trailing.line_start, 6);
        assert_eq!(trailing.line_end, 7);
        assert!(trailing.content.contains("static REGISTRY"));
    }

    #[test]
    fn large_symbol_split_into_sub_chunks() {
        // Create a large function (10 lines, with max_chunk_lines=3)
        let mut lines = vec!["fn big() {".to_string()];
        for i in 0..8 {
            lines.push(format!("    let x{i} = {i};"));
        }
        lines.push("}".to_string());
        let source = lines.join("\n");

        let symbols = vec![RawSymbol {
            name: Some("big".to_string()),
            symbol_type: SymbolType::Function,
            start_byte: 0,
            end_byte: source.len(),
            start_row: 0,
            end_row: 9,
        }];

        let config = IndexingConfig {
            max_chunk_lines: 3,
            ..Default::default()
        };
        let chunks = chunks_from_symbols(&symbols, &source, "test.rs", Language::Rust, &config);

        // 10 lines / 3 lines per chunk = 4 sub-chunks (3+3+3+1)
        assert_eq!(
            chunks.len(),
            4,
            "expected 4 sub-chunks, got {}",
            chunks.len()
        );

        // Verify no content gaps: reconstruct and compare
        let mut all_content = String::new();
        for (i, chunk) in chunks.iter().enumerate() {
            if i > 0 {
                all_content.push('\n');
            }
            all_content.push_str(&chunk.content);
            // Sub-chunks should have part numbers in name
            assert!(
                chunk.symbol_name.as_ref().unwrap().contains("part"),
                "sub-chunk should have part number"
            );
        }
        assert_eq!(all_content, source);
    }

    #[test]
    fn tier0_fallback_produces_chunks() {
        let mut lines = Vec::new();
        for i in 0..120 {
            lines.push(format!("line {i}"));
        }
        let source = lines.join("\n");

        let chunks = tier0_line_chunks(&source, "data.xyz", Language::Unknown);
        // 120 lines, window=50, overlap=10, step=40
        // Chunks: [0..49], [40..89], [80..119] = 3 chunks
        assert_eq!(
            chunks.len(),
            3,
            "expected 3 tier0 chunks, got {}",
            chunks.len()
        );

        // All chunks should have Block type
        for chunk in &chunks {
            assert_eq!(chunk.symbol_type, Some(SymbolType::Block));
            assert_eq!(chunk.language, Language::Unknown);
        }

        // First chunk starts at line 1
        assert_eq!(chunks[0].line_start, 1);
        assert_eq!(chunks[0].line_end, 50);

        // Second chunk overlaps
        assert_eq!(chunks[1].line_start, 41);
        assert_eq!(chunks[1].line_end, 90);
    }

    #[test]
    fn tier0_empty_source_no_chunks() {
        let chunks = tier0_line_chunks("", "empty.xyz", Language::Unknown);
        assert!(chunks.is_empty());
    }

    #[test]
    fn tier0_small_file_one_chunk() {
        let source = "line 1\nline 2\nline 3";
        let chunks = tier0_line_chunks(source, "small.xyz", Language::Unknown);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].line_start, 1);
        assert_eq!(chunks[0].line_end, 3);
    }

    #[test]
    fn chunks_have_correct_file_path() {
        let source = "fn foo() {}\n";
        let symbols = vec![RawSymbol {
            name: Some("foo".to_string()),
            symbol_type: SymbolType::Function,
            start_byte: 0,
            end_byte: source.len(),
            start_row: 0,
            end_row: 0,
        }];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "src/lib.rs",
            Language::Rust,
            &default_config(),
        );
        assert_eq!(chunks[0].file_path, "src/lib.rs");
    }

    #[test]
    fn chunks_have_unique_ids() {
        let source = "fn a() {}\nfn b() {}\n";
        let symbols = vec![
            RawSymbol {
                name: Some("a".to_string()),
                symbol_type: SymbolType::Function,
                start_byte: 0,
                end_byte: 0,
                start_row: 0,
                end_row: 0,
            },
            RawSymbol {
                name: Some("b".to_string()),
                symbol_type: SymbolType::Function,
                start_byte: 0,
                end_byte: 0,
                start_row: 1,
                end_row: 1,
            },
        ];
        let chunks = chunks_from_symbols(
            &symbols,
            source,
            "test.rs",
            Language::Rust,
            &default_config(),
        );
        let ids: Vec<_> = chunks.iter().map(|c| &c.id).collect();
        let unique: std::collections::HashSet<_> = ids.iter().collect();
        assert_eq!(ids.len(), unique.len(), "all chunk IDs should be unique");
    }

    #[test]
    fn whole_file_chunk_uses_filename_as_symbol() {
        let chunks = whole_file_chunk("[workspace]\nmembers = []\n", "Cargo.toml", Language::Toml);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("Cargo.toml"));
        assert_eq!(chunks[0].line_start, 1);
        assert_eq!(chunks[0].line_end, 2);
    }

    #[test]
    fn markdown_fenced_comments_do_not_start_sections() {
        let source =
            "# Real Title\n\n```python\n# this is a comment\nx = 1\n```\n## Next Title\ntext\n";

        let chunks = markdown_section_chunks(source, "README.md");

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("Real Title"));
        assert!(chunks[0].content.contains("# this is a comment"));
        assert_eq!(chunks[1].symbol_name.as_deref(), Some("Next Title"));
    }

    #[test]
    fn markdown_fences_support_tildes_and_commonmark_indentation() {
        let source = "# Title\n\n   ~~~yaml\n   # not a heading\n   ~~~\n## Next\n";

        let chunks = markdown_section_chunks(source, "README.md");

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("Title"));
        assert!(
            !chunks[0]
                .symbol_name
                .as_deref()
                .unwrap()
                .contains("not a heading")
        );
        assert_eq!(chunks[1].symbol_name.as_deref(), Some("Next"));
    }

    #[test]
    fn markdown_unclosed_fence_keeps_following_hashes_in_section() {
        let source = "# Title\n\n~~~python\n# comment\n## not a heading\n";

        let chunks = markdown_section_chunks(source, "README.md");

        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0].symbol_name.as_deref(), Some("Title"));
        assert!(chunks[0].content.contains("## not a heading"));
    }
}