hl7v2-cli 1.2.1

Command-line interface for HL7 v2 message manipulation and validation.
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
//! Unit tests for hl7v2-cli
//!
//! Tests argument parsing, command execution, and error handling.

#[cfg(test)]
#[expect(
    clippy::assertions_on_result_states,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::uninlined_format_args,
    clippy::unwrap_used,
    reason = "legacy CLI unit tests use static fixtures; cleanup is tracked in policy/clippy-debt.toml"
)]
mod cli_unit_tests {
    use hl7v2_test_utils::fixtures::SampleMessages;
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    // Helper to create a temp file with content
    fn create_temp_file(dir: &TempDir, filename: &str, content: &[u8]) -> PathBuf {
        let path = dir.path().join(filename);
        fs::write(&path, content).expect("Failed to write temp file");
        path
    }

    // Helper to create a temp HL7 file
    fn create_temp_hl7_file(dir: &TempDir, filename: &str) -> PathBuf {
        create_temp_file(dir, filename, SampleMessages::adt_a01().as_bytes())
    }

    // =========================================================================
    // Argument Parsing Tests
    // =========================================================================

    mod argument_parsing {

        use clap::CommandFactory;

        #[test]
        fn test_parse_command_requires_input() {
            // Test that parse command requires an input file argument
            // This is enforced by clap's derive macros
            use crate::Cli;
            let schema = Cli::command();
            // The command structure requires input for Parse variant
            assert!(schema.get_subcommands().any(|c| c.get_name() == "parse"));
        }

        #[test]
        fn test_validate_command_requires_profile() {
            // Test that validate command requires a profile argument
            use crate::Cli;
            let schema = Cli::command();
            assert!(schema.get_subcommands().any(|c| c.get_name() == "val"));
        }

        #[test]
        fn test_ack_command_mode_options() {
            // Verify ACK mode options exist
            let modes = vec!["original", "enhanced"];
            for mode in modes {
                // These should be valid values for --mode
                assert!(mode == "original" || mode == "enhanced");
            }
        }

        #[test]
        fn test_ack_command_code_options() {
            // Verify ACK code options exist
            let codes = vec!["AA", "AE", "AR", "CA", "CE", "CR"];
            for code in codes {
                // These should be valid values for --code
                assert!(!code.is_empty());
            }
        }
    }

    // =========================================================================
    // Parse Command Tests
    // =========================================================================

    mod parse_command {
        use super::*;
        use hl7v2::{parse, to_json};

        #[test]
        fn test_parse_valid_hl7_message() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let result = parse(bytes);
            assert!(result.is_ok());

            let message = result.unwrap();
            assert!(!message.segments.is_empty());
            assert!(message.segments[0].id_str() == "MSH");
        }

        #[test]
        fn test_parse_outputs_valid_json() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let message = parse(bytes).expect("Parse should succeed");
            let json_value = to_json(&message);

            // Verify it's valid JSON
            let json_string = serde_json::to_string(&json_value).expect("Should serialize to JSON");
            assert!(json_string.contains("MSH"));
        }

        #[test]
        fn test_parse_mllp_framed_message() {
            // Create MLLP-framed message
            let content = SampleMessages::adt_a01();
            let mut mllp_bytes = vec![0x0B]; // SB
            mllp_bytes.extend_from_slice(content.as_bytes());
            mllp_bytes.push(0x1C); // EB
            mllp_bytes.push(0x0D); // CR

            let result = hl7v2::parse_mllp(&mllp_bytes);
            assert!(result.is_ok());

            let message = result.unwrap();
            assert!(message.segments[0].id_str() == "MSH");
        }

        #[test]
        fn test_parse_detects_segment_count() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let message = parse(bytes).expect("Parse should succeed");

            // ADT^A01 should have MSH, EVN, PID, PV1 segments
            assert!(message.segments.len() >= 4);
        }

        #[test]
        fn test_parse_extracts_delimiters() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let message = parse(bytes).expect("Parse should succeed");

            // Standard delimiters
            assert_eq!(message.delims.field, '|');
            assert_eq!(message.delims.comp, '^');
            assert_eq!(message.delims.rep, '~');
            assert_eq!(message.delims.esc, '\\');
            assert_eq!(message.delims.sub, '&');
        }
    }

    // =========================================================================
    // Normalize Command Tests
    // =========================================================================

    mod norm_command {
        use super::*;
        use hl7v2::{parse, write};

        #[test]
        fn test_normalize_roundtrip() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let message = parse(bytes).expect("Parse should succeed");
            let normalized = write(&message);

            // Should be able to parse the normalized output
            let reparsed = parse(&normalized).expect("Reparse should succeed");
            assert_eq!(message.segments.len(), reparsed.segments.len());
        }

        #[test]
        fn test_normalize_mllp_output() {
            let content = SampleMessages::adt_a01();
            let bytes = content.as_bytes();

            let message = parse(bytes).expect("Parse should succeed");
            let normalized = write(&message);

            // Wrap in MLLP
            let mllp_bytes = hl7v2::wrap_mllp(&normalized);

            // Verify MLLP framing
            assert_eq!(mllp_bytes[0], 0x0B); // SB
            assert_eq!(mllp_bytes[mllp_bytes.len() - 2], 0x1C); // EB
            assert_eq!(mllp_bytes[mllp_bytes.len() - 1], 0x0D); // CR
        }
    }

    // =========================================================================
    // Validate Command Tests
    // =========================================================================

    mod validate_command {
        use super::*;

        #[test]
        fn test_validate_with_valid_profile() {
            // Profile format must match hl7v2::Profile struct
            let profile_yaml = r#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
constraints:
  - path: MSH.1
    required: true
  - path: MSH.2
    required: true
"#;
            let result = hl7v2::load_profile(profile_yaml);
            assert!(result.is_ok(), "Failed to load profile: {:?}", result.err());
        }

        #[test]
        fn test_validate_detects_missing_required_segment() {
            // Profile format must match hl7v2::Profile struct
            let profile_yaml = r#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
  - id: EVN
  - id: PID
  - id: ZZ1
constraints:
  - path: MSH
    required: true
  - path: EVN
    required: true
  - path: PID
    required: true
  - path: ZZ1
    required: true
"#;
            let profile = hl7v2::load_profile(profile_yaml).expect("Profile should load");
            let message =
                hl7v2::parse(SampleMessages::adt_a01().as_bytes()).expect("Parse should succeed");

            let results = hl7v2::validate(&message, &profile);

            // Should have validation issues because ZZ1 is not in the sample message
            assert!(
                !results.is_empty(),
                "Should have validation errors for missing ZZ1 segment"
            );
        }
    }

    // =========================================================================
    // ACK Generation Tests
    // =========================================================================

    mod ack_command {
        use super::*;
        use hl7v2::{AckCode, ack};

        #[test]
        fn test_generate_ack_aa() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");

            let ack_result = ack(&message, AckCode::AA);
            assert!(ack_result.is_ok());

            let ack_message = ack_result.unwrap();
            assert!(ack_message.segments.iter().any(|s| s.id_str() == "MSH"));
            assert!(ack_message.segments.iter().any(|s| s.id_str() == "MSA"));
        }

        #[test]
        fn test_generate_ack_ae() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");

            let ack_result = ack(&message, AckCode::AE);
            assert!(ack_result.is_ok());
        }

        #[test]
        fn test_generate_ack_ar() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");

            let ack_result = ack(&message, AckCode::AR);
            assert!(ack_result.is_ok());
        }

        #[test]
        fn test_ack_contains_original_message_control_id() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");

            let ack_message = ack(&message, AckCode::AA).expect("ACK should generate");

            // MSA segment should reference the original message
            let msa = ack_message.segments.iter().find(|s| s.id_str() == "MSA");
            assert!(msa.is_some());
        }
    }

    // =========================================================================
    // Generate Command Tests
    // =========================================================================

    mod gen_command {

        #[test]
        fn test_parse_template_yaml() {
            // Template format matches hl7v2::synthetic::template::Template struct
            let template_yaml = r#"
name: ADT_A01
delims: "^~\\&"
segments:
  - "MSH|^~\\&|TestApp|TestFac|ReceivingApp|ReceivingFac|20250128152312||ADT^A01^ADT_A01|ABC123|P|2.5.1"
  - "PID|1||123456^^^HOSP^MR||Doe^John"
values: {}
"#;
            let result: Result<hl7v2::synthetic::generate::Template, _> =
                serde_yaml::from_str(template_yaml);
            assert!(
                result.is_ok(),
                "Failed to parse template YAML: {:?}",
                result.err()
            );
        }
    }

    // =========================================================================
    // Error Handling Tests
    // =========================================================================

    mod error_handling {
        use super::*;

        #[test]
        fn test_parse_empty_input_returns_error() {
            let result = hl7v2::parse(b"");
            assert!(result.is_err());
        }

        #[test]
        fn test_parse_invalid_input_returns_error() {
            // Not a valid HL7 message
            let result = hl7v2::parse(b"This is not HL7");
            assert!(result.is_err());
        }

        #[test]
        fn test_parse_truncated_message_returns_error() {
            // Truncated message (just MSH with no proper structure)
            let result = hl7v2::parse(b"MSH");
            assert!(result.is_err());
        }

        #[test]
        fn test_missing_file_error() {
            let non_existent = PathBuf::from("/nonexistent/path/file.hl7");
            let result = fs::read_to_string(&non_existent);
            assert!(result.is_err());
        }

        #[test]
        fn test_invalid_profile_yaml_returns_error() {
            let invalid_yaml = "this is not: valid: yaml:::";
            let _result = hl7v2::load_profile(invalid_yaml);
            // Should handle gracefully (either error or empty profile)
            // Behavior depends on implementation
        }
    }

    // =========================================================================
    // MLLP Tests
    // =========================================================================

    mod mllp_handling {
        use super::*;

        #[test]
        fn test_mllp_wrap() {
            let data = b"MSH|^~\\&|Test\r";
            let wrapped = hl7v2::wrap_mllp(data);

            assert_eq!(wrapped[0], 0x0B); // SB
            assert!(wrapped[..].ends_with(&[0x1C, 0x0D])); // EB CR
        }

        #[test]
        fn test_mllp_parse_and_unwrap() {
            let content = SampleMessages::adt_a01();
            let mut mllp_bytes = vec![0x0B];
            mllp_bytes.extend_from_slice(content.as_bytes());
            mllp_bytes.push(0x1C);
            mllp_bytes.push(0x0D);

            let message = hl7v2::parse_mllp(&mllp_bytes).expect("Should parse MLLP");
            assert!(!message.segments.is_empty());
        }

        #[test]
        fn test_mllp_write() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");

            let mllp_bytes = hl7v2::write_mllp(&message);

            assert_eq!(mllp_bytes[0], 0x0B);
            assert!(mllp_bytes[..].ends_with(&[0x1C, 0x0D]));
        }
    }

    // =========================================================================
    // Interactive Mode Tests
    // =========================================================================

    mod interactive_mode {

        #[test]
        fn test_interactive_help_command() {
            // The help command should list all available commands
            let commands = ["parse", "norm", "val", "ack", "gen", "help", "exit"];
            for cmd in commands {
                assert!(!cmd.is_empty());
            }
        }

        #[test]
        fn test_interactive_parse_command_parsing() {
            // Test parsing of interactive parse command format
            let input = "parse test.hl7 --json --summary";
            let parts: Vec<&str> = input.split_whitespace().collect();

            assert_eq!(parts[0], "parse");
            assert_eq!(parts[1], "test.hl7");
            assert!(parts.contains(&"--json"));
            assert!(parts.contains(&"--summary"));
        }
    }

    // Performance monitor tests are covered through integration tests
    // since the monitor module is not public

    // =========================================================================
    // Output Formatting Tests
    // =========================================================================

    mod output_formatting {
        use super::*;

        #[test]
        fn test_json_pretty_format() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");
            let json_value = hl7v2::to_json(&message);

            let pretty = serde_json::to_string_pretty(&json_value).expect("Should serialize");
            assert!(pretty.contains('\n')); // Pretty format has newlines
        }

        #[test]
        fn test_json_compact_format() {
            let content = SampleMessages::adt_a01();
            let message = hl7v2::parse(content.as_bytes()).expect("Parse should succeed");
            let json_value = hl7v2::to_json(&message);

            let compact = serde_json::to_string(&json_value).expect("Should serialize");
            // Compact format should be smaller than pretty
            assert!(!compact.contains("\n  ")); // No indented newlines
        }
    }

    // =========================================================================
    // New CLI Flags Tests
    // =========================================================================

    mod new_flags {
        use super::*;
        use hl7v2::{normalize, parse, write};

        // -------------------------------------------------------------------------
        // --canonical-delims flag tests
        // -------------------------------------------------------------------------

        #[test]
        fn test_canonical_delimiters_normalization() {
            // Create a message with non-canonical delimiters
            let content = "MSH|@#$\\&|SendingApp|SendingFac|ReceivingApp|ReceivingFac|20250128152312||ADT^A01|ABC123|P|2.5.1\rPID|1||12345^^^HOSP^MR||Doe^John\r";

            // Parse and normalize with canonical delimiters
            let message = parse(content.as_bytes()).expect("Parse should succeed");
            let original_bytes = write(&message);
            let normalized = normalize(&original_bytes, true).expect("Normalize should succeed");
            let normalized_str = String::from_utf8_lossy(&normalized);

            // Verify canonical delimiters are used
            assert!(normalized_str.starts_with("MSH|^~\\&|"));
        }

        #[test]
        fn test_canonical_delimiters_preserves_content() {
            let content = SampleMessages::adt_a01();
            let message = parse(content.as_bytes()).expect("Parse should succeed");

            let original_bytes = write(&message);
            let normalized = normalize(&original_bytes, true).expect("Normalize should succeed");

            // Parse the normalized message
            let reparsed = parse(&normalized).expect("Reparse should succeed");

            // Verify segment count is preserved
            assert_eq!(message.segments.len(), reparsed.segments.len());
        }

        // -------------------------------------------------------------------------
        // --envelope flag tests
        // -------------------------------------------------------------------------

        #[test]
        fn test_envelope_mllp_wrap() {
            let content = SampleMessages::adt_a01();
            let message = parse(content.as_bytes()).expect("Parse should succeed");

            let output_bytes = write(&message);
            let mllp_bytes = hl7v2::wrap_mllp(&output_bytes);

            // Verify MLLP framing
            assert_eq!(mllp_bytes[0], 0x0B); // SB
            assert!(mllp_bytes[..].ends_with(&[0x1C, 0x0D])); // EB CR
        }

        #[test]
        fn test_envelope_and_canonical_combined() {
            let content = SampleMessages::adt_a01();
            let message = parse(content.as_bytes()).expect("Parse should succeed");

            // Normalize and wrap
            let original_bytes = write(&message);
            let normalized = normalize(&original_bytes, true).expect("Normalize should succeed");
            let mllp_bytes = hl7v2::wrap_mllp(&normalized);

            // Verify MLLP framing
            assert_eq!(mllp_bytes[0], 0x0B); // SB

            // Extract and verify content starts with canonical delimiters
            let content = &mllp_bytes[1..mllp_bytes.len() - 2];
            let content_str = String::from_utf8_lossy(content);
            assert!(content_str.starts_with("MSH|^~\\&|"));
        }

        // -------------------------------------------------------------------------
        // --report flag tests (validation report formats)
        // -------------------------------------------------------------------------

        #[test]
        fn test_validation_report_json_format() {
            let profile_yaml = r#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
constraints:
  - path: MSH.1
    required: true
"#;
            let profile = hl7v2::load_profile(profile_yaml).expect("Profile should load");
            let message =
                parse(SampleMessages::adt_a01().as_bytes()).expect("Parse should succeed");

            let results = hl7v2::validate(&message, &profile);

            // Create a validation report
            let report = crate::ValidationReport {
                input_file: "test.hl7".to_string(),
                profile_file: "profile.yaml".to_string(),
                file_size: 100,
                segment_count: message.segments.len(),
                is_valid: results.is_empty(),
                issue_count: results.len(),
                issues: results.iter().map(|r| format!("{:?}", r)).collect(),
            };

            // Verify JSON serialization works
            let json = serde_json::to_string_pretty(&report).expect("Should serialize to JSON");
            assert!(json.contains("input_file"));
            assert!(json.contains("is_valid"));
        }

        #[test]
        fn test_validation_report_yaml_format() {
            let profile_yaml = r#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
constraints:
  - path: MSH.1
    required: true
"#;
            let profile = hl7v2::load_profile(profile_yaml).expect("Profile should load");
            let message =
                parse(SampleMessages::adt_a01().as_bytes()).expect("Parse should succeed");

            let results = hl7v2::validate(&message, &profile);

            // Create a validation report
            let report = crate::ValidationReport {
                input_file: "test.hl7".to_string(),
                profile_file: "profile.yaml".to_string(),
                file_size: 100,
                segment_count: message.segments.len(),
                is_valid: results.is_empty(),
                issue_count: results.len(),
                issues: results.iter().map(|r| format!("{:?}", r)).collect(),
            };

            // Verify YAML serialization works
            let yaml = serde_yaml::to_string(&report).expect("Should serialize to YAML");
            assert!(yaml.contains("input_file"));
            assert!(yaml.contains("is_valid"));
        }

        // -------------------------------------------------------------------------
        // Stats command logic tests
        // -------------------------------------------------------------------------

        #[test]
        fn test_collect_stats_basic() {
            use hl7v2::parse;
            let content = SampleMessages::adt_a01();
            let message = parse(content.as_bytes()).expect("Parse should succeed");

            let stats = crate::collect_stats(&message, false);

            assert_eq!(stats.segment_count, message.segments.len());
            assert!(stats.field_distributions.is_none());
            assert!(stats.segments.iter().any(|s| s.segment_id == "MSH"));
            assert!(stats.segments.iter().any(|s| s.segment_id == "PID"));
        }

        #[test]
        fn test_collect_stats_with_distributions() {
            use hl7v2::parse;
            let content = SampleMessages::adt_a01();
            let message = parse(content.as_bytes()).expect("Parse should succeed");

            let stats = crate::collect_stats(&message, true);

            assert!(stats.field_distributions.is_some());
            let dists = stats.field_distributions.unwrap();
            assert!(!dists.is_empty());
            // Should contain MSH.3, etc. (skips MSH.0 as per logic)
            assert!(dists.iter().any(|d| d.path == "MSH.3"));
        }

        #[test]
        fn test_format_stats_report_text() {
            let segments = vec![
                crate::SegmentStats {
                    segment_id: "MSH".to_string(),
                    count: 1,
                },
                crate::SegmentStats {
                    segment_id: "PID".to_string(),
                    count: 1,
                },
            ];

            let report = crate::StatsReport {
                input_file: "test.hl7".to_string(),
                file_size: 100,
                segment_count: 2,
                segments,
                field_distributions: None,
            };

            let output = crate::format_stats_report(&report, &crate::ReportFormat::Text)
                .expect("Should format as text");

            assert!(output.contains("Message Statistics:"));
            assert!(output.contains("Input file: test.hl7"));
            assert!(output.contains("Total segments: 2"));
            assert!(output.contains("MSH: 1 occurrence(s)"));
            assert!(output.contains("PID: 1 occurrence(s)"));
        }

        #[test]
        fn test_format_stats_report_yaml() {
            let report = crate::StatsReport {
                input_file: "test.hl7".to_string(),
                file_size: 100,
                segment_count: 1,
                segments: vec![crate::SegmentStats {
                    segment_id: "MSH".to_string(),
                    count: 1,
                }],
                field_distributions: None,
            };

            let output = crate::format_stats_report(&report, &crate::ReportFormat::Yaml)
                .expect("Should format as YAML");

            assert!(output.contains("input_file: test.hl7"));
            assert!(output.contains("segment_count: 1"));
        }

        #[test]
        fn test_stats_command_execution() {
            use crate::ReportFormat;
            use crate::stats_command;
            let dir = TempDir::new().expect("Failed to create temp dir");
            let file_path = create_temp_hl7_file(&dir, "test.hl7");

            // Execute stats command
            let result = stats_command(&file_path, false, true, &ReportFormat::Text);
            assert!(result.is_ok());
        }

        #[test]
        fn test_command_paths_accept_mllp_inputs_through_facade() {
            let dir = TempDir::new().expect("Failed to create temp dir");
            let framed = hl7v2::wrap_mllp(SampleMessages::adt_a01().as_bytes());
            let mllp_path = create_temp_file(&dir, "message.mllp", &framed);
            let output_path = dir.path().join("normalized.hl7");
            let profile_path = create_temp_file(
                &dir,
                "profile.yaml",
                br#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
constraints:
  - path: MSH.9
    required: true
"#,
            );

            assert!(
                crate::parse_command(&mllp_path, false, true, true, true, false, false).is_ok()
            );
            assert!(
                crate::norm_command(&mllp_path, true, &Some(output_path), true, true, false)
                    .is_ok()
            );
            assert!(
                crate::val_command(
                    &mllp_path,
                    &profile_path,
                    true,
                    false,
                    &crate::ReportFormat::Text,
                    false,
                )
                .is_ok()
            );
            assert!(
                crate::stats_command(&mllp_path, true, false, &crate::ReportFormat::Text).is_ok()
            );
            assert!(
                crate::ack_command(
                    &mllp_path,
                    &crate::AckMode::Original,
                    &crate::AckCode::AA,
                    true,
                    true,
                    false,
                )
                .is_ok()
            );
        }

        // -------------------------------------------------------------------------
        // --streaming flag tests
        // -------------------------------------------------------------------------

        #[test]
        fn test_streaming_mode_flag() {
            // The streaming flag is primarily for memory-efficient processing
            // of large files. Here we just verify the flag exists and can be parsed.
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let parse_cmd = schema.get_subcommands().find(|c| c.get_name() == "parse");
            assert!(parse_cmd.is_some());

            let parse_cmd = parse_cmd.unwrap();
            let streaming_arg = parse_cmd
                .get_arguments()
                .find(|a| a.get_id() == "streaming");
            assert!(streaming_arg.is_some());
        }

        // -------------------------------------------------------------------------
        // ReportFormat enum tests
        // -------------------------------------------------------------------------

        #[test]
        fn test_report_format_values() {
            use crate::ReportFormat;

            // Verify all format variants exist
            let _text = ReportFormat::Text;
            let _json = ReportFormat::Json;
            let _yaml = ReportFormat::Yaml;

            // Verify default
            assert_eq!(ReportFormat::default(), ReportFormat::Text);
        }

        // -------------------------------------------------------------------------
        // Clap argument parsing tests for new flags
        // -------------------------------------------------------------------------

        #[test]
        fn test_parse_command_has_canonical_delims_flag() {
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let parse_cmd = schema.get_subcommands().find(|c| c.get_name() == "parse");
            assert!(parse_cmd.is_some());

            let parse_cmd = parse_cmd.unwrap();
            let canonical_arg = parse_cmd
                .get_arguments()
                .find(|a| a.get_id() == "canonical_delims");
            assert!(canonical_arg.is_some());
        }

        #[test]
        fn test_parse_command_has_envelope_flag() {
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let parse_cmd = schema.get_subcommands().find(|c| c.get_name() == "parse");
            assert!(parse_cmd.is_some());

            let parse_cmd = parse_cmd.unwrap();
            let envelope_arg = parse_cmd.get_arguments().find(|a| a.get_id() == "envelope");
            assert!(envelope_arg.is_some());
        }

        #[test]
        fn test_val_command_has_report_flag() {
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let val_cmd = schema.get_subcommands().find(|c| c.get_name() == "val");
            assert!(val_cmd.is_some());

            let val_cmd = val_cmd.unwrap();
            let report_arg = val_cmd.get_arguments().find(|a| a.get_id() == "report");
            assert!(report_arg.is_some());
        }

        #[test]
        fn test_stats_command_exists() {
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let stats_cmd = schema.get_subcommands().find(|c| c.get_name() == "stats");
            assert!(stats_cmd.is_some());
        }

        #[test]
        fn test_stats_command_has_distributions_flag() {
            use crate::Cli;
            use clap::CommandFactory;

            let schema = Cli::command();
            let stats_cmd = schema.get_subcommands().find(|c| c.get_name() == "stats");
            assert!(stats_cmd.is_some());

            let stats_cmd = stats_cmd.unwrap();
            let distributions_arg = stats_cmd
                .get_arguments()
                .find(|a| a.get_id() == "distributions");
            assert!(distributions_arg.is_some());
        }
    }
}