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
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
//! Command-line interface for HL7 v2 processing.

#![expect(
    clippy::arithmetic_side_effects,
    clippy::allow_attributes,
    clippy::allow_attributes_without_reason,
    clippy::cast_precision_loss,
    clippy::exit,
    clippy::indexing_slicing,
    clippy::unchecked_time_subtraction,
    clippy::uninlined_format_args,
    clippy::unnecessary_debug_formatting,
    clippy::unwrap_used,
    reason = "pre-existing CLI reporting and table-rendering debt is tracked in policy/clippy-debt.toml"
)]
#![cfg_attr(
    test,
    expect(
        clippy::expect_used,
        reason = "pre-existing CLI config tests use static fixture expects; cleanup is tracked in policy/clippy-debt.toml"
    )
)]

use clap::{Parser, Subcommand};
use hl7v2::synthetic::generate::{Template, generate};
use hl7v2::{
    AckCode as GenAckCode, Event, Message, StreamParser, ack, load_profile, normalize, parse,
    parse_mllp, to_json, validate, wrap_mllp, write, write_mllp,
};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process;
mod config;
mod monitor;

mod serve;
#[cfg(test)]
mod tests;

#[derive(Parser)]
#[command(
    name = "hl7v2",
    about = "HL7 v2 parser, validator, and generator",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Parse HL7 v2 message and output JSON
    Parse {
        /// Input HL7 file
        input: PathBuf,

        /// Output JSON format
        #[arg(long)]
        json: bool,

        /// Output with canonical delimiters (|^~\&)
        #[arg(long)]
        canonical_delims: bool,

        /// Wrap output in MLLP envelope (add SB/EB markers)
        #[arg(long)]
        envelope: bool,

        /// Input is MLLP framed
        #[arg(long)]
        mllp: bool,

        /// Enable streaming mode for large files (memory-efficient processing)
        #[arg(long)]
        streaming: bool,

        /// Show summary statistics
        #[arg(long)]
        summary: bool,
    },

    /// Normalize HL7 v2 message
    Norm {
        /// Input HL7 file
        input: PathBuf,

        /// Use canonical delimiters (|^~\&)
        #[arg(long)]
        canonical_delims: bool,

        /// Output file
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Input is MLLP framed
        #[arg(long)]
        mllp_in: bool,

        /// Output should be MLLP framed
        #[arg(long)]
        mllp_out: bool,

        /// Show summary statistics
        #[arg(long)]
        summary: bool,
    },

    /// Validate HL7 v2 message against profile
    Val {
        /// Input HL7 file
        input: PathBuf,

        /// Profile YAML file
        #[arg(long)]
        profile: PathBuf,

        /// Input is MLLP framed
        #[arg(long)]
        mllp: bool,

        /// Show detailed validation results
        #[arg(long)]
        detailed: bool,

        /// Output validation report format (json, yaml, text)
        #[arg(long, value_enum, default_value = "text")]
        report: ReportFormat,

        /// Show summary statistics
        #[arg(long)]
        summary: bool,
    },

    /// Show statistics for HL7 v2 message
    Stats {
        /// Input HL7 file
        input: PathBuf,

        /// Input is MLLP framed
        #[arg(long)]
        mllp: bool,

        /// Show field value distributions
        #[arg(long)]
        distributions: bool,

        /// Output format (json, yaml, text)
        #[arg(long, value_enum, default_value = "text")]
        format: ReportFormat,
    },

    /// Generate ACK for HL7 v2 message
    Ack {
        /// Input HL7 file
        input: PathBuf,

        /// ACK mode (original or enhanced)
        #[arg(long)]
        mode: AckMode,

        /// ACK code
        #[arg(long)]
        code: AckCode,

        /// Input is MLLP framed
        #[arg(long)]
        mllp_in: bool,

        /// Output should be MLLP framed
        #[arg(long)]
        mllp_out: bool,

        /// Show summary statistics
        #[arg(long)]
        summary: bool,
    },

    /// Generate synthetic messages
    Gen {
        /// Profile YAML file
        #[arg(long)]
        profile: PathBuf,

        /// Random seed
        #[arg(long)]
        seed: u64,

        /// Number of messages to generate
        #[arg(long)]
        count: usize,

        /// Output directory
        #[arg(long)]
        out: PathBuf,

        /// Show generation statistics
        #[arg(long)]
        stats: bool,
    },

    /// Start HTTP/gRPC server for HL7 v2 processing
    Serve {
        /// Server mode (http or grpc)
        #[arg(long, value_enum, default_value = "http")]
        mode: ServerMode,

        /// Port to listen on
        #[arg(short, long, default_value = "8080")]
        port: u16,

        /// Host address to bind to
        #[arg(long, default_value = "0.0.0.0")]
        host: String,

        /// Maximum request body size in bytes
        #[arg(long, default_value = "10485760")]
        max_body_size: usize,
    },

    /// Interactive mode
    Interactive,
}

/// Server mode selection
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq)]
enum ServerMode {
    /// HTTP server with REST API
    Http,
    /// gRPC server (requires grpc feature)
    Grpc,
}

#[derive(clap::ValueEnum, Clone, Debug, PartialEq)]
enum AckMode {
    Original,
    Enhanced,
}

#[derive(clap::ValueEnum, Clone, Debug)]
#[value(rename_all = "UPPERCASE")]
enum AckCode {
    AA,
    AE,
    AR,
    CA,
    CE,
    CR,
}

/// Report output format
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Default)]
enum ReportFormat {
    #[default]
    Text,
    Json,
    Yaml,
}

#[tokio::main]
async fn main() {
    // Initialize tracing for server mode
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing::Level::INFO.into()),
        )
        .init();

    let cli = Cli::parse();

    let result = match &cli.command {
        Commands::Parse {
            input,
            json,
            canonical_delims,
            envelope,
            mllp,
            streaming,
            summary,
        } => parse_command(
            input,
            *json,
            *canonical_delims,
            *envelope,
            *mllp,
            *streaming,
            *summary,
        ),
        Commands::Norm {
            input,
            canonical_delims,
            output,
            mllp_in,
            mllp_out,
            summary,
        } => norm_command(
            input,
            *canonical_delims,
            output,
            *mllp_in,
            *mllp_out,
            *summary,
        ),
        Commands::Val {
            input,
            profile,
            mllp,
            detailed,
            report,
            summary,
        } => val_command(input, profile, *mllp, *detailed, report, *summary),
        Commands::Stats {
            input,
            mllp,
            distributions,
            format,
        } => stats_command(input, *mllp, *distributions, format),
        Commands::Ack {
            input,
            mode,
            code,
            mllp_in,
            mllp_out,
            summary,
        } => ack_command(input, mode, code, *mllp_in, *mllp_out, *summary),
        Commands::Gen {
            profile,
            seed,
            count,
            out,
            stats,
        } => gen_command(profile, *seed, *count, out, *stats),
        Commands::Serve {
            mode,
            port,
            host,
            max_body_size,
        } => serve::run_server(mode, *port, host, *max_body_size).await,
        Commands::Interactive => interactive_mode(),
    };

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        process::exit(1);
    }
}

/// Display performance statistics
fn display_performance_stats(monitor: &monitor::PerformanceMonitor) {
    println!();
    println!("Performance Statistics:");
    println!("  Total execution time: {:?}", monitor.elapsed());

    let metrics = monitor.get_metrics();
    if !metrics.is_empty() {
        println!("  Detailed metrics:");
        for (name, duration) in metrics {
            println!("    {}: {:?}", name, duration);
        }
    }

    // System information
    let system_info = monitor::get_system_info();
    println!("  System information:");
    if let Some(cpu_usage) = system_info.cpu.cpu_usage_percent {
        println!("    CPU usage: {:.2}%", cpu_usage);
    }
    println!("    Total memory: {} bytes", system_info.total_memory);
    println!("    Used memory: {} bytes", system_info.used_memory);
    if let Some(rss) = system_info.memory.resident_set_size {
        println!("    Process memory (RSS): {} bytes", rss);
    }
    if let Some(vms) = system_info.memory.virtual_memory_size {
        println!("    Process memory (VMS): {} bytes", vms);
    }
}

fn parse_command(
    input: &PathBuf,
    json: bool,
    canonical_delims: bool,
    envelope: bool,
    mllp: bool,
    streaming: bool,
    summary: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    if streaming {
        let file = fs::File::open(input)?;
        let reader = std::io::BufReader::new(file);
        let mut parser = StreamParser::new(reader);
        let mut message_count = 0;
        let mut event_count = 0;

        while let Ok(Some(event)) = parser.next_event() {
            event_count += 1;
            if matches!(event, Event::StartMessage { .. }) {
                message_count += 1;
            }

            if json {
                let event_json = match &event {
                    Event::StartMessage { delims } => serde_json::json!({
                        "event": "start_message",
                        "delims": {
                            "field": delims.field.to_string(),
                            "comp": delims.comp.to_string(),
                            "rep": delims.rep.to_string(),
                            "esc": delims.esc.to_string(),
                            "sub": delims.sub.to_string(),
                        }
                    }),
                    Event::Segment { id } => serde_json::json!({
                        "event": "segment",
                        "id": String::from_utf8_lossy(id)
                    }),
                    Event::Field { num, raw } => serde_json::json!({
                        "event": "field",
                        "num": num,
                        "raw": String::from_utf8_lossy(raw)
                    }),
                    Event::EndMessage => serde_json::json!({
                        "event": "end_message"
                    }),
                };
                println!("{}", serde_json::to_string(&event_json)?);
            } else {
                match event {
                    Event::StartMessage { delims } => println!(
                        "--- Message {} Start (delims: {:?}) ---",
                        message_count, delims
                    ),
                    Event::Segment { id } => println!("Segment: {}", String::from_utf8_lossy(&id)),
                    Event::Field { num, raw } => {
                        println!("  Field {}: {}", num, String::from_utf8_lossy(&raw));
                    }
                    Event::EndMessage => println!("--- Message End ---"),
                }
            }
        }

        if summary {
            println!("\nStreaming Parse Summary:");
            println!("  Input file: {:?}", input);
            println!("  Messages: {}", message_count);
            println!("  Total events: {}", event_count);
            display_performance_stats(&monitor);
        }
        return Ok(());
    }

    // Read the input file
    let contents = fs::read(input)?;
    let file_size = contents.len();

    let read_time = monitor.elapsed();
    monitor.record_metric("File read", read_time);

    // Parse the HL7 message
    let message = if mllp {
        parse_mllp(&contents)?
    } else {
        parse(&contents)?
    };

    let parse_time = monitor.elapsed() - read_time;
    monitor.record_metric("Message parsing", parse_time);

    // Count segments
    let segment_count = message.segments.len();

    // Handle output based on flags
    if canonical_delims {
        // Output with canonical delimiters (|^~\&)
        // Normalize the raw bytes with canonical delimiters
        let original_bytes = write(&message);
        let output_bytes = normalize(&original_bytes, true)?;

        if envelope {
            // Wrap in MLLP envelope
            let mllp_bytes = wrap_mllp(&output_bytes);
            std::io::stdout().write_all(&mllp_bytes)?;
        } else {
            std::io::stdout().write_all(&output_bytes)?;
        }
    } else if envelope {
        // Output with original delimiters but wrapped in MLLP envelope
        let output_bytes = write(&message);
        let mllp_bytes = wrap_mllp(&output_bytes);
        std::io::stdout().write_all(&mllp_bytes)?;
    } else {
        // Default JSON output
        let json_value = to_json(&message);
        let json_conversion_time = monitor.elapsed() - read_time - parse_time;
        monitor.record_metric("JSON conversion", json_conversion_time);

        // Output JSON
        if json {
            println!("{}", serde_json::to_string_pretty(&json_value)?);
        } else {
            println!("{}", serde_json::to_string(&json_value)?);
        }
    }

    let output_time = monitor.elapsed() - read_time - parse_time;
    monitor.record_metric("Output", output_time);

    // Show summary if requested
    if summary {
        println!();
        println!("Parse Summary:");
        println!("  Input file: {:?}", input);
        println!("  File size: {} bytes", file_size);
        println!("  Segments: {}", segment_count);
        println!("  Streaming mode: {}", streaming);
        println!("  Canonical delimiters: {}", canonical_delims);
        println!("  MLLP envelope: {}", envelope);
        println!(
            "  Delimiters: |^~\\& (field={} comp={} rep={} esc={} sub={})",
            message.delims.field,
            message.delims.comp,
            message.delims.rep,
            message.delims.esc,
            message.delims.sub
        );
        display_performance_stats(&monitor);
    }

    Ok(())
}

fn norm_command(
    input: &PathBuf,
    canonical_delims: bool,
    output: &Option<PathBuf>,
    mllp_in: bool,
    mllp_out: bool,
    summary: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    // Read the input file
    let contents = fs::read(input)?;
    let input_file_size = contents.len();

    let read_time = monitor.elapsed();
    monitor.record_metric("File read", read_time);

    // Parse the HL7 message
    let message = if mllp_in {
        parse_mllp(&contents)?
    } else {
        parse(&contents)?
    };

    let parse_time = monitor.elapsed() - read_time;
    monitor.record_metric("Message parsing", parse_time);

    // Count segments before normalization
    let segment_count = message.segments.len();

    // Normalize the message
    let original_bytes = write(&message);
    let normalized_bytes = if canonical_delims {
        // Use core normalization for canonical delimiters
        normalize(&original_bytes, true)?
    } else {
        original_bytes
    };

    let normalize_time = monitor.elapsed() - read_time - parse_time;
    monitor.record_metric("Message normalization", normalize_time);

    // Add MLLP framing if requested
    let output_bytes = if mllp_out {
        wrap_mllp(&normalized_bytes)
    } else {
        normalized_bytes
    };

    let mllp_time = monitor.elapsed() - read_time - parse_time - normalize_time;
    monitor.record_metric("MLLP processing", mllp_time);

    // Write to output file or stdout
    if let Some(output_path) = output {
        fs::write(output_path, &output_bytes)?;
        if summary {
            let write_time =
                monitor.elapsed() - read_time - parse_time - normalize_time - mllp_time;
            monitor.record_metric("File write", write_time);

            println!();
            println!("Normalize Summary:");
            println!("  Input file: {:?}", input);
            println!("  Output file: {:?}", output_path);
            println!("  Input size: {} bytes", input_file_size);
            println!("  Output size: {} bytes", output_bytes.len());
            println!("  Segments: {}", segment_count);
            println!("  Canonical delimiters: {}", canonical_delims);
            println!("  MLLP output: {}", mllp_out);
            display_performance_stats(&monitor);
        }
    } else {
        std::io::stdout().write_all(&output_bytes)?;
        if summary {
            let write_time =
                monitor.elapsed() - read_time - parse_time - normalize_time - mllp_time;
            monitor.record_metric("Output write", write_time);

            println!();
            println!("Normalize Summary:");
            println!("  Input file: {:?}", input);
            println!("  Output: stdout");
            println!("  Input size: {} bytes", input_file_size);
            println!("  Output size: {} bytes", output_bytes.len());
            println!("  Segments: {}", segment_count);
            println!("  Canonical delimiters: {}", canonical_delims);
            println!("  MLLP output: {}", mllp_out);
            display_performance_stats(&monitor);
        }
    }

    Ok(())
}

fn val_command(
    input: &PathBuf,
    profile: &PathBuf,
    mllp: bool,
    detailed: bool,
    report: &ReportFormat,
    summary: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    // Read the HL7 message file
    let contents = fs::read(input)?;
    let file_size = contents.len();

    let read_time = monitor.elapsed();
    monitor.record_metric("File read", read_time);

    // Parse the HL7 message
    let message = if mllp {
        parse_mllp(&contents)?
    } else {
        parse(&contents)?
    };

    let parse_time = monitor.elapsed() - read_time;
    monitor.record_metric("Message parsing", parse_time);

    // Read the profile YAML file
    let profile_yaml = fs::read_to_string(profile)?;

    let read_profile_time = monitor.elapsed() - read_time - parse_time;
    monitor.record_metric("Profile read", read_profile_time);

    // Load the profile
    let loaded_profile = load_profile(&profile_yaml)?;

    let load_profile_time = monitor.elapsed() - read_time - parse_time - read_profile_time;
    monitor.record_metric("Profile loading", load_profile_time);

    // Validate the message
    let results = validate(&message, &loaded_profile);

    let validation_time =
        monitor.elapsed() - read_time - parse_time - read_profile_time - load_profile_time;
    monitor.record_metric("Message validation", validation_time);

    // Build validation report
    let validation_report = ValidationReport {
        input_file: input.to_string_lossy().to_string(),
        profile_file: profile.to_string_lossy().to_string(),
        file_size,
        segment_count: message.segments.len(),
        is_valid: results.is_empty(),
        issue_count: results.len(),
        issues: results.iter().map(|r| format!("{:?}", r)).collect(),
    };

    // Output based on report format
    match report {
        ReportFormat::Json => {
            let json_output = serde_json::to_string_pretty(&validation_report)?;
            println!("{}", json_output);
        }
        ReportFormat::Yaml => {
            let yaml_output = serde_yaml::to_string(&validation_report)?;
            println!("{}", yaml_output);
        }
        ReportFormat::Text => {
            // Print validation results in text format
            if results.is_empty() {
                println!("Validation passed: No issues found");
            } else if detailed {
                println!("Validation issues found:");
                for result in &results {
                    println!("  - {:?}", result);
                }
            } else {
                println!("Validation failed: {} issues found", results.len());
            }
        }
    }

    // Show summary if requested (only for text format to avoid mixing output)
    if summary && *report == ReportFormat::Text {
        println!();
        println!("Validation Summary:");
        println!("  Input file: {:?}", input);
        println!("  Profile file: {:?}", profile);
        println!("  File size: {} bytes", file_size);
        println!("  Segments: {}", message.segments.len());
        println!("  Issues found: {}", results.len());
        display_performance_stats(&monitor);
    }

    // Exit with error code if validation failed
    if !results.is_empty() {
        std::process::exit(1);
    }

    Ok(())
}

/// Validation report structure for JSON/YAML output
#[derive(serde::Serialize)]
struct ValidationReport {
    input_file: String,
    profile_file: String,
    file_size: usize,
    segment_count: usize,
    is_valid: bool,
    issue_count: usize,
    issues: Vec<String>,
}

/// Statistics report structure for JSON/YAML output
#[derive(serde::Serialize)]
struct StatsReport {
    input_file: String,
    file_size: usize,
    segment_count: usize,
    segments: Vec<SegmentStats>,
    field_distributions: Option<Vec<FieldDistribution>>,
}

#[derive(serde::Serialize)]
struct SegmentStats {
    segment_id: String,
    count: usize,
}

#[derive(serde::Serialize)]
struct FieldDistribution {
    path: String,
    unique_values: usize,
    sample_values: Vec<String>,
}

/// Collect statistics from an HL7 message
fn collect_stats(message: &Message, distributions: bool) -> StatsReport {
    // Collect segment statistics
    let mut segment_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    for segment in &message.segments {
        *segment_counts
            .entry(segment.id_str().to_string())
            .or_insert(0) += 1;
    }

    let segments: Vec<SegmentStats> = segment_counts
        .into_iter()
        .map(|(id, count)| SegmentStats {
            segment_id: id,
            count,
        })
        .collect();

    // Collect field distributions if requested
    let field_distributions = if distributions {
        let mut dists: Vec<FieldDistribution> = Vec::new();

        // Sample some common fields for distribution analysis
        for segment in &message.segments {
            let segment_id = segment.id_str();

            // Get field values (simplified - just first few fields)
            for (field_idx, field) in segment.fields.iter().enumerate().take(5) {
                if field_idx == 0 {
                    continue; // Skip segment ID field
                }

                let path = format!("{}.{}", segment_id, field_idx);
                // Get the first text value from the field
                let value = field.first_text().unwrap_or("").to_string();

                // Check if we already have this path
                if let Some(existing) = dists.iter_mut().find(|d| d.path == path) {
                    if !existing.sample_values.contains(&value) && existing.sample_values.len() < 10
                    {
                        existing.sample_values.push(value);
                    }
                    existing.unique_values = existing.sample_values.len();
                } else {
                    dists.push(FieldDistribution {
                        path,
                        unique_values: 1,
                        sample_values: vec![value],
                    });
                }
            }
        }

        Some(dists)
    } else {
        None
    };

    StatsReport {
        input_file: String::new(), // To be filled by caller
        file_size: 0,              // To be filled by caller
        segment_count: message.segments.len(),
        segments,
        field_distributions,
    }
}

/// Format statistics report based on requested format
fn format_stats_report(
    report: &StatsReport,
    format: &ReportFormat,
) -> Result<String, Box<dyn std::error::Error>> {
    match format {
        ReportFormat::Json => Ok(serde_json::to_string_pretty(report)?),
        ReportFormat::Yaml => Ok(serde_yaml::to_string(report)?),
        ReportFormat::Text => {
            let mut output = String::new();
            output.push_str("Message Statistics:\n");
            output.push_str(&format!("  Input file: {}\n", report.input_file));
            output.push_str(&format!("  File size: {} bytes\n", report.file_size));
            output.push_str(&format!("  Total segments: {}\n", report.segment_count));
            output.push('\n');
            output.push_str("Segment breakdown:\n");
            for seg in &report.segments {
                output.push_str(&format!(
                    "  {}: {} occurrence(s)\n",
                    seg.segment_id, seg.count
                ));
            }

            if let Some(dists) = &report.field_distributions {
                output.push('\n');
                output.push_str("Field value distributions:\n");
                for dist in dists {
                    output.push_str(&format!("  {}:\n", dist.path));
                    output.push_str(&format!("    Unique values: {}\n", dist.unique_values));
                    if !dist.sample_values.is_empty() {
                        output.push_str(&format!(
                            "    Sample values: {:?}\n",
                            dist.sample_values.iter().take(5).collect::<Vec<_>>()
                        ));
                    }
                }
            }
            Ok(output)
        }
    }
}

fn stats_command(
    input: &PathBuf,
    mllp: bool,
    distributions: bool,
    format: &ReportFormat,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    // Read the HL7 message file
    let contents = fs::read(input)?;
    let file_size = contents.len();

    let read_time = monitor.elapsed();
    monitor.record_metric("File read", read_time);

    // Parse the HL7 message
    let message = if mllp {
        parse_mllp(&contents)?
    } else {
        parse(&contents)?
    };

    let parse_time = monitor.elapsed() - read_time;
    monitor.record_metric("Message parsing", parse_time);

    // Collect statistics
    let mut stats_report = collect_stats(&message, distributions);
    stats_report.input_file = input.to_string_lossy().to_string();
    stats_report.file_size = file_size;

    // Format and output report
    let report_output = format_stats_report(&stats_report, format)?;
    println!("{}", report_output);

    let output_time = monitor.elapsed() - read_time - parse_time;
    monitor.record_metric("Output", output_time);

    Ok(())
}

fn ack_command(
    input: &PathBuf,
    mode: &AckMode,
    code: &AckCode,
    mllp_in: bool,
    mllp_out: bool,
    summary: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    // Read the HL7 message file
    let contents = fs::read(input)?;
    let input_file_size = contents.len();

    let read_time = monitor.elapsed();
    monitor.record_metric("File read", read_time);

    // Parse the HL7 message
    let message = if mllp_in {
        parse_mllp(&contents)?
    } else {
        parse(&contents)?
    };

    let parse_time = monitor.elapsed() - read_time;
    monitor.record_metric("Message parsing", parse_time);

    // Convert ACK code
    let ack_code = match code {
        AckCode::AA => GenAckCode::AA,
        AckCode::AE => GenAckCode::AE,
        AckCode::AR => GenAckCode::AR,
        AckCode::CA => GenAckCode::CA,
        AckCode::CE => GenAckCode::CE,
        AckCode::CR => GenAckCode::CR,
    };

    // Generate ACK
    let ack_message = ack(&message, ack_code)?; // Remove the extra parameter

    let ack_generation_time = monitor.elapsed() - read_time - parse_time;
    monitor.record_metric("ACK generation", ack_generation_time);

    // Write ACK message
    let ack_bytes = if mllp_out {
        write_mllp(&ack_message)
    } else {
        write(&ack_message)
    };

    let mllp_processing_time = monitor.elapsed() - read_time - parse_time - ack_generation_time;
    monitor.record_metric("MLLP processing", mllp_processing_time);

    std::io::stdout().write_all(&ack_bytes)?;

    // Show summary if requested
    if summary {
        let write_time =
            monitor.elapsed() - read_time - parse_time - ack_generation_time - mllp_processing_time;
        monitor.record_metric("Output write", write_time);

        println!();
        println!("ACK Generation Summary:");
        println!("  Input file: {:?}", input);
        println!("  Mode: {:?}", mode);
        println!("  Code: {:?}", code);
        println!("  Input size: {} bytes", input_file_size);
        println!("  Output size: {} bytes", ack_bytes.len());
        println!("  Segments in original: {}", message.segments.len());
        println!("  Segments in ACK: {}", ack_message.segments.len());
        println!("  MLLP input: {}", mllp_in);
        println!("  MLLP output: {}", mllp_out);
        display_performance_stats(&monitor);
    }

    Ok(())
}

/// Interactive mode for HL7 v2 processing
fn interactive_mode() -> Result<(), Box<dyn std::error::Error>> {
    println!("HL7 v2 Toolkit - Interactive Mode");
    println!("Type 'help' for available commands or 'exit' to quit.");
    println!();

    loop {
        print!("hl7v2> ");
        std::io::stdout().flush()?;

        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        let input = input.trim();

        match input {
            "exit" | "quit" => {
                println!("Goodbye!");
                break;
            }
            "help" => {
                println!("Available commands:");
                println!("  parse <file> [options]  - Parse an HL7 message");
                println!("  norm <file> [options]   - Normalize an HL7 message");
                println!("  val <file> <profile>    - Validate an HL7 message");
                println!("  ack <file> [options]    - Generate an ACK for an HL7 message");
                println!("  gen <profile> [options] - Generate synthetic messages");
                println!("  help                    - Show this help message");
                println!("  exit|quit               - Exit interactive mode");
                println!();
            }
            _ => {
                if input.starts_with("parse ") {
                    handle_parse_command(input)?;
                } else if input.starts_with("norm ") {
                    handle_norm_command(input)?;
                } else if input.starts_with("val ") {
                    handle_val_command(input)?;
                } else if input.starts_with("ack ") {
                    handle_ack_command(input)?;
                } else if input.starts_with("gen ") {
                    handle_gen_command(input)?;
                } else if !input.is_empty() {
                    println!("Unknown command. Type 'help' for available commands.");
                }
            }
        }
    }

    Ok(())
}

/// Handle parse command in interactive mode
fn handle_parse_command(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 2 {
        println!(
            "Usage: parse <file> [--json] [--canonical-delims] [--envelope] [--mllp] [--streaming] [--summary]"
        );
        return Ok(());
    }

    let file_path = PathBuf::from(parts[1]);
    let mut json = false;
    let mut canonical_delims = false;
    let mut envelope = false;
    let mut mllp = false;
    let mut streaming = false;
    let mut summary = false;

    for part in &parts[2..] {
        match *part {
            "--json" => json = true,
            "--canonical-delims" => canonical_delims = true,
            "--envelope" => envelope = true,
            "--mllp" => mllp = true,
            "--streaming" => streaming = true,
            "--summary" => summary = true,
            _ => println!("Unknown option: {}", part),
        }
    }

    parse_command(
        &file_path,
        json,
        canonical_delims,
        envelope,
        mllp,
        streaming,
        summary,
    )
}

/// Handle norm command in interactive mode
fn handle_norm_command(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 2 {
        println!("Usage: norm <file> [--canonical-delims] [--mllp-in] [--mllp-out] [--summary]");
        return Ok(());
    }

    let file_path = PathBuf::from(parts[1]);
    let mut canonical_delims = false;
    let mut mllp_in = false;
    let mut mllp_out = false;
    let mut summary = false;

    for part in &parts[2..] {
        match *part {
            "--canonical-delims" => canonical_delims = true,
            "--mllp-in" => mllp_in = true,
            "--mllp-out" => mllp_out = true,
            "--summary" => summary = true,
            _ => println!("Unknown option: {}", part),
        }
    }

    norm_command(
        &file_path,
        canonical_delims,
        &None,
        mllp_in,
        mllp_out,
        summary,
    )
}

/// Handle val command in interactive mode
fn handle_val_command(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 3 {
        println!(
            "Usage: val <file> <profile> [--mllp] [--detailed] [--report <text|json|yaml>] [--summary]"
        );
        return Ok(());
    }

    let file_path = PathBuf::from(parts[1]);
    let profile_path = PathBuf::from(parts[2]);
    let mut mllp = false;
    let mut detailed = false;
    let mut summary = false;
    let mut report = ReportFormat::Text;

    let mut i = 3;
    while i < parts.len() {
        match parts[i] {
            "--mllp" => {
                mllp = true;
                i += 1;
            }
            "--detailed" => {
                detailed = true;
                i += 1;
            }
            "--summary" => {
                summary = true;
                i += 1;
            }
            "--report" => {
                if i + 1 < parts.len() {
                    report = match parts[i + 1] {
                        "json" => ReportFormat::Json,
                        "yaml" => ReportFormat::Yaml,
                        _ => ReportFormat::Text,
                    };
                    i += 2;
                } else {
                    println!("Missing report format value");
                    return Ok(());
                }
            }
            _ => {
                println!("Unknown option: {}", parts[i]);
                i += 1;
            }
        }
    }

    val_command(&file_path, &profile_path, mllp, detailed, &report, summary)
}

/// Handle ack command in interactive mode
fn handle_ack_command(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 2 {
        println!(
            "Usage: ack <file> [--mode <original|enhanced>] [--code <AA|AE|AR|CA|CE|CR>] [--mllp-in] [--mllp-out] [--summary]"
        );
        return Ok(());
    }

    let file_path = PathBuf::from(parts[1]);
    let mut mode = AckMode::Original;
    let mut code = AckCode::AA;
    let mut mllp_in = false;
    let mut mllp_out = false;
    let mut summary = false;

    let mut i = 2;
    while i < parts.len() {
        match parts[i] {
            "--mode" => {
                if i + 1 < parts.len() {
                    mode = match parts[i + 1] {
                        "original" => AckMode::Original,
                        "enhanced" => AckMode::Enhanced,
                        _ => {
                            println!("Invalid mode: {}", parts[i + 1]);
                            return Ok(());
                        }
                    };
                    i += 2;
                } else {
                    println!("Missing mode value");
                    return Ok(());
                }
            }
            "--code" => {
                if i + 1 < parts.len() {
                    code = match parts[i + 1] {
                        "AA" => AckCode::AA,
                        "AE" => AckCode::AE,
                        "AR" => AckCode::AR,
                        "CA" => AckCode::CA,
                        "CE" => AckCode::CE,
                        "CR" => AckCode::CR,
                        _ => {
                            println!("Invalid code: {}", parts[i + 1]);
                            return Ok(());
                        }
                    };
                    i += 2;
                } else {
                    println!("Missing code value");
                    return Ok(());
                }
            }
            "--mllp-in" => {
                mllp_in = true;
                i += 1;
            }
            "--mllp-out" => {
                mllp_out = true;
                i += 1;
            }
            "--summary" => {
                summary = true;
                i += 1;
            }
            _ => {
                println!("Unknown option: {}", parts[i]);
                return Ok(());
            }
        }
    }

    ack_command(&file_path, &mode, &code, mllp_in, mllp_out, summary)
}

/// Handle gen command in interactive mode
fn handle_gen_command(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.len() < 2 {
        println!(
            "Usage: gen <profile> [--seed <number>] [--count <number>] [--out <directory>] [--stats]"
        );
        return Ok(());
    }

    let profile_path = PathBuf::from(parts[1]);
    let mut seed = 42;
    let mut count = 1;
    let mut out = PathBuf::from("output");
    let mut stats = false;

    let mut i = 2;
    while i < parts.len() {
        match parts[i] {
            "--seed" => {
                if i + 1 < parts.len() {
                    seed = parts[i + 1].parse().unwrap_or(42);
                    i += 2;
                } else {
                    println!("Missing seed value");
                    return Ok(());
                }
            }
            "--count" => {
                if i + 1 < parts.len() {
                    count = parts[i + 1].parse().unwrap_or(1);
                    i += 2;
                } else {
                    println!("Missing count value");
                    return Ok(());
                }
            }
            "--out" => {
                if i + 1 < parts.len() {
                    out = PathBuf::from(parts[i + 1]);
                    i += 2;
                } else {
                    println!("Missing output directory");
                    return Ok(());
                }
            }
            "--stats" => {
                stats = true;
                i += 1;
            }
            _ => {
                println!("Unknown option: {}", parts[i]);
                return Ok(());
            }
        }
    }

    gen_command(&profile_path, seed, count, &out, stats)
}

fn gen_command(
    profile: &PathBuf,
    seed: u64,
    count: usize,
    out: &PathBuf,
    stats: bool,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut monitor = monitor::PerformanceMonitor::new();

    // Read the template YAML file
    let template_yaml = fs::read_to_string(profile)?;

    let read_template_time = monitor.elapsed();
    monitor.record_metric("Template read", read_template_time);

    // Parse the template from YAML
    let template: Template = serde_yaml::from_str(&template_yaml)?;

    let parse_template_time = monitor.elapsed() - read_template_time;
    monitor.record_metric("Template parsing", parse_template_time);

    // Generate messages
    let messages = generate(&template, seed, count)?;

    let generation_time = monitor.elapsed() - read_template_time - parse_template_time;
    monitor.record_metric("Message generation", generation_time);

    // Create output directory if it doesn't exist
    fs::create_dir_all(out)?;

    let create_dir_time =
        monitor.elapsed() - read_template_time - parse_template_time - generation_time;
    monitor.record_metric("Directory creation", create_dir_time);

    // Write each message to a separate file
    let mut written_files = 0;
    for (i, message) in messages.iter().enumerate() {
        let filename = out.join(format!("message_{:03}.hl7", i + 1));
        let message_bytes = write(message);
        fs::write(&filename, &message_bytes)?;
        if stats {
            println!("Generated message written to: {:?}", filename);
        }
        written_files += 1;
    }

    let write_time = monitor.elapsed()
        - read_template_time
        - parse_template_time
        - generation_time
        - create_dir_time;
    monitor.record_metric("File writing", write_time);

    if stats {
        println!("Successfully generated {} messages", messages.len());
    }

    // Show stats if requested
    if stats {
        println!();
        println!("Generation Statistics:");
        println!("  Template file: {:?}", profile);
        println!("  Seed: {}", seed);
        println!("  Count: {}", count);
        println!("  Output directory: {:?}", out);
        println!("  Messages generated: {}", messages.len());
        println!("  Files written: {}", written_files);
        display_performance_stats(&monitor);
    }

    Ok(())
}