copybook-codec 0.4.3

Deterministic COBOL copybook codec for EBCDIC/ASCII fixed and RDW records.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Edited PIC (Phase E2 + E3) decode and encode support
//!
//! This module implements decode and encode for edited numeric PICTURE clauses following IBM COBOL specifications.
//! Edited PICs include formatting symbols like Z (zero suppression), $ (currency), comma, decimal point,
//! B (blank space insertion), and sign editing (+, -, CR, DB).
//!
//! The decode algorithm walks the input string and PIC pattern in lockstep, extracting numeric digits
//! and validating formatting symbols. The encode algorithm formats numeric values according to the pattern.

use copybook_core::{Error, ErrorCode, Result};
use tracing::warn;

/// Pattern tokens for edited PIC clauses.
///
/// Each variant represents a formatting symbol in an edited PICTURE clause,
/// used during decode and encode of edited numeric fields.
#[derive(Debug, Clone, PartialEq)]
pub enum PicToken {
    /// Numeric digit (9) - always displays
    Digit,
    /// Zero suppression (Z) - displays space if leading zero
    ZeroSuppress,
    /// Zero insert (0) - always displays '0'
    ZeroInsert,
    /// Asterisk fill (*) - displays '*' for leading zeros
    AsteriskFill,
    /// Blank space (B)
    Space,
    /// Literal comma
    Comma,
    /// Literal slash
    Slash,
    /// Decimal point
    DecimalPoint,
    /// Currency symbol ($)
    Currency,
    /// Leading plus sign
    LeadingPlus,
    /// Leading minus sign
    LeadingMinus,
    /// Trailing plus sign
    TrailingPlus,
    /// Trailing minus sign
    TrailingMinus,
    /// Credit (CR) - two characters
    Credit,
    /// Debit (DB) - two characters
    Debit,
}

impl std::fmt::Display for PicToken {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Digit => write!(f, "9"),
            Self::ZeroSuppress => write!(f, "Z"),
            Self::ZeroInsert => write!(f, "0"),
            Self::AsteriskFill => write!(f, "*"),
            Self::Space => write!(f, "B"),
            Self::Comma => write!(f, ","),
            Self::Slash => write!(f, "/"),
            Self::DecimalPoint => write!(f, "."),
            Self::Currency => write!(f, "$"),
            Self::LeadingPlus | Self::TrailingPlus => write!(f, "+"),
            Self::LeadingMinus | Self::TrailingMinus => write!(f, "-"),
            Self::Credit => write!(f, "CR"),
            Self::Debit => write!(f, "DB"),
        }
    }
}

/// Sign extracted from an edited PIC field during decode.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Sign {
    /// Positive or unsigned value.
    Positive,
    /// Negative value.
    Negative,
}

/// Tokenize an edited PIC pattern into tokens
///
/// # Errors
/// Returns error if the PIC pattern is malformed
#[inline]
#[allow(clippy::too_many_lines)]
pub fn tokenize_edited_pic(pic_str: &str) -> Result<Vec<PicToken>> {
    let mut tokens = Vec::new();
    let mut chars = pic_str.chars().peekable();
    let mut found_decimal = false;

    // Skip leading 'S' if present (sign is handled separately via sign editing symbols)
    if chars.peek() == Some(&'S') || chars.peek() == Some(&'s') {
        chars.next();
    }

    while let Some(ch) = chars.next() {
        match ch.to_ascii_uppercase() {
            '9' => {
                let count = parse_repetition(&mut chars)?;
                for _ in 0..count {
                    tokens.push(PicToken::Digit);
                }
            }
            'Z' => {
                let count = parse_repetition(&mut chars)?;
                for _ in 0..count {
                    tokens.push(PicToken::ZeroSuppress);
                }
            }
            '0' => {
                let count = parse_repetition(&mut chars)?;
                for _ in 0..count {
                    tokens.push(PicToken::ZeroInsert);
                }
            }
            '*' => {
                let count = parse_repetition(&mut chars)?;
                for _ in 0..count {
                    tokens.push(PicToken::AsteriskFill);
                }
            }
            'B' => {
                let count = parse_repetition(&mut chars)?;
                for _ in 0..count {
                    tokens.push(PicToken::Space);
                }
            }
            ',' => tokens.push(PicToken::Comma),
            '/' => tokens.push(PicToken::Slash),
            '.' => {
                if found_decimal {
                    return Err(Error::new(
                        ErrorCode::CBKP001_SYNTAX,
                        format!("Multiple decimal points in edited PIC: {pic_str}"),
                    ));
                }
                found_decimal = true;
                tokens.push(PicToken::DecimalPoint);
            }
            '$' => tokens.push(PicToken::Currency),
            '+' => {
                // Check if at beginning (leading) or end (trailing)
                if tokens.is_empty() {
                    tokens.push(PicToken::LeadingPlus);
                } else {
                    tokens.push(PicToken::TrailingPlus);
                }
            }
            '-' => {
                // Check if at beginning (leading) or end (trailing)
                if tokens.is_empty() {
                    tokens.push(PicToken::LeadingMinus);
                } else {
                    tokens.push(PicToken::TrailingMinus);
                }
            }
            'C' => {
                // Check for CR
                if let Some(&next_ch) = chars.peek()
                    && (next_ch == 'R' || next_ch == 'r')
                {
                    chars.next(); // consume 'R'
                    tokens.push(PicToken::Credit);
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKP001_SYNTAX,
                        format!("Invalid character 'C' in edited PIC: {pic_str}"),
                    ));
                }
            }
            'D' => {
                // Check for DB
                if let Some(&next_ch) = chars.peek()
                    && (next_ch == 'B' || next_ch == 'b')
                {
                    chars.next(); // consume 'B'
                    tokens.push(PicToken::Debit);
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKP001_SYNTAX,
                        format!("Invalid character 'D' in edited PIC: {pic_str}"),
                    ));
                }
            }
            _ => {
                // Skip implicit decimal point markers (V), whitespace, or unknown characters
            }
        }
    }

    if tokens.is_empty() {
        return Err(Error::new(
            ErrorCode::CBKP001_SYNTAX,
            format!("Empty or invalid edited PIC pattern: {pic_str}"),
        ));
    }

    Ok(tokens)
}

/// Parse repetition count from chars like (5)
fn parse_repetition<I>(chars: &mut std::iter::Peekable<I>) -> Result<usize>
where
    I: Iterator<Item = char>,
{
    if chars.peek() == Some(&'(') {
        chars.next(); // consume '('
        let mut count_str = String::new();
        while let Some(&ch) = chars.peek() {
            if ch == ')' {
                chars.next(); // consume ')'
                break;
            } else if ch.is_ascii_digit() {
                count_str.push(ch);
                chars.next();
            } else {
                return Err(Error::new(
                    ErrorCode::CBKP001_SYNTAX,
                    format!("Invalid repetition count: {count_str}"),
                ));
            }
        }
        count_str.parse::<usize>().map_err(|_| {
            Error::new(
                ErrorCode::CBKP001_SYNTAX,
                format!("Invalid repetition count: {count_str}"),
            )
        })
    } else {
        Ok(1)
    }
}

/// Decoded numeric value extracted from an edited PIC field.
///
/// Contains the sign, raw digit string, and scale needed to
/// produce a JSON numeric representation.
#[derive(Debug, Clone, PartialEq)]
pub struct NumericValue {
    /// Sign of the number
    pub sign: Sign,
    /// Digits without decimal point (e.g., "12345" for 123.45 with scale=2)
    pub digits: String,
    /// Number of decimal places
    pub scale: u16,
}

impl NumericValue {
    /// Format as decimal string for JSON output
    #[must_use]
    #[inline]
    pub fn to_decimal_string(&self) -> String {
        if self.digits.is_empty() || self.digits.chars().all(|c| c == '0') {
            return "0".to_string();
        }

        let sign_prefix = match self.sign {
            Sign::Positive => "",
            Sign::Negative => "-",
        };

        if self.scale == 0 {
            // Integer - just return digits with sign
            format!("{sign_prefix}{}", self.digits)
        } else {
            // Decimal - insert decimal point
            let scale = self.scale as usize;
            let digits_len = self.digits.len();

            if scale >= digits_len {
                // Need leading zeros (e.g., 0.0123)
                let zeros = "0".repeat(scale - digits_len);
                format!("{sign_prefix}0.{zeros}{}", self.digits)
            } else {
                // Split at decimal point
                let (int_part, frac_part) = self.digits.split_at(digits_len - scale);
                if int_part.is_empty() {
                    format!("{sign_prefix}0.{frac_part}")
                } else {
                    format!("{sign_prefix}{int_part}.{frac_part}")
                }
            }
        }
    }
}

/// Decode edited numeric string according to PICTURE pattern
///
/// # Errors
/// Returns error if the input doesn't match the pattern
#[inline]
#[allow(clippy::too_many_lines)]
pub fn decode_edited_numeric(
    input: &str,
    pattern: &[PicToken],
    scale: u16,
    blank_when_zero: bool,
) -> Result<NumericValue> {
    // Check for BLANK WHEN ZERO
    if blank_when_zero && input.chars().all(|c| c == ' ') {
        warn!("CBKD423_EDITED_PIC_BLANK_WHEN_ZERO: Edited PIC field is blank, decoding as zero");
        crate::lib_api::increment_warning_counter();
        return Ok(NumericValue {
            sign: Sign::Positive,
            digits: "0".to_string(),
            scale,
        });
    }

    let input_chars: Vec<char> = input.chars().collect();
    let mut pattern_idx = 0;
    let mut input_idx = 0;
    let mut digits = String::new();
    let mut sign = Sign::Positive;
    let mut found_non_zero = false;

    // Extract sign from pattern and input
    while pattern_idx < pattern.len() {
        let token = &pattern[pattern_idx];

        if input_idx >= input_chars.len() {
            return Err(Error::new(
                ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                format!(
                    "Input too short for edited PIC pattern (expected {} characters, got {})",
                    pattern.len(),
                    input.len()
                ),
            ));
        }

        let input_char = input_chars[input_idx];

        match token {
            PicToken::Digit
            | PicToken::ZeroSuppress
            | PicToken::ZeroInsert
            | PicToken::AsteriskFill => {
                // Expect digit or space or asterisk
                if input_char.is_ascii_digit() {
                    let digit_val = input_char;
                    if digit_val != '0' {
                        found_non_zero = true;
                    }
                    if found_non_zero || matches!(token, PicToken::Digit | PicToken::ZeroInsert) {
                        digits.push(digit_val);
                    } else {
                        // Leading zero suppression - push 0 to maintain position
                        digits.push('0');
                    }
                } else if input_char == ' ' {
                    // Space for zero suppression
                    if matches!(token, PicToken::Digit) {
                        // Required digit position cannot be space
                        return Err(Error::new(
                            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                            format!("Expected digit but found space at position {input_idx}"),
                        ));
                    }
                    digits.push('0');
                } else if input_char == '*' {
                    // Asterisk fill for check protection
                    if !matches!(token, PicToken::AsteriskFill) {
                        return Err(Error::new(
                            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                            format!("Unexpected asterisk at position {input_idx}"),
                        ));
                    }
                    digits.push('0');
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!(
                            "Expected digit, space, or asterisk but found '{input_char}' at position {input_idx}"
                        ),
                    ));
                }
                input_idx += 1;
            }
            PicToken::Space => {
                if input_char != ' ' && input_char != 'B' {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!("Expected space but found '{input_char}' at position {input_idx}"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::Comma => {
                if input_char != ',' {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!("Expected comma but found '{input_char}' at position {input_idx}"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::Slash => {
                if input_char != '/' {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!("Expected slash but found '{input_char}' at position {input_idx}"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::DecimalPoint => {
                if input_char != '.' {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!(
                            "Expected decimal point but found '{input_char}' at position {input_idx}"
                        ),
                    ));
                }
                input_idx += 1;
            }
            PicToken::Currency => {
                if input_char != '$' && input_char != ' ' {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        format!(
                            "Expected currency symbol but found '{input_char}' at position {input_idx}"
                        ),
                    ));
                }
                input_idx += 1;
            }
            PicToken::LeadingPlus => {
                if input_char == '+' || input_char == ' ' {
                    sign = Sign::Positive;
                } else if input_char == '-' {
                    sign = Sign::Negative;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected '+' or '-' for leading plus but found '{input_char}'"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::LeadingMinus => {
                if input_char == '-' {
                    sign = Sign::Negative;
                } else if input_char == ' ' {
                    sign = Sign::Positive;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected '-' for leading minus but found '{input_char}'"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::TrailingPlus => {
                if input_char == '+' || input_char == ' ' {
                    sign = Sign::Positive;
                } else if input_char == '-' {
                    sign = Sign::Negative;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected '+' or '-' for trailing plus but found '{input_char}'"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::TrailingMinus => {
                if input_char == '-' {
                    sign = Sign::Negative;
                } else if input_char == ' ' {
                    sign = Sign::Positive;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected '-' for trailing minus but found '{input_char}'"),
                    ));
                }
                input_idx += 1;
            }
            PicToken::Credit => {
                // CR requires two characters
                if input_idx + 1 >= input_chars.len() {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        "Input too short for CR symbol".to_string(),
                    ));
                }
                let cr_str: String = input_chars[input_idx..input_idx + 2].iter().collect();
                if cr_str == "CR" {
                    sign = Sign::Negative;
                } else if cr_str == "  " {
                    sign = Sign::Positive;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected 'CR' or spaces but found '{cr_str}'"),
                    ));
                }
                input_idx += 2;
            }
            PicToken::Debit => {
                // DB requires two characters
                if input_idx + 1 >= input_chars.len() {
                    return Err(Error::new(
                        ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                        "Input too short for DB symbol".to_string(),
                    ));
                }
                let db_str: String = input_chars[input_idx..input_idx + 2].iter().collect();
                if db_str == "DB" {
                    sign = Sign::Negative;
                } else if db_str == "  " {
                    sign = Sign::Positive;
                } else {
                    return Err(Error::new(
                        ErrorCode::CBKD422_EDITED_PIC_SIGN_MISMATCH,
                        format!("Expected 'DB' or spaces but found '{db_str}'"),
                    ));
                }
                input_idx += 2;
            }
        }

        pattern_idx += 1;
    }

    // Check if we consumed all input
    if input_idx != input_chars.len() {
        return Err(Error::new(
            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
            format!(
                "Input longer than expected (pattern consumed {} chars, input has {} chars)",
                input_idx,
                input_chars.len()
            ),
        ));
    }

    // Clean up digits - remove leading zeros but preserve at least one digit
    let digits = digits.trim_start_matches('0');
    let digits = if digits.is_empty() {
        "0".to_string()
    } else {
        digits.to_string()
    };

    // If all zeros, force positive sign
    if digits == "0" {
        sign = Sign::Positive;
    }

    Ok(NumericValue {
        sign,
        digits,
        scale,
    })
}

/// Parsed numeric value for encoding
#[derive(Debug, Clone)]
struct ParsedNumeric {
    /// Sign of the number
    sign: Sign,
    /// All digits without decimal point (e.g., "12345" for 123.45)
    digits: Vec<u8>,
    /// Position of decimal point from right (0 for integers, 2 for 2 decimal places)
    decimal_places: usize,
}

/// Parse a numeric string into its components for encoding
fn parse_numeric_value(value: &str) -> Result<ParsedNumeric> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(Error::new(
            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
            "Empty numeric value",
        ));
    }

    let mut chars = trimmed.chars().peekable();
    let sign = if chars.peek() == Some(&'-') {
        chars.next();
        Sign::Negative
    } else if chars.peek() == Some(&'+') {
        chars.next();
        Sign::Positive
    } else {
        Sign::Positive
    };

    let mut digits = Vec::new();
    let mut found_decimal = false;
    let mut decimal_places = 0;
    let mut found_digit = false;

    for ch in chars {
        if ch.is_ascii_digit() {
            digits.push(ch as u8 - b'0');
            if found_decimal {
                decimal_places += 1;
            }
            found_digit = true;
        } else if ch == '.' {
            if found_decimal {
                return Err(Error::new(
                    ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                    format!("Multiple decimal points in value: {value}"),
                ));
            }
            found_decimal = true;
        } else {
            return Err(Error::new(
                ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
                format!("Invalid character '{ch}' in numeric value: {value}"),
            ));
        }
    }

    if !found_digit {
        return Err(Error::new(
            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
            format!("No digits found in value: {value}"),
        ));
    }

    Ok(ParsedNumeric {
        sign,
        digits,
        decimal_places,
    })
}

/// Encode a numeric value to an edited PIC string
///
/// # Errors
/// Returns error if the value cannot be encoded to the pattern
#[inline]
#[allow(clippy::too_many_lines)]
pub fn encode_edited_numeric(
    value: &str,
    pattern: &[PicToken],
    scale: u16,
    _blank_when_zero: bool,
) -> Result<String> {
    // Parse the input value
    let parsed = parse_numeric_value(value)?;

    // All tokens are now supported in E3.7 (including Space)
    // No unsupported token check needed

    // Check if value is all zeros (force positive sign)
    let is_zero = parsed.digits.iter().all(|&d| d == 0);
    let effective_sign = if is_zero { Sign::Positive } else { parsed.sign };

    // Count numeric positions and decimal point in pattern
    let mut has_decimal = false;
    for token in pattern {
        if *token == PicToken::DecimalPoint {
            has_decimal = true;
        }
    }

    // Calculate expected decimal places from pattern
    let _pattern_decimal_places = if has_decimal {
        // Count numeric positions after decimal point
        let mut after_decimal = 0;
        let mut found = false;
        for token in pattern {
            if *token == PicToken::DecimalPoint {
                found = true;
            } else if found
                && matches!(
                    token,
                    PicToken::Digit | PicToken::ZeroSuppress | PicToken::ZeroInsert
                )
            {
                after_decimal += 1;
            }
        }
        after_decimal
    } else {
        0
    };

    // Adjust digits to match pattern scale
    let scale = scale as usize;
    let mut adjusted_digits = parsed.digits.clone();

    // Pad or truncate to match scale
    if scale > parsed.decimal_places {
        // Need to add trailing zeros
        let to_add = scale - parsed.decimal_places;
        adjusted_digits.extend(std::iter::repeat_n(0, to_add));
    } else if scale < parsed.decimal_places {
        // Need to truncate (round down for now)
        let to_remove = parsed.decimal_places - scale;
        for _ in 0..to_remove {
            adjusted_digits.pop();
        }
    }

    // Calculate integer and fractional parts
    let decimal_places = scale;
    let total_digits = adjusted_digits.len();
    let int_digits = total_digits.saturating_sub(decimal_places);

    // Count integer and fractional positions in pattern
    let mut int_positions = 0;
    let mut frac_positions = 0;
    let mut after_decimal = false;
    for token in pattern {
        match token {
            PicToken::Digit
            | PicToken::ZeroSuppress
            | PicToken::ZeroInsert
            | PicToken::AsteriskFill => {
                if after_decimal {
                    frac_positions += 1;
                } else {
                    int_positions += 1;
                }
            }
            PicToken::DecimalPoint => {
                after_decimal = true;
            }
            _ => {}
        }
    }

    // Check if value fits in pattern
    if int_digits > int_positions || decimal_places > frac_positions {
        return Err(Error::new(
            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT,
            format!(
                "Value too long for pattern (pattern has {int_positions} integer positions, value has {int_digits} digits)"
            ),
        ));
    }

    // Calculate output length (CR and DB are 2 characters each, others are 1)
    let output_len: usize = pattern
        .iter()
        .map(|token| match token {
            PicToken::Credit | PicToken::Debit => 2,
            _ => 1,
        })
        .sum();

    // Build output string by filling from right to left
    let mut result: Vec<char> = vec![' '; output_len];
    let mut int_digit_idx = int_digits; // Start from the end
    let mut frac_digit_idx = decimal_places; // Start from the end

    // Fill from right to left
    // We need to track character position separately from token index
    let mut char_pos = output_len;
    for (token_idx, token) in pattern.iter().enumerate().rev() {
        // Determine how many characters this token occupies
        let token_width = match token {
            PicToken::Credit | PicToken::Debit => 2,
            _ => 1,
        };
        char_pos -= token_width;

        match token {
            PicToken::Digit => {
                let digit = {
                    // Check if this position is before or after decimal
                    let is_after_decimal = pattern[..token_idx].contains(&PicToken::DecimalPoint);
                    if is_after_decimal && frac_digit_idx > 0 {
                        frac_digit_idx -= 1;
                        char::from_digit(
                            u32::from(adjusted_digits[int_digits + frac_digit_idx]),
                            10,
                        )
                        .unwrap_or('0')
                    } else if !is_after_decimal && int_digit_idx > 0 {
                        int_digit_idx -= 1;
                        char::from_digit(u32::from(adjusted_digits[int_digit_idx]), 10)
                            .unwrap_or('0')
                    } else {
                        '0'
                    }
                };
                result[char_pos] = digit;
            }
            PicToken::ZeroSuppress => {
                let is_after_decimal = pattern[..token_idx].contains(&PicToken::DecimalPoint);
                if is_after_decimal && frac_digit_idx > 0 {
                    frac_digit_idx -= 1;
                    let d = adjusted_digits[int_digits + frac_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else if !is_after_decimal && int_digit_idx > 0 {
                    int_digit_idx -= 1;
                    let d = adjusted_digits[int_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else {
                    result[char_pos] = ' ';
                }
            }
            PicToken::ZeroInsert => {
                let is_after_decimal = pattern[..token_idx].contains(&PicToken::DecimalPoint);
                if is_after_decimal && frac_digit_idx > 0 {
                    frac_digit_idx -= 1;
                    let d = adjusted_digits[int_digits + frac_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else if !is_after_decimal && int_digit_idx > 0 {
                    int_digit_idx -= 1;
                    let d = adjusted_digits[int_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else {
                    result[char_pos] = '0';
                }
            }
            PicToken::AsteriskFill => {
                let is_after_decimal = pattern[..token_idx].contains(&PicToken::DecimalPoint);
                if is_after_decimal && frac_digit_idx > 0 {
                    frac_digit_idx -= 1;
                    let d = adjusted_digits[int_digits + frac_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else if !is_after_decimal && int_digit_idx > 0 {
                    int_digit_idx -= 1;
                    let d = adjusted_digits[int_digit_idx];
                    result[char_pos] = char::from_digit(u32::from(d), 10).unwrap_or('0');
                } else {
                    result[char_pos] = '*';
                }
            }
            PicToken::DecimalPoint => {
                result[char_pos] = '.';
            }
            PicToken::Comma => {
                // Commas are always displayed, but become spaces during zero suppression
                // Check if there are any significant digits to the right (already filled)
                // or if the value is not zero
                let has_significant_right = result[char_pos + 1..]
                    .iter()
                    .any(|&ch| ch != ' ' && ch != '0' && ch != ',' && ch != '.');
                result[char_pos] = if !is_zero || has_significant_right {
                    ','
                } else {
                    ' '
                };
            }
            PicToken::Slash => {
                // Slashes are always displayed (date format use case)
                result[char_pos] = '/';
            }
            PicToken::Currency => {
                // Currency symbol ($) is always displayed at its pattern position
                result[char_pos] = '$';
            }
            PicToken::LeadingPlus | PicToken::TrailingPlus => {
                result[char_pos] = match effective_sign {
                    Sign::Positive => '+',
                    Sign::Negative => '-',
                };
            }
            PicToken::LeadingMinus | PicToken::TrailingMinus => {
                result[char_pos] = match effective_sign {
                    Sign::Positive => ' ',
                    Sign::Negative => '-',
                };
            }
            PicToken::Credit => {
                // CR occupies 2 characters: "CR" for negative, "  " for positive
                match effective_sign {
                    Sign::Positive => {
                        result[char_pos] = ' ';
                        result[char_pos + 1] = ' ';
                    }
                    Sign::Negative => {
                        result[char_pos] = 'C';
                        result[char_pos + 1] = 'R';
                    }
                }
            }
            PicToken::Debit => {
                // DB occupies 2 characters: "DB" for negative, "  " for positive
                match effective_sign {
                    Sign::Positive => {
                        result[char_pos] = ' ';
                        result[char_pos + 1] = ' ';
                    }
                    Sign::Negative => {
                        result[char_pos] = 'D';
                        result[char_pos + 1] = 'B';
                    }
                }
            }
            PicToken::Space => {
                // B token always inserts a literal space character
                result[char_pos] = ' ';
            }
        }
    }

    Ok(result.into_iter().collect())
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_tokenize_simple_z() {
        let tokens = tokenize_edited_pic("ZZZ9").unwrap();
        assert_eq!(
            tokens,
            vec![
                PicToken::ZeroSuppress,
                PicToken::ZeroSuppress,
                PicToken::ZeroSuppress,
                PicToken::Digit
            ]
        );
    }

    #[test]
    fn test_tokenize_with_decimal() {
        let tokens = tokenize_edited_pic("ZZZ9.99").unwrap();
        assert_eq!(
            tokens,
            vec![
                PicToken::ZeroSuppress,
                PicToken::ZeroSuppress,
                PicToken::ZeroSuppress,
                PicToken::Digit,
                PicToken::DecimalPoint,
                PicToken::Digit,
                PicToken::Digit
            ]
        );
    }

    #[test]
    fn test_tokenize_currency() {
        let tokens = tokenize_edited_pic("$ZZ,ZZZ.99").unwrap();
        assert_eq!(tokens[0], PicToken::Currency);
        assert!(tokens.contains(&PicToken::Comma));
        assert!(tokens.contains(&PicToken::DecimalPoint));
    }

    #[test]
    fn test_decode_simple() {
        let pattern = tokenize_edited_pic("ZZZ9").unwrap();
        let result = decode_edited_numeric("  12", &pattern, 0, false).unwrap();
        assert_eq!(result.sign, Sign::Positive);
        assert_eq!(result.digits, "12");
        assert_eq!(result.to_decimal_string(), "12");
    }

    #[test]
    fn test_decode_with_decimal() {
        let pattern = tokenize_edited_pic("ZZZ9.99").unwrap();
        let result = decode_edited_numeric("  12.34", &pattern, 2, false).unwrap();
        assert_eq!(result.sign, Sign::Positive);
        assert_eq!(result.digits, "1234");
        assert_eq!(result.scale, 2);
        assert_eq!(result.to_decimal_string(), "12.34");
    }

    #[test]
    fn test_decode_blank_when_zero() {
        let pattern = tokenize_edited_pic("ZZZ9").unwrap();
        let result = decode_edited_numeric("    ", &pattern, 0, true).unwrap();
        assert_eq!(result.to_decimal_string(), "0");
    }

    #[test]
    fn test_decode_with_currency() {
        let pattern = tokenize_edited_pic("$ZZZ.99").unwrap();
        let result = decode_edited_numeric("$ 12.34", &pattern, 2, false).unwrap();
        assert_eq!(result.to_decimal_string(), "12.34");
    }

    #[test]
    fn test_decode_trailing_cr() {
        let pattern = tokenize_edited_pic("ZZZ9CR").unwrap();
        let result = decode_edited_numeric("  12CR", &pattern, 0, false).unwrap();
        assert_eq!(result.sign, Sign::Negative);
        assert_eq!(result.to_decimal_string(), "-12");
    }

    #[test]
    fn test_decode_trailing_db() {
        let pattern = tokenize_edited_pic("ZZZ9DB").unwrap();
        let result = decode_edited_numeric("  12DB", &pattern, 0, false).unwrap();
        assert_eq!(result.sign, Sign::Negative);
        assert_eq!(result.to_decimal_string(), "-12");
    }

    // ===== E3.1 Encode Tests =====

    #[test]
    fn test_encode_basic_digits() {
        let pattern = tokenize_edited_pic("9999").unwrap();
        let result = encode_edited_numeric("1234", &pattern, 0, false).unwrap();
        assert_eq!(result, "1234");
    }

    #[test]
    fn test_encode_zero_with_zero_insert() {
        let pattern = tokenize_edited_pic("9999").unwrap();
        let result = encode_edited_numeric("0", &pattern, 0, false).unwrap();
        assert_eq!(result, "0000");
    }

    #[test]
    fn test_encode_zero_suppression() {
        let pattern = tokenize_edited_pic("ZZZ9").unwrap();
        let result = encode_edited_numeric("123", &pattern, 0, false).unwrap();
        assert_eq!(result, " 123");
    }

    #[test]
    fn test_encode_zero_suppression_zero() {
        let pattern = tokenize_edited_pic("ZZZ9").unwrap();
        let result = encode_edited_numeric("0", &pattern, 0, false).unwrap();
        assert_eq!(result, "   0");
    }

    #[test]
    fn test_encode_zero_suppression_single_digit() {
        let pattern = tokenize_edited_pic("ZZZ9").unwrap();
        let result = encode_edited_numeric("1", &pattern, 0, false).unwrap();
        assert_eq!(result, "   1");
    }

    #[test]
    fn test_encode_zero_insert() {
        let pattern = tokenize_edited_pic("0009").unwrap();
        let result = encode_edited_numeric("123", &pattern, 0, false).unwrap();
        assert_eq!(result, "0123");
    }

    #[test]
    fn test_encode_zero_insert_all_zeros() {
        let pattern = tokenize_edited_pic("0009").unwrap();
        let result = encode_edited_numeric("0", &pattern, 0, false).unwrap();
        assert_eq!(result, "0000");
    }

    #[test]
    fn test_encode_decimal_point() {
        let pattern = tokenize_edited_pic("99.99").unwrap();
        let result = encode_edited_numeric("12.34", &pattern, 2, false).unwrap();
        assert_eq!(result, "12.34");
    }

    #[test]
    fn test_encode_zero_decimal() {
        let pattern = tokenize_edited_pic("99.99").unwrap();
        let result = encode_edited_numeric("0.00", &pattern, 2, false).unwrap();
        assert_eq!(result, "00.00");
    }

    #[test]
    fn test_encode_leading_plus_positive() {
        let pattern = tokenize_edited_pic("+999").unwrap();
        let result = encode_edited_numeric("123", &pattern, 0, false).unwrap();
        assert_eq!(result, "+123");
    }

    #[test]
    fn test_encode_leading_plus_negative() {
        let pattern = tokenize_edited_pic("+999").unwrap();
        let result = encode_edited_numeric("-123", &pattern, 0, false).unwrap();
        assert_eq!(result, "-123");
    }

    #[test]
    fn test_encode_leading_minus_positive() {
        let pattern = tokenize_edited_pic("-999").unwrap();
        let result = encode_edited_numeric("123", &pattern, 0, false).unwrap();
        assert_eq!(result, " 123");
    }

    #[test]
    fn test_encode_leading_minus_negative() {
        let pattern = tokenize_edited_pic("-999").unwrap();
        let result = encode_edited_numeric("-123", &pattern, 0, false).unwrap();
        assert_eq!(result, "-123");
    }

    #[test]
    fn test_encode_leading_plus_with_decimal() {
        let pattern = tokenize_edited_pic("+99.99").unwrap();
        let result = encode_edited_numeric("12.34", &pattern, 2, false).unwrap();
        assert_eq!(result, "+12.34");
    }

    #[test]
    fn test_encode_leading_minus_with_decimal() {
        let pattern = tokenize_edited_pic("-99.99").unwrap();
        let result = encode_edited_numeric("-12.34", &pattern, 2, false).unwrap();
        assert_eq!(result, "-12.34");
    }

    #[test]
    fn test_encode_negative_zero_forces_positive() {
        let pattern = tokenize_edited_pic("-999").unwrap();
        let result = encode_edited_numeric("-0", &pattern, 0, false).unwrap();
        assert_eq!(result, " 000");
    }

    #[test]
    fn test_encode_value_too_long() {
        let pattern = tokenize_edited_pic("999").unwrap();
        let result = encode_edited_numeric("1234", &pattern, 0, false);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err().code,
            ErrorCode::CBKD421_EDITED_PIC_INVALID_FORMAT
        ));
    }

    // ===== E3.7 Space Insertion Tests =====

    #[test]
    fn test_encode_space_insertion_simple() {
        let pattern = tokenize_edited_pic("999B999").unwrap();
        let result = encode_edited_numeric("123456", &pattern, 0, false).unwrap();
        assert_eq!(result, "123 456");
    }

    #[test]
    fn test_encode_space_insertion_multiple() {
        let pattern = tokenize_edited_pic("9B9B9").unwrap();
        let result = encode_edited_numeric("123", &pattern, 0, false).unwrap();
        assert_eq!(result, "1 2 3");
    }

    #[test]
    fn test_encode_space_with_zero_suppress() {
        let pattern = tokenize_edited_pic("ZZZB999").unwrap();
        let result = encode_edited_numeric("123456", &pattern, 0, false).unwrap();
        assert_eq!(result, "123 456");
    }

    #[test]
    fn test_encode_space_with_decimal() {
        let pattern = tokenize_edited_pic("999B999.99").unwrap();
        let result = encode_edited_numeric("123456.78", &pattern, 2, false).unwrap();
        assert_eq!(result, "123 456.78");
    }

    #[test]
    fn test_encode_space_multiple_repetition() {
        let pattern = tokenize_edited_pic("99B(3)99").unwrap();
        let result = encode_edited_numeric("1234", &pattern, 0, false).unwrap();
        assert_eq!(result, "12   34");
    }

    #[test]
    fn test_encode_space_with_currency() {
        let pattern = tokenize_edited_pic("$999B999.99").unwrap();
        let result = encode_edited_numeric("123456.78", &pattern, 2, false).unwrap();
        assert_eq!(result, "$123 456.78");
    }

    #[test]
    fn test_encode_space_with_sign() {
        let pattern = tokenize_edited_pic("+999B999").unwrap();
        let result = encode_edited_numeric("123456", &pattern, 0, false).unwrap();
        assert_eq!(result, "+123 456");
    }

    #[test]
    fn test_encode_empty_value() {
        let pattern = tokenize_edited_pic("999").unwrap();
        let result = encode_edited_numeric("", &pattern, 0, false);
        assert!(result.is_err());
    }

    #[test]
    fn test_encode_invalid_character() {
        let pattern = tokenize_edited_pic("999").unwrap();
        let result = encode_edited_numeric("12a", &pattern, 0, false);
        assert!(result.is_err());
    }
}