copybook-core 0.4.3

Core COBOL copybook parser, schema, and validation primitives.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Schema types for COBOL copybook structures
//!
//! This module defines the core data structures that represent a parsed
//! COBOL copybook schema, including fields, types, and layout information.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A parsed COBOL copybook schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schema {
    /// Root fields in the schema
    pub fields: Vec<Field>,
    /// Fixed record length (LRECL) if applicable
    pub lrecl_fixed: Option<u32>,
    /// Tail ODO information if present
    pub tail_odo: Option<TailODO>,
    /// Schema fingerprint for provenance tracking
    pub fingerprint: String,
}

/// Information about tail ODO (OCCURS DEPENDING ON) arrays
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TailODO {
    /// Path to the ODO counter field
    pub counter_path: String,
    /// Minimum array length
    pub min_count: u32,
    /// Maximum array length
    pub max_count: u32,
    /// Path to the ODO array field
    pub array_path: String,
}

/// A field in the copybook schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Field {
    /// Hierarchical path (e.g., "ROOT.CUSTOMER.ID")
    pub path: String,
    /// Field name (last component of path)
    pub name: String,
    /// Level number from copybook
    pub level: u8,
    /// Field type and characteristics
    pub kind: FieldKind,
    /// Byte offset within record
    pub offset: u32,
    /// Field length in bytes
    pub len: u32,
    /// Path of field this redefines (if any)
    pub redefines_of: Option<String>,
    /// Array information (if any)
    pub occurs: Option<Occurs>,
    /// Alignment padding bytes (if SYNCHRONIZED)
    pub sync_padding: Option<u16>,
    /// Whether field is SYNCHRONIZED
    pub synchronized: bool,
    /// Whether field has BLANK WHEN ZERO
    pub blank_when_zero: bool,
    /// Resolved RENAMES information (for level-66 fields only)
    pub resolved_renames: Option<ResolvedRenames>,
    /// Child fields (for groups)
    pub children: Vec<Field>,
}

/// Field type and characteristics
///
/// # Examples
///
/// ```
/// use copybook_core::FieldKind;
///
/// let alpha = FieldKind::Alphanum { len: 10 };
/// assert!(matches!(alpha, FieldKind::Alphanum { len: 10 }));
///
/// let packed = FieldKind::PackedDecimal { digits: 7, scale: 2, signed: true };
/// assert!(matches!(packed, FieldKind::PackedDecimal { signed: true, .. }));
///
/// let group = FieldKind::Group;
/// assert!(matches!(group, FieldKind::Group));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FieldKind {
    /// Alphanumeric field (PIC X)
    Alphanum {
        /// Field length in characters
        len: u32,
    },
    /// Zoned decimal field (PIC 9, display)
    ZonedDecimal {
        /// Total number of digits
        digits: u16,
        /// Decimal places (can be negative for scaling)
        scale: i16,
        /// Whether field is signed
        signed: bool,
        /// SIGN SEPARATE clause information (if applicable)
        sign_separate: Option<SignSeparateInfo>,
    },
    /// Binary integer field (COMP/BINARY)
    BinaryInt {
        /// Number of bits (16, 32, 64)
        bits: u16,
        /// Whether field is signed
        signed: bool,
    },
    /// Packed decimal field (COMP-3)
    PackedDecimal {
        /// Total number of digits
        digits: u16,
        /// Decimal places (can be negative for scaling)
        scale: i16,
        /// Whether field is signed
        signed: bool,
    },
    /// Group field (contains other fields)
    Group,
    /// Level-88 condition field (conditional values)
    Condition {
        /// Condition values (e.g., VALUE 'A', VALUE 1 THROUGH 5)
        values: Vec<String>,
    },
    /// Level-66 RENAMES field (field aliasing/regrouping)
    Renames {
        /// Starting field name in the range
        from_field: String,
        /// Ending field name in the range
        thru_field: String,
    },
    /// Edited numeric field (Phase E2: parse, represent, and decode)
    /// Examples: PIC ZZZ9, PIC $ZZ,ZZ9.99, PIC 9(7)V99CR
    EditedNumeric {
        /// Original PIC string (e.g., "ZZ,ZZZ.99")
        pic_string: String,
        /// Display width (computed from PIC)
        width: u16,
        /// Decimal places (scale) for numeric value
        scale: u16,
        /// Whether field has sign editing
        signed: bool,
    },
    /// Single-precision floating-point (COMP-1, IEEE 754 binary32, 4 bytes)
    FloatSingle,
    /// Double-precision floating-point (COMP-2, IEEE 754 binary64, 8 bytes)
    FloatDouble,
}

/// Resolved RENAMES (level-66) alias information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedRenames {
    /// Byte offset of the aliased range
    pub offset: u32,
    /// Total byte length of the aliased range
    pub length: u32,
    /// Paths of fields covered by this alias (in document order)
    pub members: Vec<String>,
}

/// SIGN SEPARATE clause information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignSeparateInfo {
    /// Placement of the sign (LEADING or TRAILING)
    pub placement: SignPlacement,
}

/// Sign placement for SIGN SEPARATE clause
///
/// # Examples
///
/// ```
/// use copybook_core::SignPlacement;
///
/// let placement = SignPlacement::Leading;
/// assert_eq!(placement, SignPlacement::Leading);
/// assert_ne!(placement, SignPlacement::Trailing);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SignPlacement {
    /// Sign byte precedes the numeric digits
    Leading,
    /// Sign byte follows the numeric digits
    Trailing,
}

/// Array occurrence information
///
/// # Examples
///
/// ```
/// use copybook_core::Occurs;
///
/// let fixed = Occurs::Fixed { count: 10 };
/// assert!(matches!(fixed, Occurs::Fixed { count: 10 }));
///
/// let odo = Occurs::ODO {
///     min: 0,
///     max: 100,
///     counter_path: "ITEM-COUNT".to_string(),
/// };
/// assert!(matches!(odo, Occurs::ODO { max: 100, .. }));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Occurs {
    /// Fixed-size array
    Fixed {
        /// Number of elements
        count: u32,
    },
    /// Variable-size array (OCCURS DEPENDING ON)
    ODO {
        /// Minimum number of elements
        min: u32,
        /// Maximum number of elements
        max: u32,
        /// Path to counter field
        counter_path: String,
    },
}

impl Schema {
    /// Create a new empty schema
    #[must_use]
    pub fn new() -> Self {
        Self {
            fields: Vec::new(),
            lrecl_fixed: None,
            tail_odo: None,
            fingerprint: String::new(),
        }
    }

    /// Create a schema from a list of fields
    #[must_use]
    pub fn from_fields(fields: Vec<Field>) -> Self {
        let mut schema = Self {
            fields,
            lrecl_fixed: None,
            tail_odo: None,
            fingerprint: String::new(),
        };
        schema.calculate_fingerprint();
        schema
    }

    /// Calculate the schema fingerprint using SHA-256
    pub fn calculate_fingerprint(&mut self) {
        use sha2::{Digest, Sha256};

        // Create canonical JSON representation
        let canonical_json = self.create_canonical_json();

        // Calculate SHA-256 hash
        let mut hasher = Sha256::new();
        hasher.update(canonical_json.as_bytes());

        let result = hasher.finalize();
        self.fingerprint = format!("{result:x}");
    }

    /// Create canonical JSON representation for fingerprinting
    pub fn create_canonical_json(&self) -> String {
        use serde_json::{Map, Value};

        let mut schema_obj = Map::new();

        // Add fields in canonical order
        let fields_json: Vec<Value> = self
            .fields
            .iter()
            .map(Self::field_to_canonical_json)
            .collect();
        schema_obj.insert("fields".to_string(), Value::Array(fields_json));

        // Add schema-level properties
        if let Some(lrecl) = self.lrecl_fixed {
            schema_obj.insert("lrecl_fixed".to_string(), Value::Number(lrecl.into()));
        }

        if let Some(ref tail_odo) = self.tail_odo {
            let mut tail_odo_obj = Map::new();
            tail_odo_obj.insert(
                "counter_path".to_string(),
                Value::String(tail_odo.counter_path.clone()),
            );
            tail_odo_obj.insert(
                "min_count".to_string(),
                Value::Number(tail_odo.min_count.into()),
            );
            tail_odo_obj.insert(
                "max_count".to_string(),
                Value::Number(tail_odo.max_count.into()),
            );
            tail_odo_obj.insert(
                "array_path".to_string(),
                Value::String(tail_odo.array_path.clone()),
            );
            schema_obj.insert("tail_odo".to_string(), Value::Object(tail_odo_obj));
        }

        // Convert to canonical JSON string
        serde_json::to_string(&Value::Object(schema_obj)).unwrap_or_default()
    }

    /// Convert field to canonical JSON for fingerprinting
    fn field_to_canonical_json(field: &Field) -> Value {
        use serde_json::{Map, Value};

        let mut field_obj = Map::new();

        // Add fields in canonical order
        field_obj.insert("path".to_string(), Value::String(field.path.clone()));
        field_obj.insert("name".to_string(), Value::String(field.name.clone()));
        field_obj.insert("level".to_string(), Value::Number(field.level.into()));

        // Add field kind
        let kind_str = match &field.kind {
            FieldKind::Alphanum { len } => format!("Alphanum({len})"),
            FieldKind::ZonedDecimal {
                digits,
                scale,
                signed,
                sign_separate,
            } => {
                format!("ZonedDecimal({digits},{scale},{signed},{sign_separate:?})")
            }
            FieldKind::BinaryInt { bits, signed } => {
                format!("BinaryInt({bits},{signed})")
            }
            FieldKind::PackedDecimal {
                digits,
                scale,
                signed,
            } => {
                format!("PackedDecimal({digits},{scale},{signed})")
            }
            FieldKind::Group => "Group".to_string(),
            FieldKind::Condition { values } => format!("Condition({values:?})"),
            FieldKind::Renames {
                from_field,
                thru_field,
            } => format!("Renames({from_field},{thru_field})"),
            FieldKind::EditedNumeric {
                pic_string,
                width,
                scale,
                signed,
            } => {
                format!("EditedNumeric({pic_string},{width},scale={scale},signed={signed})")
            }
            FieldKind::FloatSingle => "FloatSingle".to_string(),
            FieldKind::FloatDouble => "FloatDouble".to_string(),
        };
        field_obj.insert("kind".to_string(), Value::String(kind_str));

        // Add optional fields
        if let Some(ref redefines) = field.redefines_of {
            field_obj.insert("redefines_of".to_string(), Value::String(redefines.clone()));
        }

        if let Some(ref occurs) = field.occurs {
            let occurs_str = match occurs {
                Occurs::Fixed { count } => format!("Fixed({count})"),
                Occurs::ODO {
                    min,
                    max,
                    counter_path,
                } => {
                    format!("ODO({min},{max},{counter_path})")
                }
            };
            field_obj.insert("occurs".to_string(), Value::String(occurs_str));
        }

        if field.synchronized {
            field_obj.insert("synchronized".to_string(), Value::Bool(true));
        }

        if field.blank_when_zero {
            field_obj.insert("blank_when_zero".to_string(), Value::Bool(true));
        }

        // Add children recursively
        if !field.children.is_empty() {
            let children_json: Vec<Value> = field
                .children
                .iter()
                .map(Self::field_to_canonical_json)
                .collect();
            field_obj.insert("children".to_string(), Value::Array(children_json));
        }

        Value::Object(field_obj)
    }

    /// Find a field by path
    ///
    /// Looks up a field by its fully-qualified dotted path (e.g., `"REC.ID"`).
    /// Searches recursively through all nested groups.
    ///
    /// # Examples
    ///
    /// ```
    /// use copybook_core::parse_copybook;
    ///
    /// let schema = parse_copybook("01 REC.\n   05 ID PIC 9(5).\n   05 NAME PIC X(20).").unwrap();
    ///
    /// let field = schema.find_field("REC.ID").unwrap();
    /// assert_eq!(field.name, "ID");
    /// assert_eq!(field.len, 5);
    ///
    /// assert!(schema.find_field("NONEXISTENT").is_none());
    /// ```
    #[must_use]
    pub fn find_field(&self, path: &str) -> Option<&Field> {
        Self::find_field_recursive(&self.fields, path)
    }

    fn find_field_recursive<'a>(fields: &'a [Field], path: &str) -> Option<&'a Field> {
        for field in fields {
            if field.path == path {
                return Some(field);
            }
            if let Some(found) = Self::find_field_recursive(&field.children, path) {
                return Some(found);
            }
        }
        None
    }

    /// Find a field by path or RENAMES alias name
    ///
    /// This method first tries to find a field by its path using standard lookup.
    /// If not found, it searches for a level-66 RENAMES field whose name matches
    /// the query and returns that alias field.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use copybook_core::Schema;
    /// let schema: Schema = // ... parsed schema with RENAMES
    /// # Schema::new();
    ///
    /// // Direct field lookup
    /// if let Some(field) = schema.find_field_or_alias("CUSTOMER-INFO") {
    ///     println!("Found field: {}", field.name);
    /// }
    ///
    /// // Alias lookup - finds level-66 field
    /// if let Some(alias) = schema.find_field_or_alias("CUSTOMER-DETAILS") {
    ///     if alias.level == 66 {
    ///         println!("Found RENAMES alias: {}", alias.name);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn find_field_or_alias(&self, name_or_path: &str) -> Option<&Field> {
        // First try direct field lookup
        if let Some(field) = self.find_field(name_or_path) {
            return Some(field);
        }

        // If not found, check if it's a RENAMES alias (level-66)
        // We need to match by field name (last path component), not full path
        let query_name = name_or_path.rsplit('.').next().unwrap_or(name_or_path);
        Self::find_alias_field_recursive(&self.fields, query_name)
    }

    /// Recursively search for a level-66 RENAMES field by name
    fn find_alias_field_recursive<'a>(fields: &'a [Field], alias_name: &str) -> Option<&'a Field> {
        for field in fields {
            // Check if this is a level-66 field with matching name
            if field.level == 66 && field.name.eq_ignore_ascii_case(alias_name) {
                return Some(field);
            }
            // Recurse into children
            if let Some(found) = Self::find_alias_field_recursive(&field.children, alias_name) {
                return Some(found);
            }
        }
        None
    }

    /// Resolve a RENAMES alias to its first target field
    ///
    /// If the query matches a level-66 RENAMES alias, this method returns the
    /// first storage-bearing field covered by that alias (from resolved_renames.members).
    /// Otherwise, it performs standard field lookup.
    ///
    /// This is useful for codec integration where you want to decode/encode data
    /// using an alias name but need the actual storage field.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use copybook_core::Schema;
    /// let schema: Schema = // ... parsed schema with RENAMES
    /// # Schema::new();
    ///
    /// // Resolve alias to target field
    /// if let Some(target) = schema.resolve_alias_to_target("CUSTOMER-DETAILS") {
    ///     // target will be CUSTOMER-INFO (or its first member)
    ///     println!("Alias resolves to: {}", target.name);
    /// }
    /// ```
    #[must_use]
    pub fn resolve_alias_to_target(&self, name_or_path: &str) -> Option<&Field> {
        // First try to find it as an alias
        if let Some(alias_field) = self.find_field_or_alias(name_or_path) {
            // If it's a level-66 with resolved_renames, return the first member
            if alias_field.level == 66
                && let Some(ref resolved) = alias_field.resolved_renames
                && let Some(first_member_path) = resolved.members.first()
            {
                return self.find_field(first_member_path);
            }
            // Otherwise return the field itself
            return Some(alias_field);
        }
        None
    }

    /// Find all fields that redefine the field at the given path
    ///
    /// Returns a list of fields whose `redefines_of` points to `target_path`.
    ///
    /// # Examples
    ///
    /// ```
    /// use copybook_core::parse_copybook;
    ///
    /// let schema = parse_copybook(
    ///     "01 REC.\n   05 AMT-NUM PIC 9(5)V99.\n   05 AMT-TXT REDEFINES AMT-NUM PIC X(7)."
    /// ).unwrap();
    ///
    /// let redefs = schema.find_redefining_fields("AMT-NUM");
    /// assert_eq!(redefs.len(), 1);
    /// assert_eq!(redefs[0].name, "AMT-TXT");
    /// ```
    #[must_use]
    pub fn find_redefining_fields<'a>(&'a self, target_path: &str) -> Vec<&'a Field> {
        fn collect<'a>(fields: &'a [Field], target_path: &str, acc: &mut Vec<&'a Field>) {
            for f in fields {
                if let Some(ref redef) = f.redefines_of
                    && redef == target_path
                {
                    acc.push(f);
                }
                collect(&f.children, target_path, acc);
            }
        }

        let mut result = Vec::new();
        collect(&self.fields, target_path, &mut result);
        result
    }

    /// Get all fields in a flat list (pre-order traversal)
    ///
    /// Returns every field in the schema, including nested children,
    /// as a flat vector in pre-order (depth-first) traversal order.
    ///
    /// # Examples
    ///
    /// ```
    /// use copybook_core::parse_copybook;
    ///
    /// let schema = parse_copybook("01 REC.\n   05 ID PIC 9(5).\n   05 NAME PIC X(20).").unwrap();
    ///
    /// let all = schema.all_fields();
    /// assert_eq!(all.len(), 3); // REC group + 2 leaf fields
    /// assert_eq!(all[0].name, "REC");
    /// assert_eq!(all[1].name, "ID");
    /// assert_eq!(all[2].name, "NAME");
    /// ```
    #[must_use]
    pub fn all_fields(&self) -> Vec<&Field> {
        let mut result = Vec::new();
        Self::collect_fields_recursive(&self.fields, &mut result);
        result
    }

    fn collect_fields_recursive<'a>(fields: &'a [Field], result: &mut Vec<&'a Field>) {
        for field in fields {
            result.push(field);
            Self::collect_fields_recursive(&field.children, result);
        }
    }
}

impl Field {
    /// Create a new field with level and name
    #[must_use]
    pub fn new(level: u8, name: String) -> Self {
        Self {
            path: name.clone(),
            name,
            level,
            kind: FieldKind::Group, // Default to group, will be updated by parser
            offset: 0,
            len: 0,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        }
    }

    /// Create a new field with all parameters
    #[must_use]
    pub fn with_kind(level: u8, name: String, kind: FieldKind) -> Self {
        Self {
            path: name.clone(),
            name,
            level,
            kind,
            offset: 0,
            len: 0,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        }
    }

    /// Check if this is a group field
    #[must_use]
    pub fn is_group(&self) -> bool {
        matches!(self.kind, FieldKind::Group)
    }

    /// Check if this is a scalar (leaf) field
    #[must_use]
    pub fn is_scalar(&self) -> bool {
        !self.is_group()
    }

    /// Get the effective length including any arrays
    #[must_use]
    pub fn effective_length(&self) -> u32 {
        match &self.occurs {
            Some(Occurs::Fixed { count }) => self.len * count,
            Some(Occurs::ODO { max, .. }) => self.len * max,
            None => self.len,
        }
    }

    /// Returns SIGN SEPARATE info if this is a zoned decimal field with that clause.
    #[must_use]
    pub fn sign_separate(&self) -> Option<&SignSeparateInfo> {
        if let FieldKind::ZonedDecimal { sign_separate, .. } = &self.kind {
            sign_separate.as_ref()
        } else {
            None
        }
    }

    /// Returns true if this is a packed decimal (COMP-3) field.
    #[must_use]
    pub fn is_packed(&self) -> bool {
        matches!(self.kind, FieldKind::PackedDecimal { .. })
    }

    /// Returns true if this is a binary integer (COMP/BINARY) field.
    #[must_use]
    pub fn is_binary(&self) -> bool {
        matches!(self.kind, FieldKind::BinaryInt { .. })
    }

    /// Returns true if this field's name is FILLER (case-insensitive).
    #[must_use]
    pub fn is_filler(&self) -> bool {
        self.name.eq_ignore_ascii_case("FILLER")
    }
}

impl Default for Schema {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_schema_default() {
        let schema = Schema::default();
        assert!(schema.fields.is_empty());
        assert!(schema.lrecl_fixed.is_none());
        assert!(schema.tail_odo.is_none());
        // Fingerprint is empty for default schema (calculated later)
        assert!(schema.fingerprint.is_empty());
    }

    #[test]
    fn test_schema_new() {
        let schema = Schema::new();
        assert!(schema.fields.is_empty());
        assert!(schema.lrecl_fixed.is_none());
        assert!(schema.tail_odo.is_none());
    }

    #[test]
    fn test_tail_odo_serialization() {
        let tail_odo = TailODO {
            counter_path: "ROOT.COUNT".to_string(),
            min_count: 1,
            max_count: 100,
            array_path: "ROOT.ARRAY".to_string(),
        };

        let serialized = serde_json::to_string(&tail_odo).unwrap();
        let deserialized: TailODO = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.counter_path, "ROOT.COUNT");
        assert_eq!(deserialized.min_count, 1);
        assert_eq!(deserialized.max_count, 100);
        assert_eq!(deserialized.array_path, "ROOT.ARRAY");
    }

    #[test]
    fn test_field_new() {
        let field = Field::new(5, "TEST-FIELD".to_string());
        assert_eq!(field.level, 5);
        assert_eq!(field.name, "TEST-FIELD");
        assert_eq!(field.path, "TEST-FIELD");
        assert!(matches!(field.kind, FieldKind::Group));
        assert_eq!(field.offset, 0);
        assert_eq!(field.len, 0);
    }

    #[test]
    fn test_field_with_kind() {
        let kind = FieldKind::Alphanum { len: 10 };
        let field = Field::with_kind(5, "TEST-FIELD".to_string(), kind.clone());
        assert_eq!(field.level, 5);
        assert_eq!(field.name, "TEST-FIELD");
        assert!(matches!(field.kind, FieldKind::Alphanum { len: 10 }));
    }

    #[test]
    fn test_field_is_group() {
        let group_field = Field::new(1, "GROUP".to_string());
        assert!(group_field.is_group());
        assert!(!group_field.is_scalar());

        let scalar_field =
            Field::with_kind(5, "SCALAR".to_string(), FieldKind::Alphanum { len: 10 });
        assert!(!scalar_field.is_group());
        assert!(scalar_field.is_scalar());
    }

    #[test]
    fn test_field_effective_length_no_occurs() {
        let field = Field {
            path: "TEST".to_string(),
            name: "TEST".to_string(),
            level: 5,
            kind: FieldKind::Alphanum { len: 10 },
            offset: 0,
            len: 10,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        };
        assert_eq!(field.effective_length(), 10);
    }

    #[test]
    fn test_field_effective_length_fixed_occurs() {
        let field = Field {
            path: "TEST".to_string(),
            name: "TEST".to_string(),
            level: 5,
            kind: FieldKind::Alphanum { len: 10 },
            offset: 0,
            len: 10,
            redefines_of: None,
            occurs: Some(Occurs::Fixed { count: 5 }),
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        };
        assert_eq!(field.effective_length(), 50);
    }

    #[test]
    fn test_field_effective_length_odo_occurs() {
        let field = Field {
            path: "TEST".to_string(),
            name: "TEST".to_string(),
            level: 5,
            kind: FieldKind::Alphanum { len: 10 },
            offset: 0,
            len: 10,
            redefines_of: None,
            occurs: Some(Occurs::ODO {
                min: 1,
                max: 100,
                counter_path: "ROOT.COUNT".to_string(),
            }),
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: Vec::new(),
        };
        assert_eq!(field.effective_length(), 1000);
    }

    #[test]
    fn test_field_kind_serialization() {
        let kinds = vec![
            FieldKind::Alphanum { len: 10 },
            FieldKind::ZonedDecimal {
                digits: 5,
                scale: 2,
                signed: true,
                sign_separate: None,
            },
            FieldKind::BinaryInt {
                bits: 32,
                signed: true,
            },
            FieldKind::PackedDecimal {
                digits: 7,
                scale: 2,
                signed: true,
            },
            FieldKind::Group,
            FieldKind::Condition {
                values: vec!["A".to_string(), "B".to_string()],
            },
            FieldKind::Renames {
                from_field: "FIELD1".to_string(),
                thru_field: "FIELD2".to_string(),
            },
            FieldKind::EditedNumeric {
                pic_string: "ZZ9.99".to_string(),
                width: 6,
                scale: 2,
                signed: false,
            },
        ];

        for kind in kinds {
            let serialized = serde_json::to_string(&kind).unwrap();
            let deserialized: FieldKind = serde_json::from_str(&serialized).unwrap();
            // Can't directly compare FieldKind due to no PartialEq, so re-serialize and compare
            let re_serialized = serde_json::to_string(&deserialized).unwrap();
            assert_eq!(serialized, re_serialized);
        }
    }

    #[test]
    fn test_sign_placement_serialization() {
        let placements = vec![SignPlacement::Leading, SignPlacement::Trailing];

        for placement in placements {
            let serialized = serde_json::to_string(&placement).unwrap();
            let deserialized: SignPlacement = serde_json::from_str(&serialized).unwrap();
            assert_eq!(serialized, serde_json::to_string(&deserialized).unwrap());
        }
    }

    #[test]
    fn test_sign_separate_info_serialization() {
        let info = SignSeparateInfo {
            placement: SignPlacement::Leading,
        };

        let serialized = serde_json::to_string(&info).unwrap();
        let deserialized: SignSeparateInfo = serde_json::from_str(&serialized).unwrap();

        assert!(matches!(deserialized.placement, SignPlacement::Leading));
    }

    #[test]
    fn test_resolved_renames_serialization() {
        let renames = ResolvedRenames {
            offset: 10,
            length: 50,
            members: vec!["FIELD1".to_string(), "FIELD2".to_string()],
        };

        let serialized = serde_json::to_string(&renames).unwrap();
        let deserialized: ResolvedRenames = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.offset, 10);
        assert_eq!(deserialized.length, 50);
        assert_eq!(deserialized.members.len(), 2);
        assert_eq!(deserialized.members[0], "FIELD1");
        assert_eq!(deserialized.members[1], "FIELD2");
    }

    #[test]
    fn test_schema_serialization() {
        let schema = Schema {
            fields: vec![Field::new(1, "ROOT".to_string())],
            lrecl_fixed: Some(100),
            tail_odo: Some(TailODO {
                counter_path: "ROOT.COUNT".to_string(),
                min_count: 1,
                max_count: 100,
                array_path: "ROOT.ARRAY".to_string(),
            }),
            fingerprint: "test-fingerprint".to_string(),
        };

        let serialized = serde_json::to_string(&schema).unwrap();
        let deserialized: Schema = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.fields.len(), 1);
        assert_eq!(deserialized.lrecl_fixed, Some(100));
        assert!(deserialized.tail_odo.is_some());
        assert_eq!(deserialized.fingerprint, "test-fingerprint");
    }

    #[test]
    fn test_schema_find_field() {
        let mut field = Field::new(5, "CHILD".to_string());
        field.path = "PARENT.CHILD".to_string();

        let schema = Schema {
            fields: vec![Field {
                path: "PARENT".to_string(),
                name: "PARENT".to_string(),
                level: 1,
                kind: FieldKind::Group,
                offset: 0,
                len: 10,
                redefines_of: None,
                occurs: None,
                sync_padding: None,
                synchronized: false,
                blank_when_zero: false,
                resolved_renames: None,
                children: vec![field],
            }],
            lrecl_fixed: None,
            tail_odo: None,
            fingerprint: "test".to_string(),
        };

        let found = schema.find_field("PARENT.CHILD");
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "CHILD");

        let not_found = schema.find_field("NONEXISTENT");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_schema_find_redefining_fields() {
        let _base_field = Field::new(5, "BASE".to_string());
        let redef_field1 =
            Field::with_kind(5, "REDEF1".to_string(), FieldKind::Alphanum { len: 5 });
        let redef_field2 = Field::with_kind(
            5,
            "REDEF2".to_string(),
            FieldKind::ZonedDecimal {
                digits: 5,
                scale: 0,
                signed: false,
                sign_separate: None,
            },
        );

        let mut base_field_with_redef = Field::new(5, "BASE".to_string());
        base_field_with_redef.path = "ROOT.BASE".to_string();
        base_field_with_redef.redefines_of = None;

        let mut redef_field1_with_path = redef_field1.clone();
        redef_field1_with_path.path = "ROOT.REDEF1".to_string();
        redef_field1_with_path.redefines_of = Some("ROOT.BASE".to_string());

        let mut redef_field2_with_path = redef_field2.clone();
        redef_field2_with_path.path = "ROOT.REDEF2".to_string();
        redef_field2_with_path.redefines_of = Some("ROOT.BASE".to_string());

        let schema = Schema {
            fields: vec![
                base_field_with_redef,
                redef_field1_with_path,
                redef_field2_with_path,
            ],
            lrecl_fixed: None,
            tail_odo: None,
            fingerprint: "test".to_string(),
        };

        let redefining = schema.find_redefining_fields("ROOT.BASE");
        assert_eq!(redefining.len(), 2);
        assert!(redefining.iter().any(|f| f.name == "REDEF1"));
        assert!(redefining.iter().any(|f| f.name == "REDEF2"));
    }

    #[test]
    fn test_schema_all_fields() {
        let child1 = Field::with_kind(5, "CHILD1".to_string(), FieldKind::Alphanum { len: 5 });
        let child2 = Field::with_kind(5, "CHILD2".to_string(), FieldKind::Alphanum { len: 5 });

        let mut parent = Field::new(1, "PARENT".to_string());
        parent.path = "ROOT.PARENT".to_string();
        parent.children = vec![child1, child2];

        let top_level = Field::with_kind(1, "TOP".to_string(), FieldKind::Alphanum { len: 10 });

        let schema = Schema {
            fields: vec![parent, top_level],
            lrecl_fixed: None,
            tail_odo: None,
            fingerprint: "test".to_string(),
        };

        let all_fields = schema.all_fields();
        // Should have: parent, child1, child2, top_level
        assert_eq!(all_fields.len(), 4);
        assert!(all_fields.iter().any(|f| f.name == "PARENT"));
        assert!(all_fields.iter().any(|f| f.name == "CHILD1"));
        assert!(all_fields.iter().any(|f| f.name == "CHILD2"));
        assert!(all_fields.iter().any(|f| f.name == "TOP"));
    }
}