ascfix 0.7.1

Automatic ASCII diagram repair tool for Markdown files
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
//! List normalization for Markdown lists.
//!
//! This module detects and normalizes Markdown lists, fixing inconsistent
//! indentation and bullet styles.

/// Represents a detected list item.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Reason: Part of public API for library usage
pub struct ListItem {
    /// The bullet character (-, *, +) or number for ordered lists
    pub marker: String,
    /// The content of the list item (after the bullet)
    pub content: String,
    /// Indentation level (0 = top level, 1 = nested, etc.)
    pub level: usize,
    /// Whether this is a task list item (- \[ \], - \[x\])
    pub is_task: bool,
    /// Checkbox state for task lists (Some(true) = checked, Some(false) = unchecked, None = not a task)
    pub checked: Option<bool>,
    /// The line number where this item starts
    pub line_number: usize,
}

/// Represents a complete list.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(dead_code)] // Reason: Part of public API for library usage
pub struct List {
    /// All items in the list
    pub items: Vec<ListItem>,
    /// The starting line number of the list
    pub start_line: usize,
    /// The ending line number of the list
    pub end_line: usize,
    /// Whether this is an ordered (numbered) list
    pub is_ordered: bool,
}

/// Detect all lists in the given content.
///
/// Identifies both bullet lists (-, *, +) and ordered lists (1., 2), etc.).
/// Lists inside code blocks are ignored.
///
/// # Examples
///
/// ```
/// use ascfix::lists::detect_lists;
///
/// let content = "- Item 1\n- Item 2\n- Item 3";
/// let lists = detect_lists(content);
/// assert_eq!(lists.len(), 1);
/// assert_eq!(lists[0].items.len(), 3);
/// ```
#[must_use]
#[allow(dead_code)] // Reason: Public API for list detection, used in tests
pub fn detect_lists(content: &str) -> Vec<List> {
    let mut lists = Vec::new();
    let lines: Vec<&str> = content.lines().collect();

    // Get code block line ranges to skip
    let code_line_ranges = get_code_block_line_ranges(content);

    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];

        // Skip lines inside code blocks
        if is_in_code_region(i, &code_line_ranges) {
            i += 1;
            continue;
        }

        // Check if this line starts a list item
        if let Some(item) = parse_list_item(line, i) {
            // Check if we're continuing an existing list or starting a new one
            let mut current_list_items = vec![item];
            let start_line = i;
            i += 1;

            // Continue collecting list items
            while i < lines.len() {
                let next_line = lines[i];

                // Skip code block lines
                if is_in_code_region(i, &code_line_ranges) {
                    break;
                }

                // Check for continuation (blank lines or nested content)
                if next_line.trim().is_empty() {
                    // Look ahead to see if list continues
                    if i + 1 < lines.len() {
                        if let Some(next_item) = parse_list_item(lines[i + 1], i + 1) {
                            // Check if this continues the same list
                            if is_same_list(&current_list_items, &next_item) {
                                i += 1; // Skip blank line
                                continue;
                            }
                        }
                    }
                    break;
                }

                // Check for new list item
                if let Some(next_item) = parse_list_item(next_line, i) {
                    // Check if same list or nested
                    if is_same_list(&current_list_items, &next_item)
                        || is_nested_list(&current_list_items, &next_item)
                    {
                        current_list_items.push(next_item);
                        i += 1;
                        continue;
                    }
                }

                // Check for continuation line (indented content)
                if is_continuation_line(next_line, &current_list_items) {
                    i += 1;
                    continue;
                }

                break;
            }

            // Create the list
            if !current_list_items.is_empty() {
                let is_ordered = current_list_items[0].marker.parse::<i32>().is_ok();
                lists.push(List {
                    items: current_list_items,
                    start_line,
                    end_line: i - 1,
                    is_ordered,
                });
            }
        } else {
            i += 1;
        }
    }

    lists
}

/// Get code block regions as line number ranges (`start_line`, `end_line`).
fn get_code_block_line_ranges(content: &str) -> Vec<(usize, usize)> {
    let mut ranges = Vec::new();
    let lines: Vec<&str> = content.lines().collect();
    let mut in_code_block = false;
    let mut block_start = 0;

    for (i, &line) in lines.iter().enumerate() {
        let trimmed = line.trim();

        // Check for fence markers
        if is_fence_line(trimmed) {
            if in_code_block {
                // End of code block
                ranges.push((block_start, i));
                in_code_block = false;
            } else {
                // Start of code block
                block_start = i;
                in_code_block = true;
            }
        }
    }

    // Handle unclosed code block
    if in_code_block {
        ranges.push((block_start, lines.len() - 1));
    }

    ranges
}

/// Check if a line is a fence marker (starts with backticks or tildes).
fn is_fence_line(line: &str) -> bool {
    line.starts_with("```") || line.starts_with("~~~")
}

/// Parse a single line to see if it's a list item.
fn parse_list_item(line: &str, line_number: usize) -> Option<ListItem> {
    let trimmed = line.trim_start();

    // Check for bullet list markers: -, *, +
    if let Some(rest) = trimmed.strip_prefix("- ") {
        return parse_task_or_item("-", rest, line_number);
    }
    if let Some(rest) = trimmed.strip_prefix("* ") {
        return Some(ListItem {
            marker: "*".to_string(),
            content: rest.to_string(),
            level: 0, // Will be calculated based on indentation
            is_task: false,
            checked: None,
            line_number,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("+ ") {
        return Some(ListItem {
            marker: "+".to_string(),
            content: rest.to_string(),
            level: 0,
            is_task: false,
            checked: None,
            line_number,
        });
    }

    // Check for ordered list markers: 1., 2), etc.
    // Pattern: number followed by . or )
    let chars: Vec<char> = trimmed.chars().collect();
    if !chars.is_empty() && chars[0].is_ascii_digit() {
        // Find the end of the number
        let mut num_end = 0;
        while num_end < chars.len() && chars[num_end].is_ascii_digit() {
            num_end += 1;
        }

        if num_end < chars.len() && (chars[num_end] == '.' || chars[num_end] == ')') {
            let number = &trimmed[0..num_end];
            let rest = trimmed[num_end + 1..].trim_start();
            return Some(ListItem {
                marker: number.to_string(),
                content: rest.to_string(),
                level: 0,
                is_task: false,
                checked: None,
                line_number,
            });
        }
    }

    None
}

/// Check if content is a task list item and parse accordingly.
fn parse_task_or_item(marker: &str, content: &str, line_number: usize) -> Option<ListItem> {
    let trimmed = content.trim_start();

    // Check for task list: [ ], [x], [X]
    if let Some(rest) = trimmed.strip_prefix("[ ] ") {
        return Some(ListItem {
            marker: marker.to_string(),
            content: rest.to_string(),
            level: 0,
            is_task: true,
            checked: Some(false),
            line_number,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("[x] ") {
        return Some(ListItem {
            marker: marker.to_string(),
            content: rest.to_string(),
            level: 0,
            is_task: true,
            checked: Some(true),
            line_number,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("[X] ") {
        return Some(ListItem {
            marker: marker.to_string(),
            content: rest.to_string(),
            level: 0,
            is_task: true,
            checked: Some(true),
            line_number,
        });
    }

    // Regular bullet item
    Some(ListItem {
        marker: marker.to_string(),
        content: content.to_string(),
        level: 0,
        is_task: false,
        checked: None,
        line_number,
    })
}

/// Check if a new item belongs to the same list as existing items.
#[allow(dead_code)] // Reason: Used by detect_lists
fn is_same_list(existing_items: &[ListItem], new_item: &ListItem) -> bool {
    if existing_items.is_empty() {
        return true;
    }

    // Same bullet style or both ordered
    let first = &existing_items[0];

    // Check if both use same bullet type
    if ["-", "*", "+"].contains(&first.marker.as_str())
        && ["-", "*", "+"].contains(&new_item.marker.as_str())
    {
        return true;
    }

    // Check if both are ordered lists
    if first.marker.parse::<i32>().is_ok() && new_item.marker.parse::<i32>().is_ok() {
        return true;
    }

    false
}

/// Check if a new item is a nested list item.
#[allow(dead_code)] // Reason: Used by detect_lists
fn is_nested_list(existing_items: &[ListItem], new_item: &ListItem) -> bool {
    // A nested item has more indentation
    // For now, just check if it's indented more than the first item
    if existing_items.is_empty() {
        return false;
    }

    // Compare line numbers to determine nesting
    // In practice, we'd need the actual indentation levels
    new_item.line_number > existing_items[0].line_number
}

/// Check if a line is a continuation of the current list item.
#[allow(dead_code)] // Reason: Used by detect_lists
fn is_continuation_line(line: &str, current_items: &[ListItem]) -> bool {
    if current_items.is_empty() {
        return false;
    }

    // A continuation line is indented (has leading whitespace)
    // and doesn't start a new list item
    if line.trim().is_empty() {
        return false;
    }

    let leading_spaces = line.len() - line.trim_start().len();
    // Must have at least 2 spaces of indentation to be a continuation
    leading_spaces >= 2 && parse_list_item(line, 0).is_none()
}

/// Check if a line number is inside a code block region.
fn is_in_code_region(line_num: usize, regions: &[(usize, usize)]) -> bool {
    for (start, end) in regions {
        if line_num >= *start && line_num <= *end {
            return true;
        }
    }
    false
}

/// Compute the required indentation string for a given nesting level.
///
/// Each parent level contributes spaces based on its marker type:
/// - Ordered markers (`1`, `10`, etc.): `marker.len() + 2` spaces (number + ". ")
/// - Unordered markers (`-`, `*`, `+`): 2 spaces ("- ")
///
/// This ensures continuation content is indented correctly per the `CommonMark`
/// spec, where `1. ` requires ≥3 spaces for child content and `- ` requires ≥2.
fn required_indent_for_level(stack: &[(usize, String)], level: usize) -> String {
    let mut total = 0;
    for (_, marker) in stack.iter().take(level) {
        if marker.parse::<i32>().is_ok() {
            // Ordered: "N. " contributes marker.len() + 2 spaces
            total += marker.len() + 2;
        } else {
            // Unordered: "- " contributes 2 spaces
            total += 2;
        }
    }
    " ".repeat(total)
}

/// Normalize list indentation to standard 2-space increments for unordered lists.
///
/// Takes content with lists and normalizes the indentation of nested items.
/// For unordered list parents, uses 2-space increments per nesting level.
/// For ordered list parents, uses the correct `CommonMark` continuation width
/// (marker length + 2) to avoid breaking nested list parsing.
///
/// # Examples
///
/// ```
/// use ascfix::lists::normalize_list_indentation;
///
/// let content = "- Item 1\n    - Nested item\n- Item 2";
/// let normalized = normalize_list_indentation(content);
/// assert!(normalized.contains("  - Nested item")); // 2 spaces, not 4
/// ```
#[must_use]
#[allow(dead_code)] // Reason: Public API for list normalization, used in tests
pub fn normalize_list_indentation(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    if lines.is_empty() {
        return String::new();
    }

    // Get code block regions to skip
    let code_ranges = get_code_block_line_ranges(content);

    let mut result = Vec::new();
    // Stack stores (original_indent, marker) for each nesting level
    let mut list_stack: Vec<(usize, String)> = Vec::new();

    for (i, &line) in lines.iter().enumerate() {
        // Skip lines inside code blocks
        if is_in_code_region(i, &code_ranges) {
            result.push(line.to_string());
            continue;
        }

        // Check if this line is a list item
        if let Some(item) = parse_list_item(line, i) {
            let current_indent = line.len() - line.trim_start().len();

            // Determine the nesting level based on indentation
            let level = if list_stack.is_empty() {
                // First item in a list
                list_stack.push((current_indent, item.marker.clone()));
                0
            } else {
                // Find the appropriate level based on indentation
                let mut level = list_stack.len();
                for (idx, (indent, _)) in list_stack.iter().enumerate() {
                    if current_indent <= *indent {
                        level = idx;
                        break;
                    }
                }

                // Trim stack to current level
                list_stack.truncate(level);

                // If this is a new nesting level, add it
                if level == list_stack.len() {
                    list_stack.push((current_indent, item.marker.clone()));
                }

                level
            };

            // Calculate normalized indentation based on parent marker types
            let normalized_indent = required_indent_for_level(&list_stack, level);
            let reconstructed = format!("{}{} {}", normalized_indent, item.marker, item.content);
            result.push(reconstructed);
        } else {
            // Non-list line — pass through unchanged.
            // Do not clear the stack on blank lines: a blank line inside a
            // loose list item (e.g. "1. item\n\n   - sub") is valid CommonMark
            // continuation and must preserve the ordered-list context so that
            // subsequent sub-items receive the correct indentation.
            result.push(line.to_string());
        }
    }

    result.join("\n")
}

/// Normalize bullet styles to a consistent character.
///
/// Converts all bullet list markers (`-`, `*`, `+`) to the specified style.
/// Ordered lists are not affected. Task list syntax is preserved.
///
/// # Arguments
///
/// * `content` - The content containing lists to normalize
/// * `target_bullet` - The bullet character to use (`-`, `*`, or `+`)
///
/// # Examples
///
/// ```
/// use ascfix::lists::normalize_bullet_styles;
///
/// let content = "- Item 1\n* Item 2\n+ Item 3";
/// let normalized = normalize_bullet_styles(content, '-');
/// assert!(normalized.contains("- Item 1"));
/// assert!(normalized.contains("- Item 2"));
/// assert!(normalized.contains("- Item 3"));
/// ```
#[must_use]
#[allow(dead_code)] // Reason: Public API for list normalization, used in tests
pub fn normalize_bullet_styles(content: &str, target_bullet: char) -> String {
    let lines: Vec<&str> = content.lines().collect();
    if lines.is_empty() {
        return String::new();
    }

    // Validate target bullet
    let target = match target_bullet {
        '-' | '*' | '+' => target_bullet,
        _ => '-', // Default to dash if invalid
    };

    // Get code block regions to skip
    let code_ranges = get_code_block_line_ranges(content);

    let mut result = Vec::new();

    for (i, &line) in lines.iter().enumerate() {
        // Skip lines inside code blocks
        if is_in_code_region(i, &code_ranges) {
            result.push(line.to_string());
            continue;
        }

        // Check if this line is a list item
        if let Some(item) = parse_list_item(line, i) {
            // Only modify bullet lists (not ordered lists)
            if ["-", "*", "+"].contains(&item.marker.as_str()) {
                let indent = line.len() - line.trim_start().len();
                let indent_str = " ".repeat(indent);

                // Reconstruct with target bullet
                let reconstructed = if item.is_task {
                    format!(
                        "{}{} [{}] {}",
                        indent_str,
                        target,
                        if item.checked.unwrap_or(false) {
                            "x"
                        } else {
                            " "
                        },
                        item.content
                    )
                } else {
                    format!("{}{} {}", indent_str, target, item.content)
                };
                result.push(reconstructed);
            } else {
                // Ordered list - keep as is
                result.push(line.to_string());
            }
        } else {
            result.push(line.to_string());
        }
    }

    result.join("\n")
}

/// Normalize lists in content with both indentation and bullet style fixes.
///
/// Combines indentation normalization (2-space increments) and bullet style
/// normalization (consistent `-` style) in a single pass.
///
/// # Examples
///
/// ```
/// use ascfix::lists::normalize_lists;
///
/// let content = "- Item 1\n    * Nested with 4 spaces\n+ Item 2";
/// let normalized = normalize_lists(content);
/// assert!(normalized.contains("- Item 1"));
/// assert!(normalized.contains("  - Nested with 4 spaces")); // 2 spaces, normalized
/// assert!(normalized.contains("- Item 2")); // + changed to -
/// ```
#[must_use]
pub fn normalize_lists(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    if lines.is_empty() {
        return String::new();
    }

    // Get code block regions to skip
    let code_ranges = get_code_block_line_ranges(content);

    let mut result = Vec::new();
    // Stack stores (original_indent, marker) for each nesting level
    let mut list_stack: Vec<(usize, String)> = Vec::new();
    let target_bullet = '-';

    for (i, &line) in lines.iter().enumerate() {
        // Skip lines inside code blocks
        if is_in_code_region(i, &code_ranges) {
            result.push(line.to_string());
            // Reset stack when entering code block
            list_stack.clear();
            continue;
        }

        // Check if this line is a list item
        if let Some(item) = parse_list_item(line, i) {
            let current_indent = line.len() - line.trim_start().len();

            // Determine the nesting level based on indentation
            let level = if list_stack.is_empty() {
                // First item in a list
                list_stack.push((current_indent, item.marker.clone()));
                0
            } else {
                // Find the appropriate level based on indentation
                let mut level = list_stack.len();
                for (idx, (indent, _)) in list_stack.iter().enumerate() {
                    if current_indent <= *indent {
                        level = idx;
                        break;
                    }
                }

                // Trim stack to current level
                list_stack.truncate(level);

                // If this is a new nesting level, add it
                if level == list_stack.len() {
                    list_stack.push((current_indent, item.marker.clone()));
                }

                level
            };

            // Calculate normalized indentation based on parent marker types
            let normalized_indent = required_indent_for_level(&list_stack, level);

            // Reconstruct with normalized bullet and indentation
            let reconstructed = if item.is_task && ["-", "*", "+"].contains(&item.marker.as_str()) {
                format!(
                    "{}{} [{}] {}",
                    normalized_indent,
                    target_bullet,
                    if item.checked.unwrap_or(false) {
                        "x"
                    } else {
                        " "
                    },
                    item.content
                )
            } else if ["-", "*", "+"].contains(&item.marker.as_str()) {
                format!("{}{} {}", normalized_indent, target_bullet, item.content)
            } else {
                // Ordered list - keep as is but normalize indentation
                format!("{}{}. {}", normalized_indent, item.marker, item.content)
            };
            result.push(reconstructed);
        } else {
            // Non-list line — pass through unchanged.
            // Do not clear the stack on blank lines: the stack truncates
            // naturally when the next list item appears at a lower indent.
            result.push(line.to_string());
        }
    }

    result.join("\n")
}

/// Normalize spacing between headers/paragraphs and lists.
///
/// Adds blank lines between:
/// - Headers (# ## ### etc.) and lists
/// - Paragraphs and lists
///
/// This fixes the common issue where Markdown parsers require blank lines
/// between block-level elements.
///
/// # Examples
///
/// ```
/// use ascfix::lists::normalize_loose_lists;
///
/// let content = "# My Title\n- Item 1\n- Item 2";
/// let normalized = normalize_loose_lists(content);
/// assert!(normalized.contains("# My Title\n\n- Item 1"));
/// ```
#[must_use]
#[allow(dead_code)] // Reason: Public API for list normalization, used in tests
pub fn normalize_loose_lists(content: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    if lines.is_empty() {
        return String::new();
    }

    // Get code block line ranges to skip
    let code_line_ranges = get_code_block_line_ranges(content);

    let mut result = Vec::new();

    for (i, &line) in lines.iter().enumerate() {
        // Skip lines inside code blocks
        if is_in_code_region(i, &code_line_ranges) {
            result.push(line.to_string());
            continue;
        }

        // Check if current line is a list item
        let is_list_item = parse_list_item(line, i).is_some();

        // Check if previous line was a header
        let prev_line = if i > 0 { lines.get(i - 1) } else { None };
        let prev_trimmed = prev_line.map_or("", |l| l.trim());

        // Determine if we need to insert a blank line
        let needs_blank_line = if is_list_item {
            // Check if previous line was a header (starts with #)
            let prev_was_header = prev_trimmed.starts_with('#');
            // Check if previous line was a paragraph (non-empty, not a list, not a header)
            // A line is a paragraph if it's not empty, not a header, and not a list item
            // We check for list items by using parse_list_item, which properly distinguishes
            // between actual list items and lines that just happen to start with special chars
            let prev_was_list_item = prev_line.is_some_and(|l| parse_list_item(l, i - 1).is_some());
            let prev_was_paragraph =
                !prev_trimmed.is_empty() && !prev_was_header && !prev_was_list_item;

            (prev_was_header || prev_was_paragraph)
                && !result.is_empty()
                && result.last().is_none_or(|s: &String| !s.trim().is_empty())
        } else {
            false
        };

        if needs_blank_line {
            result.push(String::new());
        }

        result.push(line.to_string());
    }

    result.join("\n")
}

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

    #[test]
    fn detect_simple_bullet_list() {
        let content = "- Item 1\n- Item 2\n- Item 3";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 1);
        assert_eq!(lists[0].items.len(), 3);
        assert_eq!(lists[0].items[0].content, "Item 1");
        assert_eq!(lists[0].items[1].content, "Item 2");
        assert_eq!(lists[0].items[2].content, "Item 3");
    }

    #[test]
    fn detect_list_with_mixed_bullets() {
        let content = "- Item 1\n* Item 2\n+ Item 3";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 1);
        assert_eq!(lists[0].items.len(), 3);
    }

    #[test]
    fn detect_ordered_list() {
        let content = "1. First item\n2. Second item\n3. Third item";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 1);
        assert_eq!(lists[0].items.len(), 3);
        assert!(lists[0].is_ordered);
    }

    #[test]
    fn detect_task_list() {
        let content = "- [ ] Buy milk\n- [x] Done item\n- [X] Also done";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 1);
        assert_eq!(lists[0].items.len(), 3);
        assert!(lists[0].items[0].is_task);
        assert!(!lists[0].items[0].checked.unwrap());
        assert!(lists[0].items[1].is_task);
        assert!(lists[0].items[1].checked.unwrap());
    }

    #[test]
    fn ignore_lists_in_code_blocks() {
        let content =
            "```markdown\n- Item in code block\n- Another item\n```\n\n- Real item outside";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 1);
        assert_eq!(lists[0].items.len(), 1);
        assert_eq!(lists[0].items[0].content, "Real item outside");
    }

    #[test]
    fn detect_multiple_lists() {
        let content = "- First list item 1\n- First list item 2\n\nSome text\n\n* Second list item 1\n* Second list item 2";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 2);
        assert_eq!(lists[0].items.len(), 2);
        assert_eq!(lists[1].items.len(), 2);
    }

    #[test]
    fn no_lists_in_plain_text() {
        let content = "This is just a paragraph.\nNo lists here.\nJust text.";
        let lists = detect_lists(content);
        assert_eq!(lists.len(), 0);
    }

    #[test]
    fn normalize_indentation_to_two_spaces() {
        // 4-space indentation should become 2-space
        let content = "- Item 1\n    - Nested item\n- Item 2";
        let normalized = normalize_list_indentation(content);
        assert!(normalized.contains("- Item 1"));
        assert!(normalized.contains("  - Nested item")); // 2 spaces
        assert!(!normalized.contains("    - Nested")); // No 4 spaces
    }

    #[test]
    fn normalize_deeply_nested_list() {
        // Mixed indentation should be normalized
        let content = "- Level 1\n    - Level 2\n        - Level 3\n- Back to 1";
        let normalized = normalize_list_indentation(content);
        assert!(normalized.contains("- Level 1"));
        assert!(normalized.contains("  - Level 2")); // 2 spaces
        assert!(normalized.contains("    - Level 3")); // 4 spaces (2 per level)
    }

    #[test]
    fn preserve_content_when_normalizing() {
        // Content should remain unchanged, only indentation fixed
        let content = "- First item with text\n    - Second item with more text";
        let normalized = normalize_list_indentation(content);
        assert!(normalized.contains("First item with text"));
        assert!(normalized.contains("Second item with more text"));
    }

    #[test]
    fn no_change_to_already_normalized() {
        // Already 2-space indented lists should remain unchanged
        let content = "- Item 1\n  - Nested\n  - Another nested\n- Item 2";
        let normalized = normalize_list_indentation(content);
        assert_eq!(normalized, content);
    }

    #[test]
    fn normalize_mixed_indentation_styles() {
        // Mixed 2-space and 4-space should become all 2-space relative
        let content = "- Item 1\n  - Two space\n    - Four space (should be 4)\n- Item 2";
        let normalized = normalize_list_indentation(content);
        assert!(normalized.contains("- Item 1"));
        assert!(normalized.contains("  - Two space"));
        assert!(normalized.contains("    - Four space")); // 4 spaces is correct for 2nd level
    }

    #[test]
    fn normalize_bullet_styles_to_dash() {
        // Mixed bullet styles should become dashes
        let content = "- Item 1\n* Item 2\n+ Item 3";
        let normalized = normalize_bullet_styles(content, '-');
        assert!(normalized.contains("- Item 1"));
        assert!(normalized.contains("- Item 2"));
        assert!(normalized.contains("- Item 3"));
        assert!(!normalized.contains("* Item"));
        assert!(!normalized.contains("+ Item"));
    }

    #[test]
    fn normalize_bullet_styles_to_asterisk() {
        // Can normalize to any bullet style
        let content = "- Item 1\n* Item 2\n+ Item 3";
        let normalized = normalize_bullet_styles(content, '*');
        assert!(normalized.contains("* Item 1"));
        assert!(normalized.contains("* Item 2"));
        assert!(normalized.contains("* Item 3"));
    }

    #[test]
    fn bullet_normalization_preserves_indentation() {
        // Bullet style change should not affect indentation
        let content = "- Item 1\n  * Nested\n    + Deep";
        let normalized = normalize_bullet_styles(content, '-');
        assert!(normalized.contains("- Item 1"));
        assert!(normalized.contains("  - Nested"));
        assert!(normalized.contains("    - Deep"));
    }

    #[test]
    fn bullet_normalization_preserves_task_lists() {
        // Task list syntax should be preserved
        let content = "- [ ] Task\n* [x] Done\n+ [ ] Another";
        let normalized = normalize_bullet_styles(content, '-');
        assert!(normalized.contains("- [ ] Task"));
        assert!(normalized.contains("- [x] Done"));
        assert!(normalized.contains("- [ ] Another"));
    }

    #[test]
    fn bullet_normalization_preserves_ordered_lists() {
        // Ordered lists should not be affected
        let content = "1. First\n2. Second\n- Unordered";
        let normalized = normalize_bullet_styles(content, '-');
        assert!(normalized.contains("1. First"));
        assert!(normalized.contains("2. Second"));
        assert!(normalized.contains("- Unordered"));
    }

    #[test]
    fn normalize_complex_nested_list() {
        // Mixed nesting with different bullets should normalize correctly
        let content = "- Level 1\n  * Level 2\n    + Level 3\n- Back to 1";
        let normalized = normalize_lists(content);
        // All should use consistent bullet and indentation
        assert!(normalized.contains("- Level 1"));
        assert!(normalized.contains("  - Level 2"));
        assert!(normalized.contains("    - Level 3"));
        assert!(normalized.contains("- Back to 1"));
    }

    #[test]
    fn normalize_deeply_nested_structure() {
        // 4 levels deep
        let content = "- A\n  - B\n    - C\n      - D\n- E";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- A"));
        assert!(normalized.contains("  - B"));
        assert!(normalized.contains("    - C"));
        assert!(normalized.contains("      - D"));
        assert!(normalized.contains("- E"));
    }

    #[test]
    fn normalize_nested_with_inconsistent_indentation() {
        // Mix of 2-space and 4-space nesting should become consistent 2-space
        let content = "- Item 1\n    - Nested with 4\n      - Deeper\n- Item 2";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- Item 1"));
        assert!(normalized.contains("  - Nested with 4")); // Now 2-space
        assert!(normalized.contains("    - Deeper")); // 4-space (2nd level)
        assert!(normalized.contains("- Item 2"));
    }

    #[test]
    fn separate_adjacent_lists() {
        // Two separate lists should not affect each other
        let content =
            "- First list A\n- First list B\n\nSome text\n\n* Second list A\n* Second list B";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- First list A"));
        assert!(normalized.contains("- First list B"));
        assert!(normalized.contains("- Second list A")); // Normalized to -
        assert!(normalized.contains("- Second list B"));
    }

    #[test]
    fn preserve_task_list_checkboxes() {
        // Task list checkboxes should be preserved during normalization
        // Note: We normalize both [x] and [X] to [x] for consistency
        let content = "- [ ] Unchecked task\n- [x] Checked task\n- [X] Also checked";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- [ ] Unchecked task"));
        assert!(normalized.contains("- [x] Checked task"));
        assert!(normalized.contains("- [x] Also checked")); // [X] normalized to [x]
    }

    #[test]
    fn normalize_mixed_task_and_regular() {
        // Mix of task and regular list items
        let content = "- [ ] Buy milk\n- Regular item\n- [x] Done item";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- [ ] Buy milk"));
        assert!(normalized.contains("- Regular item"));
        assert!(normalized.contains("- [x] Done item"));
    }

    #[test]
    fn nested_task_lists() {
        // Task lists can be nested
        let content =
            "- [ ] Parent task\n  - [ ] Subtask 1\n  - [x] Subtask 2\n- [ ] Another parent";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- [ ] Parent task"));
        assert!(normalized.contains("  - [ ] Subtask 1"));
        assert!(normalized.contains("  - [x] Subtask 2"));
        assert!(normalized.contains("- [ ] Another parent"));
    }

    #[test]
    fn task_list_with_bullet_normalization() {
        // Task lists should normalize bullet style too
        let content = "- [ ] Task 1\n* [ ] Task 2\n+ [x] Done";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- [ ] Task 1"));
        assert!(normalized.contains("- [ ] Task 2")); // * changed to -
        assert!(normalized.contains("- [x] Done")); // + changed to -
    }

    #[test]
    fn task_lists_in_code_blocks_preserved() {
        // Task lists in code blocks should not be normalized
        let content =
            "```markdown\n- [ ] In code block\n- [x] Also in block\n```\n\n- [ ] Real task outside";
        let normalized = normalize_lists(content);
        assert!(normalized.contains("- [ ] In code block")); // Preserved as-is
        assert!(normalized.contains("- [ ] Real task outside"));
    }

    #[test]
    fn add_blank_line_between_header_and_list() {
        // Headers immediately followed by lists should have blank line added
        let content = "# My Title\n- Item 1\n- Item 2";
        let normalized = normalize_loose_lists(content);
        assert!(normalized.contains("# My Title\n\n- Item 1"));
    }

    #[test]
    fn add_blank_line_between_paragraph_and_list() {
        // Paragraphs immediately followed by lists should have blank line added
        let content = "Some paragraph text\n- Item 1\n- Item 2";
        let normalized = normalize_loose_lists(content);
        assert!(normalized.contains("Some paragraph text\n\n- Item 1"));
    }

    #[test]
    fn preserve_existing_blank_lines() {
        // Content that already has proper spacing should not change
        let content = "# Title\n\n- Item 1\n\nSome text\n\n- Item 2";
        let normalized = normalize_loose_lists(content);
        assert_eq!(normalized, content);
    }

    #[test]
    fn handle_loose_lists_with_paragraphs() {
        // Lists with blank lines between items (loose lists) should be preserved
        let content = "- Item 1\n\n  Paragraph text\n\n- Item 2";
        let normalized = normalize_loose_lists(content);
        assert!(normalized.contains("- Item 1\n\n  Paragraph text\n\n- Item 2"));
    }

    #[test]
    fn multiple_headers_need_spacing() {
        // Multiple headers followed by lists
        let content = "# Header 1\n- Item A\n# Header 2\n- Item B";
        let normalized = normalize_loose_lists(content);
        assert!(normalized.contains("# Header 1\n\n- Item A"));
        assert!(normalized.contains("# Header 2\n\n- Item B"));
    }

    // Regression tests for issue #10: ordered list continuation indentation

    #[test]
    fn ordered_list_child_bullet_preserves_three_space_indent() {
        // Sub-items of "1. " must stay at >=3 spaces to remain `CommonMark`-valid
        // continuations. ascfix must not reduce 3 spaces to 2.
        let content = "1. **First item**\n   - sub-item a\n   - sub-item b";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("   - sub-item a"),
            "Sub-item must keep 3-space indent under ordered parent. Got:\n{normalized}"
        );
        assert!(
            normalized.contains("   - sub-item b"),
            "Sub-item must keep 3-space indent under ordered parent. Got:\n{normalized}"
        );
        // Verify no line has exactly 2-space indent (i.e. "\n  - " not followed by a 3rd space)
        assert!(
            !normalized.contains("\n  - sub-item"),
            "2-space indent must not appear under ordered parent. Got:\n{normalized}"
        );
    }

    #[test]
    fn ordered_list_multi_item_children_preserve_indent() {
        // Full reproduction case from the bug report
        let content = "1. **Assess Current Stack**\n   - What are you using now?\n   - How complex is your API?\n\n2. **Second item**\n   - sub-item c";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("   - What are you using now?"),
            "3-space indent must be preserved. Got:\n{normalized}"
        );
        assert!(
            normalized.contains("   - sub-item c"),
            "3-space indent must be preserved. Got:\n{normalized}"
        );
    }

    #[test]
    fn unordered_list_children_still_use_two_spaces() {
        // Bullet sub-lists must still normalize to 2 spaces (existing behavior)
        let content = "- Item 1\n    - Nested with 4 spaces\n- Item 2";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("  - Nested with 4 spaces"),
            "Bullet sub-item should normalize to 2 spaces. Got:\n{normalized}"
        );
        assert!(
            !normalized.contains("    - Nested"),
            "4-space indent should be reduced. Got:\n{normalized}"
        );
    }

    #[test]
    fn double_digit_ordered_list_child_uses_four_space_indent() {
        // "10. " is 4 chars wide so continuation needs >=4 spaces
        let content = "10. **Item ten**\n    - sub-item";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("    - sub-item"),
            "Sub-item under '10.' must have 4-space indent. Got:\n{normalized}"
        );
    }

    #[test]
    fn required_indent_helper_unordered_parent() {
        // Level 1 under a "-" parent = 2 spaces
        let stack = vec![(0usize, "-".to_string())];
        assert_eq!(required_indent_for_level(&stack, 1), "  ");
    }

    #[test]
    fn required_indent_helper_ordered_parent() {
        // Level 1 under a "1" parent = 3 spaces ("1" + ". " = 1+2)
        let stack = vec![(0usize, "1".to_string())];
        assert_eq!(required_indent_for_level(&stack, 1), "   ");
    }

    #[test]
    fn required_indent_helper_double_digit_ordered() {
        // Level 1 under a "10" parent = 4 spaces ("10" + ". " = 2+2)
        let stack = vec![(0usize, "10".to_string())];
        assert_eq!(required_indent_for_level(&stack, 1), "    ");
    }

    #[test]
    fn required_indent_helper_nested_ordered_then_unordered() {
        // Level 2: ordered "1" (3) then unordered "-" (2) = 5 spaces
        let stack = vec![(0usize, "1".to_string()), (3usize, "-".to_string())];
        assert_eq!(required_indent_for_level(&stack, 2), "     ");
    }

    #[test]
    fn ordered_list_child_after_blank_line_preserves_indent() {
        // Exact reproduction from issue #10 comment: blank line between ordered
        // item and its sub-items must not strip the sub-items' indentation.
        let content = "1. **Assess Current Stack**\n\n   - What are you using now?\n   - How complex is your API?";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("   - What are you using now?"),
            "3-space indent must survive blank line before sub-item. Got:\n{normalized}"
        );
        assert!(
            normalized.contains("   - How complex is your API?"),
            "3-space indent must survive blank line before sub-item. Got:\n{normalized}"
        );
        assert!(
            !normalized.contains("\n- What are you using now?"),
            "Sub-item must not be at column 0 after blank line. Got:\n{normalized}"
        );
    }

    #[test]
    fn ordered_list_multiple_items_with_blank_line_children() {
        // Full multi-item case from the issue report
        let content = "1. **Assess Current Stack**\n\n   - What are you using now?\n   - How complex is your API?\n\n2. **Second item**\n\n   - sub-item c";
        let normalized = normalize_lists(content);
        assert!(
            normalized.contains("   - What are you using now?"),
            "Children of item 1 must keep 3-space indent. Got:\n{normalized}"
        );
        assert!(
            normalized.contains("   - sub-item c"),
            "Children of item 2 must keep 3-space indent. Got:\n{normalized}"
        );
    }

    #[test]
    fn unordered_lists_separated_by_blank_still_independent() {
        // Two separate bullet lists separated by text must not bleed into each other
        let content = "- List A item 1\n- List A item 2\n\nSome paragraph\n\n- List B item 1\n- List B item 2";
        let normalized = normalize_lists(content);
        // Both lists should be at column 0
        assert!(normalized.contains("- List A item 1"));
        assert!(normalized.contains("- List B item 1"));
        // No stray indentation
        assert!(!normalized.contains("  - List B item 1"));
    }
}