copybook-cli 0.4.3

CLI for parsing, decoding, encoding, and verifying COBOL copybook data.
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
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
#![deny(clippy::unwrap_used, clippy::expect_used)]
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Command-line interface for copybook-rs
//!
//! This binary provides a user-friendly CLI for parsing copybooks and
//! converting mainframe data files.

use crate::exit_codes::ExitCode;
use anyhow::{Error as AnyhowError, anyhow};
use clap::error::ErrorKind as ClapErrorKind;
use clap::{Args, ColorChoice, Parser, Subcommand, ValueEnum};
use copybook_codec::{
    Codepage, FloatFormat, JsonNumberMode, RawMode, RecordFormat, UnmappablePolicy,
};
use copybook_core::{Error as CoreError, Feature, FeatureCategory, FeatureFlags};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::error::Error as StdError;
use std::io::{self, ErrorKind, Write};
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::process::ExitCode as ProcessExitCode;
use std::str::FromStr;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::Level;
use tracing_subscriber::EnvFilter;

#[cfg(feature = "metrics")]
use std::net::SocketAddr;

#[cfg(feature = "metrics")]
use std::sync::Once;

static INVOCATION_ID: OnceLock<String> = OnceLock::new();

/// Bump when log schema fields change.
pub const LOG_SCHEMA: u8 = 1;

/// Diagnostic sub-codes for structured CLI warnings and policy notices.
pub mod subcode {
    /// Policy compatibility warning: `--preferred-zoned-encoding` without preservation.
    ///
    /// Reserved ranges:
    /// - `2xx`: deprecations
    /// - `4xx`: policy compatibility and enforcement (reserved for operator-facing guardrails)
    /// - `5xx`: internal escalations / invariants
    pub const POLICY_PREFERRED_WITHOUT_PRESERVE: u16 = 401;
}

fn invocation_id() -> &'static str {
    INVOCATION_ID.get_or_init(|| {
        if let Ok(from_env) = std::env::var("COPYBOOK_INVOCATION_ID") {
            return from_env;
        }
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        format!("pid{}-ts{}", std::process::id(), nanos)
    })
}

#[derive(Parser)]
#[command(name = "copybook", color = ColorChoice::Never)]
#[command(about = "Modern COBOL copybook parser and data converter")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose logging
    #[arg(short, long)]
    verbose: bool,

    /// Enforce policy checks. Precedence: --strict-policy > --no-strict-policy > `COPYBOOK_STRICT_POLICY`.
    #[arg(
        long,
        action = clap::ArgAction::SetTrue,
        conflicts_with = "no_strict_policy"
    )]
    strict_policy: bool,

    /// Disable strict checks for this run, even if `COPYBOOK_STRICT_POLICY=1`.
    #[arg(
        long = "no-strict-policy",
        action = clap::ArgAction::SetTrue,
        conflicts_with = "strict_policy"
    )]
    no_strict_policy: bool,

    #[cfg(feature = "metrics")]
    #[command(flatten)]
    metrics: MetricsOpts,

    #[command(flatten)]
    feature_flags: FeatureFlagOpts,
}

struct BrokenPipeSafeStderr(std::io::Stderr);

impl Write for BrokenPipeSafeStderr {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.0.write(buf) {
            Ok(written) => Ok(written),
            Err(err) if is_consumer_closed(&err) => Ok(buf.len()),
            Err(err) => Err(err),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.0.flush() {
            Ok(()) => Ok(()),
            Err(err) if is_consumer_closed(&err) => Ok(()),
            Err(err) => Err(err),
        }
    }
}

#[cfg(feature = "metrics")]
#[derive(Args, Debug, Clone)]
pub struct MetricsOpts {
    /// Expose Prometheus metrics at this address (e.g. 0.0.0.0:9300)
    #[arg(long)]
    pub metrics_listen: Option<SocketAddr>,
    /// Optional delay after run completion so scrapes can observe final metrics
    #[arg(long, default_value_t = 0)]
    pub metrics_grace_ms: u64,
}

/// Feature flag options for the CLI
///
/// These options allow runtime control over experimental features,
/// enterprise features, performance optimizations, debug capabilities,
/// and testing hooks.
#[derive(Args, Debug, Clone)]
pub struct FeatureFlagOpts {
    /// Enable specific feature flags (comma-separated)
    ///
    /// Available flags:
    /// - Experimental: `sign_separate`, `renames_r4_r6`, `comp_1`, `comp_2`
    /// - Enterprise: `audit_system`, `sox_compliance`, `hipaa_compliance`, `gdpr_compliance`, `pci_dss_compliance`, `security_monitoring`
    /// - Performance: `advanced_optimization`, `lru_cache`, `parallel_decode`, `zero_copy`
    /// - Debug: `verbose_logging`, `diagnostic_output`, `profiling`, `memory_tracking`
    /// - Testing: `mutation_testing`, `fuzzing_integration`, `coverage_instrumentation`, `property_based_testing`
    ///
    /// Example: --enable-features `sign_separate,verbose_logging`
    #[arg(long, value_delimiter = ',', value_name = "FEATURE")]
    pub enable_features: Vec<String>,

    /// Disable specific feature flags (comma-separated)
    ///
    /// This takes precedence over --enable-features and environment variables.
    ///
    /// Example: --disable-features `lru_cache`
    #[arg(long, value_delimiter = ',', value_name = "FEATURE")]
    pub disable_features: Vec<String>,

    /// Enable all features in a category
    ///
    /// Available categories: `experimental`, `enterprise`, `performance`, `debug`, `testing`
    ///
    /// Example: --enable-category `debug`
    #[arg(long, value_name = "CATEGORY")]
    pub enable_category: Vec<String>,

    /// Disable all features in a category
    ///
    /// Example: --disable-category `experimental`
    #[arg(long, value_name = "CATEGORY")]
    pub disable_category: Vec<String>,

    /// Load feature flags from a configuration file
    ///
    /// The file can be in TOML or JSON format.
    /// TOML format:
    /// ```toml
    /// [feature_flags]
    /// enabled = ["sign_separate", "verbose_logging"]
    /// disabled = ["lru_cache"]
    /// ```
    ///
    /// JSON format:
    /// ```json
    /// {
    ///   "feature_flags": {
    ///     "enabled": ["sign_separate", "verbose_logging"],
    ///     "disabled": ["lru_cache"]
    ///   }
    /// }
    /// ```
    #[arg(long, value_name = "PATH")]
    pub feature_flags_config: Option<PathBuf>,

    /// List all available feature flags and their status
    #[arg(long)]
    pub list_features: bool,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum DialectPreference {
    /// Normative dialect - `min_count` is strictly enforced
    #[value(name = "n")]
    N,
    /// Zero-tolerant dialect - `min_count` is ignored
    #[value(name = "0")]
    Zero,
    /// One-tolerant dialect - `min_count` is clamped to 1
    #[value(name = "1")]
    One,
}

impl From<DialectPreference> for copybook_core::dialect::Dialect {
    #[inline]
    fn from(value: DialectPreference) -> Self {
        match value {
            DialectPreference::N => Self::Normative,
            DialectPreference::Zero => Self::ZeroTolerant,
            DialectPreference::One => Self::OneTolerant,
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum ZonedEncodingPreference {
    /// Prefer default zero policy based on target code page.
    #[value(alias = "preferred-zero")]
    Preferred,
    /// Force ASCII zoned encoding format.
    Ascii,
    /// Force EBCDIC zoned encoding format.
    Ebcdic,
    /// Defer to automatic detection when metadata supplies a format.
    Auto,
}

impl From<ZonedEncodingPreference> for copybook_codec::ZonedEncodingFormat {
    #[inline]
    fn from(value: ZonedEncodingPreference) -> Self {
        match value {
            ZonedEncodingPreference::Preferred | ZonedEncodingPreference::Auto => Self::Auto,
            ZonedEncodingPreference::Ascii => Self::Ascii,
            ZonedEncodingPreference::Ebcdic => Self::Ebcdic,
        }
    }
}

#[derive(Subcommand)]
enum Commands {
    /// Parse copybook and output schema JSON
    #[command(
        after_help = "Comments: inline (*>) allowed by default; use --strict-comments to disable."
    )]
    Parse {
        /// Copybook file path
        copybook: PathBuf,
        /// Output file (stdout if not specified)
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Enforce normative validation (ODO bounds/order, REDEFINES ambiguity as errors)
        #[arg(long)]
        strict: bool,
        /// Disable inline comments (*>) - enforce COBOL-85 compatibility
        #[arg(long)]
        strict_comments: bool,
        /// Dialect for ODO `min_count` interpretation (n=normative, 0=zero-tolerant, 1=one-tolerant)
        #[arg(long, value_enum)]
        dialect: Option<DialectPreference>,
    },
    /// Inspect copybook and show human-readable layout
    #[command(
        after_help = "Comments: inline (*>) allowed by default; use --strict-comments to disable."
    )]
    Inspect {
        /// Copybook file path
        copybook: PathBuf,
        /// Character encoding
        #[arg(long, default_value = "cp037")]
        codepage: Codepage,
        /// Enforce normative validation (ODO bounds/order, REDEFINES ambiguity as errors)
        #[arg(long)]
        strict: bool,
        /// Disable inline comments (*>) - enforce COBOL-85 compatibility
        #[arg(long)]
        strict_comments: bool,
        /// Dialect for ODO `min_count` interpretation (n=normative, 0=zero-tolerant, 1=one-tolerant)
        #[arg(long, value_enum)]
        dialect: Option<DialectPreference>,
    },
    /// Decode binary data to JSONL
    #[command(
        after_help = "Comments: inline (*>) allowed by default; use --strict-comments to disable.\n\
Zoned policy: override → preserved → preferred.\n\n\
Field Projection:\n\
  Use --select to include specific fields in output (comma-separated or multiple flags).\n\
  Examples:\n\
    --select \"CUSTOMER-ID,BALANCE\"\n\
    --select CUSTOMER-ID --select BALANCE\n\
  ODO counters and parent groups are automatically included."
    )]
    Decode {
        /// Copybook file path
        copybook: PathBuf,
        /// Input data file path
        input: PathBuf,
        /// Output JSONL file path (use "-" for stdout)
        #[arg(short, long)]
        output: PathBuf,
        /// Record format (explicit, no auto-detection)
        #[arg(long)]
        format: RecordFormat,
        /// Character encoding
        #[arg(long, default_value = "cp037")]
        codepage: Codepage,
        /// JSON number mode
        #[arg(long, default_value = "lossless")]
        json_number: JsonNumberMode,
        /// Enable strict mode (default: false for lenient mode)
        #[arg(long, default_value = "false")]
        strict: bool,
        /// Maximum errors before stopping
        #[arg(long)]
        max_errors: Option<u64>,
        /// Stop on first error (default: false)
        #[arg(long, default_value = "false")]
        fail_fast: bool,
        /// Emit FILLER fields
        #[arg(long)]
        emit_filler: bool,
        /// Emit metadata
        #[arg(long)]
        emit_meta: bool,
        /// Raw data capture mode
        #[arg(long, default_value = "off")]
        emit_raw: RawMode,
        /// Unmappable character policy
        #[arg(long, default_value = "error")]
        on_decode_unmappable: UnmappablePolicy,
        /// Number of threads for parallel processing
        #[arg(long, default_value = "1")]
        threads: usize,
        /// Disable inline comments (*>) - enforce COBOL-85 compatibility
        #[arg(long)]
        strict_comments: bool,
        /// Preserve zoned encoding detected during decode; wins over preferred.
        #[arg(long)]
        preserve_zoned_encoding: bool,
        /// Preferred zoned encoding when neither preserved nor overridden.
        /// Example: prefer EBCDIC 'F' zero punch for zero.
        #[arg(long, value_enum, default_value_t = ZonedEncodingPreference::Preferred)]
        preferred_zoned_encoding: ZonedEncodingPreference,
        /// COMP-1/COMP-2 floating-point binary format.
        #[arg(long, value_enum, default_value = "ieee-be")]
        float_format: FloatFormat,
        /// Dialect for ODO `min_count` interpretation (n=normative, 0=zero-tolerant, 1=one-tolerant)
        #[arg(long, value_enum)]
        dialect: Option<DialectPreference>,
        /// Select specific fields to include in output (comma-separated or multiple flags)
        /// Automatically includes ODO counters and parent groups for structure
        #[arg(long, value_name = "FIELD[,FIELD...]")]
        select: Vec<String>,
    },
    /// Encode JSONL to binary data
    #[command(
        after_help = "Comments: inline (*>) allowed by default; use --strict-comments to disable.\n\
Zoned policy: override → preserved → preferred.\n\n\
Field Projection:\n\
  Use --select to validate only specific fields during encoding (comma-separated or multiple flags).\n\
  Examples:\n\
    --select \"CUSTOMER-ID,BALANCE\"\n\
    --select CUSTOMER-ID --select BALANCE\n\
  ODO counters and parent groups are automatically included."
    )]
    Encode {
        /// Copybook file path
        copybook: PathBuf,
        /// Input JSONL file path
        input: PathBuf,
        /// Output binary file path (use "-" for stdout)
        #[arg(short, long)]
        output: PathBuf,
        /// Record format (explicit, no auto-detection)
        #[arg(long)]
        format: RecordFormat,
        /// Character encoding
        #[arg(long, default_value = "cp037")]
        codepage: Codepage,
        /// Use raw data when available
        #[arg(long)]
        use_raw: bool,
        /// Enable BLANK WHEN ZERO encoding
        #[arg(long)]
        bwz_encode: bool,
        /// Enable strict mode (default: false for lenient mode)
        #[arg(long, default_value = "false")]
        strict: bool,
        /// Maximum errors before stopping
        #[arg(long)]
        max_errors: Option<u64>,
        /// Stop on first error (default: true)
        #[arg(long, default_value = "true")]
        fail_fast: bool,
        /// Number of threads for parallel processing
        #[arg(long, default_value = "1")]
        threads: usize,
        /// Coerce non-string JSON numbers to strings before encoding
        #[arg(long)]
        coerce_numbers: bool,
        /// Disable inline comments (*>) - enforce COBOL-85 compatibility
        #[arg(long)]
        strict_comments: bool,
        /// Force zoned encoding format (ascii|ebcdic), ignoring preserved/preferred.
        #[arg(long, value_enum)]
        zoned_encoding_override: Option<copybook_codec::ZonedEncodingFormat>,
        /// COMP-1/COMP-2 floating-point binary format.
        #[arg(long, value_enum, default_value = "ieee-be")]
        float_format: FloatFormat,
        /// Dialect for ODO `min_count` interpretation (n=normative, 0=zero-tolerant, 1=one-tolerant)
        #[arg(long, value_enum)]
        dialect: Option<DialectPreference>,
        /// Select specific fields to validate during encoding (comma-separated or multiple flags)
        /// Automatically includes ODO counters and parent groups for structure
        #[arg(long, value_name = "FIELD[,FIELD...]")]
        select: Vec<String>,
    },
    /// Enterprise audit system for regulatory compliance
    #[cfg(feature = "audit")]
    #[command(
        after_help = "Enterprise audit capabilities including SOX, HIPAA, GDPR compliance validation, \
                      performance auditing, security monitoring, and data lineage tracking.\n\n\
                      Examples:\n\
                      copybook audit validate --compliance sox,gdpr schema.cpy\n\
                      copybook audit report --include-performance schema.cpy data.bin -o report.json\n\
                      copybook audit lineage source.cpy --source-system mainframe -o lineage.json"
    )]
    Audit {
        #[command(flatten)]
        audit_command: crate::commands::audit::AuditCommand,
    },

    /// Verify data file structure
    #[command(after_help = "\
Exit codes:
  0 = valid data, no errors
  3 = validation errors found
  2 = fatal error (I/O, schema)
Report schema: docs/VERIFY_REPORT.schema.json

Comments: inline (*>) allowed by default; use --strict-comments to disable.

Field Projection:
  Use --select to validate only specific fields (comma-separated or multiple flags).
  Examples:
    --select \"CUSTOMER-ID,BALANCE\"
    --select CUSTOMER-ID --select BALANCE
  ODO counters and parent groups are automatically included.")]
    Verify {
        /// Copybook file path
        copybook: PathBuf,
        /// Input data file path
        input: PathBuf,
        /// Verification report output
        #[arg(long)]
        report: Option<PathBuf>,
        /// Record format (explicit, no auto-detection)
        #[arg(long)]
        format: RecordFormat,
        /// Character encoding
        #[arg(long, default_value = "cp037")]
        codepage: Codepage,
        /// Enable strict mode validation
        #[arg(long)]
        strict: bool,
        /// Maximum errors before stopping
        #[arg(long)]
        max_errors: Option<u64>,
        /// Number of sample records to include in report
        #[arg(long, default_value = "5")]
        sample: Option<u32>,
        /// Disable inline comments (*>) - enforce COBOL-85 compatibility
        #[arg(long)]
        strict_comments: bool,
        /// Dialect for ODO `min_count` interpretation (n=normative, 0=zero-tolerant, 1=one-tolerant)
        #[arg(long, value_enum)]
        dialect: Option<DialectPreference>,
        /// Select specific fields to validate (comma-separated or multiple flags)
        /// Automatically includes ODO counters and parent groups for structure
        #[arg(long, value_name = "FIELD[,FIELD...]")]
        select: Vec<String>,
    },
    /// Display COBOL support matrix or check copybook compatibility
    Support {
        #[command(flatten)]
        args: crate::commands::support::SupportArgs,
    },
    /// Determinism validation for encode/decode operations
    #[command(after_help = "\
Exit codes:
  0 = deterministic (hashes match)
  2 = non-deterministic (drift detected)
  3 = codec/usage error (processing failure)

Output formats:
  human = Default human-readable output with diff table
  json  = Structured JSON for CI integration

Comments: inline (*>) allowed by default; use --strict-comments to disable.")]
    Determinism {
        #[command(flatten)]
        command: crate::commands::determinism::DeterminismCommand,
    },
}

fn main() -> ProcessExitCode {
    match std::panic::catch_unwind(AssertUnwindSafe(run)) {
        Ok(Ok(code)) => ProcessExitCode::from(code),
        Ok(Err(err)) => {
            let exit_code = map_error_to_exit_code(&err);
            let stderr_line = format!("{err}\n");
            let _ = write_stderr_all(stderr_line.as_bytes());
            let diagnostics = ExitDiagnostics::new(
                exit_code,
                "copybook CLI terminated with an error",
                "cli_run",
                "", // op_stage will be overridden by emit_exit_diagnostics_stage
                Level::ERROR,
                exit_code.as_i32(),
            )
            .with_io_error(err.downcast_ref::<io::Error>())
            .with_error(Some(err.as_ref()));
            emit_exit_diagnostics_stage(&diagnostics, Stage::Finalize);
            ProcessExitCode::from(exit_code)
        }
        Err(panic_payload) => {
            if panic_caused_by_std_pipe(panic_payload.as_ref()) {
                return ProcessExitCode::from(ExitCode::Ok);
            }
            let panic_msg = extract_panic_message(panic_payload.as_ref());
            let panic_line = format!("panic: {panic_msg}\n");
            let _ = write_stderr_all(panic_line.as_bytes());
            let diagnostics = ExitDiagnostics::new(
                ExitCode::Internal,
                "copybook CLI panicked",
                "panic",
                "", // op_stage will be overridden by emit_exit_diagnostics_stage
                Level::ERROR,
                ExitCode::Internal.as_i32(),
            );
            emit_exit_diagnostics_stage(&diagnostics, Stage::Panic);
            ProcessExitCode::from(ExitCode::Internal)
        }
    }
}

#[allow(clippy::too_many_lines)]
fn run() -> anyhow::Result<ExitCode> {
    #[allow(clippy::panic)]
    if std::env::var("COPYBOOK_TEST_PANIC")
        .map(|v| v == "1")
        .unwrap_or(false)
    {
        panic!("COPYBOOK_TEST_PANIC triggered");
    }

    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let kind = err.kind();
            let _ = err.print();
            if matches!(
                kind,
                ClapErrorKind::DisplayHelp | ClapErrorKind::DisplayVersion
            ) {
                let op = if matches!(kind, ClapErrorKind::DisplayVersion) {
                    "version"
                } else {
                    "help"
                };
                let diagnostics = ExitDiagnostics::new(
                    ExitCode::Ok,
                    "completed",
                    op,
                    "", // op_stage will be overridden by emit_exit_diagnostics_stage
                    Level::INFO,
                    0,
                );
                emit_exit_diagnostics_stage(&diagnostics, Stage::Finalize);
                return Ok(ExitCode::Ok);
            }
            let exit_code = ExitCode::Encode;
            let message = err.to_string();
            let diagnostics = ExitDiagnostics::new(
                exit_code,
                &message,
                "cli_parse",
                "", // op_stage will be overridden by emit_exit_diagnostics_stage
                Level::ERROR,
                exit_code.as_i32(),
            )
            .with_error(Some(&err));
            emit_exit_diagnostics_stage(&diagnostics, Stage::Parse);
            return Ok(exit_code);
        }
    };

    #[cfg(feature = "metrics")]
    let metrics_opts = cli.metrics.clone();

    #[cfg(feature = "metrics")]
    let metrics_server = metrics_start_if_requested(&metrics_opts)?;

    #[cfg(feature = "metrics")]
    if metrics_server.is_some() {
        describe_metrics_once();
    }

    #[cfg(feature = "metrics")]
    let _metrics_guard = metrics_grace_guard(&metrics_opts);

    // Handle feature flags
    let feature_flags = initialize_feature_flags(&cli.feature_flags)?;

    // Set global feature flags for use by parser
    copybook_core::feature_flags::FeatureFlags::set_global(feature_flags.clone());

    if cli.feature_flags.list_features {
        list_all_features(&feature_flags);
        return Ok(ExitCode::Ok);
    }

    let strict_policy = effective_strict_policy(&cli);
    let verbose = cli.verbose || feature_flags.is_enabled(Feature::VerboseLogging);
    let command = cli.command;

    // Initialize tracing
    let default_directive = if verbose { "debug" } else { "warn" };
    let env_filter =
        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_directive));
    tracing_subscriber::fmt()
        .with_env_filter(env_filter)
        .with_ansi(false)
        .with_writer(|| BrokenPipeSafeStderr(std::io::stderr()))
        .init();

    let help_requested =
        std::env::args_os().any(|arg| arg == "--help" || arg == "-h" || arg == "-?" || arg == "/?");
    let version_requested = std::env::args_os().any(|arg| arg == "--version" || arg == "-V");
    if !(help_requested || version_requested) {
        tracing::info!(
            invocation_id = %invocation_id(),
            version = env!("CARGO_PKG_VERSION"),
            commit = option_env!("GIT_SHA").unwrap_or("unknown"),
            os = std::env::consts::OS,
            arch = std::env::consts::ARCH,
            strict_policy,
            "copybook-cli start"
        );
    }

    let (exit_status, exit_op): (anyhow::Result<ExitCode>, &'static str) = match command {
        Commands::Parse {
            copybook,
            output,
            strict,
            strict_comments,
            dialect,
        } => {
            let effective_dialect = effective_dialect(dialect);
            (
                crate::commands::parse::run(
                    &copybook,
                    output,
                    strict,
                    strict_comments,
                    effective_dialect,
                ),
                "parse",
            )
        }
        Commands::Inspect {
            copybook,
            codepage,
            strict,
            strict_comments,
            dialect,
        } => {
            let effective_dialect = effective_dialect(dialect);
            (
                crate::commands::inspect::run(
                    &copybook,
                    codepage,
                    strict,
                    strict_comments,
                    effective_dialect,
                ),
                "inspect",
            )
        }
        Commands::Decode {
            copybook,
            input,
            output,
            format,
            codepage,
            json_number,
            strict,
            max_errors,
            fail_fast,
            emit_filler,
            emit_meta,
            emit_raw,
            on_decode_unmappable,
            threads,
            strict_comments,
            preserve_zoned_encoding,
            preferred_zoned_encoding: preferred_zoned_encoding_cli,
            float_format,
            dialect,
            select,
        } => {
            let effective_dialect = effective_dialect(dialect);
            (
                crate::commands::decode::run(&crate::commands::decode::DecodeArgs {
                    copybook: &copybook,
                    input: &input,
                    output: &output,
                    format,
                    codepage,
                    json_number,
                    strict,
                    max_errors,
                    fail_fast,
                    emit_filler,
                    emit_meta,
                    emit_raw,
                    on_decode_unmappable,
                    threads,
                    strict_comments,
                    preserve_zoned_encoding,
                    preferred_zoned_encoding: preferred_zoned_encoding_cli.into(),
                    float_format,
                    strict_policy,
                    dialect: effective_dialect.into(),
                    select: &select,
                }),
                "decode",
            )
        }
        Commands::Encode {
            copybook,
            input,
            output,
            format,
            codepage,
            use_raw,
            bwz_encode,
            strict,
            max_errors,
            fail_fast,
            threads,
            coerce_numbers,
            strict_comments,
            zoned_encoding_override,
            float_format,
            dialect,
            select,
        } => {
            let effective_dialect = effective_dialect(dialect);
            (
                crate::commands::encode::run(
                    &copybook,
                    &input,
                    &output,
                    &crate::commands::encode::EncodeCliOptions {
                        format,
                        codepage,
                        use_raw,
                        bwz_encode,
                        strict,
                        max_errors,
                        fail_fast,
                        threads,
                        coerce_numbers,
                        strict_comments,
                        zoned_encoding_override,
                        float_format,
                        dialect: effective_dialect.into(),
                        select: &select,
                    },
                ),
                "encode",
            )
        }
        #[cfg(feature = "audit")]
        Commands::Audit { audit_command } => {
            // Run audit command asynchronously
            let runtime = tokio::runtime::Runtime::new()?;
            (
                runtime
                    .block_on(crate::commands::audit::run(audit_command))
                    .map_err(|err| anyhow!(err)),
                "audit",
            )
        }
        Commands::Verify {
            copybook,
            input,
            report,
            format,
            codepage,
            strict,
            max_errors,
            sample,
            strict_comments,
            dialect,
            select,
        } => {
            let effective_dialect = effective_dialect(dialect);
            let value = max_errors.unwrap_or(10);
            let normalized_max_errors = u32::try_from(value).map_err(|_| {
                anyhow!(
                    "--max-errors must be between 0 and {} (received {value})",
                    u32::MAX
                )
            })?;

            let opts = crate::commands::verify::VerifyOptions {
                format,
                codepage,
                strict,
                max_errors: normalized_max_errors,
                sample: sample.unwrap_or(5),
                strict_comments,
                dialect: effective_dialect.into(),
                select: &select,
            };
            (
                crate::commands::verify::run(&copybook, &input, report, &opts),
                "verify",
            )
        }
        Commands::Support { args } => (crate::commands::support::run(&args), "support"),
        Commands::Determinism { command } => {
            (crate::commands::determinism::run(&command), "determinism")
        }
    };

    #[cfg(feature = "metrics")]
    if let (Err(err), Some((handle, _))) = (&exit_status, &metrics_server) {
        let records_processed = metrics_records_total(handle);
        bump_error_if_pre_run(err, records_processed);
    }

    let status = exit_status?;

    let diagnostics = if status == ExitCode::Ok {
        ExitDiagnostics::new(
            ExitCode::Ok,
            "completed",
            exit_op,
            "", // op_stage will be overridden by emit_exit_diagnostics_stage
            Level::INFO,
            0,
        )
    } else {
        ExitDiagnostics::new(
            status,
            "command completed with non-zero exit code",
            exit_op,
            "", // op_stage will be overridden by emit_exit_diagnostics_stage
            Level::ERROR,
            status.as_i32(),
        )
    };

    let stage = if status == ExitCode::Ok {
        Stage::Finalize
    } else {
        Stage::Execute
    };
    emit_exit_diagnostics_stage(&diagnostics, stage);

    Ok(status)
}

#[cfg(feature = "metrics")]
fn install_prometheus(
    addr: SocketAddr,
) -> anyhow::Result<(
    metrics_exporter_prometheus::PrometheusHandle,
    std::thread::JoinHandle<()>,
)> {
    use metrics_exporter_prometheus::PrometheusBuilder;
    use std::sync::mpsc;

    let (handle_tx, handle_rx) = mpsc::channel();
    let join_handle = {
        let pre_runtime_tx = handle_tx.clone();
        std::thread::spawn(move || {
            let runtime = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(rt) => rt,
                Err(err) => {
                    let _ = pre_runtime_tx.send(Err(anyhow!(
                        "failed to build Tokio runtime for metrics exporter: {err}"
                    )));
                    return;
                }
            };

            runtime.block_on(async move {
                let builder = PrometheusBuilder::new().with_http_listener(addr);
                let (recorder, exporter) = match builder.build() {
                    Ok(pair) => pair,
                    Err(err) => {
                        let _ = handle_tx
                            .send(Err(anyhow!("failed to build Prometheus exporter: {err}")));
                        return;
                    }
                };

                let handle = recorder.handle();
                if let Err(err) = metrics::set_global_recorder(recorder) {
                    let _ = handle_tx
                        .send(Err(anyhow!("failed to install Prometheus recorder: {err}")));
                    return;
                }

                if handle_tx.send(Ok(handle)).is_err() {
                    tracing::warn!(
                        "metrics exporter handle receiver dropped before initialization"
                    );
                    return;
                }

                if let Err(err) = exporter.await {
                    tracing::error!(
                        error = ?err,
                        "metrics exporter terminated unexpectedly"
                    );
                }
            });
        })
    };

    let handle = handle_rx.recv().map_err(|err| {
        anyhow!("failed to receive Prometheus handle from exporter thread: {err}")
    })??;

    Ok((handle, join_handle))
}

#[cfg(feature = "metrics")]
struct MetricsGraceGuard(Option<std::time::Duration>);

#[cfg(feature = "metrics")]
fn metrics_grace_guard(opts: &MetricsOpts) -> MetricsGraceGuard {
    let duration = if opts.metrics_listen.is_some() && opts.metrics_grace_ms > 0 {
        Some(std::time::Duration::from_millis(opts.metrics_grace_ms))
    } else {
        None
    };
    MetricsGraceGuard(duration)
}

#[cfg(feature = "metrics")]
impl Drop for MetricsGraceGuard {
    fn drop(&mut self) {
        if let Some(duration) = self.0.take() {
            std::thread::sleep(duration);
        }
    }
}

#[cfg(feature = "metrics")]
fn metrics_start_if_requested(
    opts: &MetricsOpts,
) -> anyhow::Result<
    Option<(
        metrics_exporter_prometheus::PrometheusHandle,
        std::thread::JoinHandle<()>,
    )>,
> {
    opts.metrics_listen.map(install_prometheus).transpose()
}

#[cfg(feature = "metrics")]
fn metrics_records_total(handle: &metrics_exporter_prometheus::PrometheusHandle) -> Option<f64> {
    let snapshot = handle.render();
    let mut saw_zero_entry = false;

    for line in snapshot.lines() {
        if line.starts_with('#') {
            continue;
        }
        if line.starts_with("copybook_records_total")
            && let Some(value_str) = line.split_whitespace().last()
            && let Ok(value) = value_str.parse::<f64>()
        {
            if value > 0.0 {
                return Some(value);
            }
            if value == 0.0 {
                saw_zero_entry = true;
            }
        }
    }

    if saw_zero_entry { Some(0.0) } else { None }
}

#[cfg(feature = "metrics")]
fn describe_metrics_once() {
    use metrics::{describe_counter, describe_gauge, describe_histogram};

    static METRICS_ONCE: Once = Once::new();

    METRICS_ONCE.call_once(|| {
        describe_counter!(
            "copybook_records_total",
            "Records decoded by the copybook CLI"
        );
        describe_counter!("copybook_bytes_total", "Bytes decoded by the copybook CLI");
        describe_counter!(
            "copybook_decode_errors_total",
            "Decode errors grouped by error family"
        );
        describe_histogram!(
            "copybook_decode_seconds",
            "Decode wall time per file (seconds)"
        );
        describe_gauge!(
            "copybook_throughput_mibps",
            "MiB/s throughput for last completed file"
        );
    });
}

#[cfg(feature = "metrics")]
fn bump_error_if_pre_run(err: &AnyhowError, records_processed: Option<f64>) {
    if records_processed.unwrap_or(0.0) <= f64::EPSILON {
        let dominant = dominant_exit_code(err);
        let family = match dominant {
            ExitCode::Data => ExitCode::Data.tag(),
            ExitCode::Encode => ExitCode::Encode.tag(),
            ExitCode::Format => ExitCode::Format.tag(),
            ExitCode::Internal | ExitCode::Ok | ExitCode::Unknown => ExitCode::Internal.tag(),
        };
        metrics::counter!("copybook_decode_errors_total", "family" => family).increment(1);
    }
}

/// Initialize feature flags from CLI options and environment variables
#[allow(clippy::too_many_lines)]
fn initialize_feature_flags(opts: &FeatureFlagOpts) -> anyhow::Result<FeatureFlags> {
    use std::fs;
    use std::io::Read;

    // Start with defaults from environment
    let mut flags = FeatureFlags::from_env();

    // Load from config file if specified
    if let Some(config_path) = &opts.feature_flags_config {
        let mut content = String::new();
        let mut file = fs::File::open(config_path)
            .map_err(|e| anyhow!("Failed to open feature flags config: {e}"))?;
        file.read_to_string(&mut content)
            .map_err(|e| anyhow!("Failed to read feature flags config: {e}"))?;

        // Try JSON format first
        if let Ok(json_config) = serde_json::from_str::<serde_json::Value>(&content) {
            if let Some(feature_flags) = json_config.get("feature_flags") {
                if let Some(enabled) = feature_flags.get("enabled").and_then(|v| v.as_array()) {
                    for feature_name in enabled {
                        if let Some(name) = feature_name.as_str()
                            && let Ok(feature) = Feature::from_str(name)
                        {
                            flags.enable(feature);
                        }
                    }
                }
                if let Some(disabled) = feature_flags.get("disabled").and_then(|v| v.as_array()) {
                    for feature_name in disabled {
                        if let Some(name) = feature_name.as_str()
                            && let Ok(feature) = Feature::from_str(name)
                        {
                            flags.disable(feature);
                        }
                    }
                }
            }
        } else if let Ok(toml_str) = content.parse::<toml::Value>() {
            // Try TOML format
            if let Some(feature_flags) = toml_str.get("feature_flags") {
                if let Some(enabled) = feature_flags.get("enabled").and_then(|v| v.as_array()) {
                    for feature_name in enabled {
                        if let Some(name) = feature_name.as_str()
                            && let Ok(feature) = Feature::from_str(name)
                        {
                            flags.enable(feature);
                        }
                    }
                }
                if let Some(disabled) = feature_flags.get("disabled").and_then(|v| v.as_array()) {
                    for feature_name in disabled {
                        if let Some(name) = feature_name.as_str()
                            && let Ok(feature) = Feature::from_str(name)
                        {
                            flags.disable(feature);
                        }
                    }
                }
            }
        } else {
            return Err(anyhow!(
                "Failed to parse feature flags config: expected JSON or TOML format"
            ));
        }
    }

    // Process --enable-category flags
    for category_name in &opts.enable_category {
        let category = match category_name.to_lowercase().as_str() {
            "experimental" => FeatureCategory::Experimental,
            "enterprise" => FeatureCategory::Enterprise,
            "performance" => FeatureCategory::Performance,
            "debug" => FeatureCategory::Debug,
            "testing" => FeatureCategory::Testing,
            _ => {
                return Err(anyhow!(
                    "Invalid feature category '{category_name}'. Valid categories: experimental, enterprise, performance, debug, testing"
                ));
            }
        };
        for feature in FeatureFlags::features_in_category(category) {
            flags.enable(feature);
        }
    }

    // Process --disable-category flags
    for category_name in &opts.disable_category {
        let category = match category_name.to_lowercase().as_str() {
            "experimental" => FeatureCategory::Experimental,
            "enterprise" => FeatureCategory::Enterprise,
            "performance" => FeatureCategory::Performance,
            "debug" => FeatureCategory::Debug,
            "testing" => FeatureCategory::Testing,
            _ => {
                return Err(anyhow!(
                    "Invalid feature category '{category_name}'. Valid categories: experimental, enterprise, performance, debug, testing"
                ));
            }
        };
        for feature in FeatureFlags::features_in_category(category) {
            flags.disable(feature);
        }
    }

    // Process --enable-features flags
    for feature_name in &opts.enable_features {
        if let Ok(feature) = Feature::from_str(feature_name) {
            flags.enable(feature);
        } else {
            return Err(anyhow!("Invalid feature flag '{feature_name}'"));
        }
    }

    // Process --disable-features flags (takes precedence)
    for feature_name in &opts.disable_features {
        if let Ok(feature) = Feature::from_str(feature_name) {
            flags.disable(feature);
        } else {
            return Err(anyhow!("Invalid feature flag '{feature_name}'"));
        }
    }

    Ok(flags)
}

/// List all available feature flags and their status
#[allow(clippy::unwrap_used)]
fn list_all_features(flags: &FeatureFlags) {
    use std::io::Write;

    let stdout = std::io::stdout();
    let mut stdout = stdout.lock();

    writeln!(stdout, "Available Feature Flags:").unwrap();
    writeln!(stdout).unwrap();

    for category in [
        FeatureCategory::Experimental,
        FeatureCategory::Enterprise,
        FeatureCategory::Performance,
        FeatureCategory::Debug,
        FeatureCategory::Testing,
    ] {
        writeln!(stdout, "{}:", category.to_string().to_uppercase()).unwrap();
        for feature in FeatureFlags::features_in_category(category) {
            let status = if flags.is_enabled(feature) {
                "enabled"
            } else {
                "disabled"
            };
            writeln!(
                stdout,
                "  {:20} ({:8}) - {}",
                feature.to_string(),
                status,
                feature.description()
            )
            .unwrap();
        }
        writeln!(stdout).unwrap();
    }

    writeln!(
        stdout,
        "Environment variables: COPYBOOK_FF_<FEATURE_NAME>=1 to enable"
    )
    .unwrap();
}

fn map_error_to_exit_code(err: &AnyhowError) -> ExitCode {
    match dominant_exit_code(err) {
        ExitCode::Ok | ExitCode::Unknown => ExitCode::Internal,
        code => code,
    }
}

fn dominant_exit_code(err: &AnyhowError) -> ExitCode {
    let mut best = ExitCode::Unknown;
    let mut best_precedence = best.precedence();

    for prefix in collect_family_prefixes(err) {
        if let Some(code) = ExitCode::from_family_prefix(&prefix) {
            let precedence = code.precedence();
            if precedence > best_precedence {
                best = code;
                best_precedence = precedence;
            }
        }
    }

    best
}

fn collect_family_prefixes(err: &AnyhowError) -> Vec<String> {
    let mut prefixes = Vec::new();
    for cause in err.chain() {
        if let Some(core) = cause.downcast_ref::<CoreError>() {
            prefixes.push(core.family_prefix().to_string());
        }
        if let Some(prefix) = parse_prefix_from_str(&cause.to_string()) {
            prefixes.push(prefix);
        }
    }
    prefixes
}

fn parse_prefix_from_str(message: &str) -> Option<String> {
    let token = message.split_whitespace().next()?.trim_end_matches(':');
    if token.len() < 4 || !token.starts_with("CBK") {
        return None;
    }
    Some(token[..4].to_string())
}

/// Parameters for exit diagnostics logging.
pub(crate) struct ExitDiagnostics<'a> {
    exit: ExitCode,
    msg: &'a str,
    op: &'a str,
    path: Option<&'a Path>,
    io_error: Option<&'a io::Error>,
    error: Option<&'a (dyn StdError + 'static)>,
    subcode: Option<u16>,
    op_stage: &'a str,
    severity: Level,
    effective_exit: i32,
}

impl<'a> ExitDiagnostics<'a> {
    /// Create a new `ExitDiagnostics` with required parameters.
    pub fn new(
        exit: ExitCode,
        msg: &'a str,
        op: &'a str,
        op_stage: &'a str,
        severity: Level,
        effective_exit: i32,
    ) -> Self {
        Self {
            exit,
            msg,
            op,
            path: None,
            io_error: None,
            error: None,
            subcode: None,
            op_stage,
            severity,
            effective_exit,
        }
    }

    /// Set the path parameter.
    #[must_use]
    pub fn with_path(mut self, path: Option<&'a Path>) -> Self {
        self.path = path;
        self
    }

    /// Set the `io_error` parameter.
    #[must_use]
    pub fn with_io_error(mut self, io_error: Option<&'a io::Error>) -> Self {
        self.io_error = io_error;
        self
    }

    /// Set the error parameter.
    #[must_use]
    pub fn with_error(mut self, error: Option<&'a (dyn StdError + 'static)>) -> Self {
        self.error = error;
        self
    }

    /// Set the subcode parameter.
    #[must_use]
    pub fn with_subcode(mut self, subcode: Option<u16>) -> Self {
        self.subcode = subcode;
        self
    }
}

#[non_exhaustive]
#[derive(Copy, Clone)]
pub(crate) enum Stage {
    Parse,
    Execute,
    Finalize,
    Panic,
}

impl Stage {
    #[inline]
    pub const fn as_str(self) -> &'static str {
        match self {
            Stage::Parse => "parse",
            Stage::Execute => "execute",
            Stage::Finalize => "finalize",
            Stage::Panic => "panic",
        }
    }
}

#[inline]
pub(crate) fn emit_exit_diagnostics_stage(diagnostics: &ExitDiagnostics<'_>, stage: Stage) {
    let ExitDiagnostics {
        exit,
        msg,
        op,
        path,
        io_error,
        error,
        subcode,
        op_stage: _,
        severity,
        effective_exit,
    } = *diagnostics;

    let stage_diagnostics =
        ExitDiagnostics::new(exit, msg, op, stage.as_str(), severity, effective_exit)
            .with_path(path)
            .with_io_error(io_error)
            .with_error(error)
            .with_subcode(subcode);
    emit_exit_diagnostics(&stage_diagnostics);
}

pub(crate) fn emit_exit_diagnostics(diagnostics: &ExitDiagnostics<'_>) {
    let ExitDiagnostics {
        exit,
        msg,
        op,
        path,
        io_error,
        error,
        subcode,
        op_stage,
        severity,
        effective_exit,
    } = *diagnostics;
    let (errno, err_kind) =
        io_error.map_or((None, None), |err| (err.raw_os_error(), Some(err.kind())));
    let subcode_label = subcode.map_or_else(|| "n/a".to_string(), |value| value.to_string());
    let severity_tag = match severity {
        Level::ERROR => "ERROR",
        Level::WARN => "WARN",
        Level::INFO => "INFO",
        Level::DEBUG => "DEBUG",
        Level::TRACE => "TRACE",
    };

    macro_rules! log_diagnostic {
        ($macro:ident) => {
            tracing::$macro!(
                log_schema = LOG_SCHEMA,
                op_stage = %op_stage,
                invocation_id = %invocation_id(),
                severity_tag = %severity_tag,
                code_tag = %exit,
                code = exit.as_i32(),
                family = %exit.family(),
                precedence_rank = exit.precedence_rank(),
                subcode = %subcode_label,
                subcode_numeric = ?subcode,
                effective_exit = effective_exit,
                errno = ?errno,
                err_kind = ?err_kind,
                op = %op,
                path = ?path,
                io_error = ?io_error,
                error = ?error,
                "{msg}"
            )
        };
    }

    match severity {
        Level::ERROR => log_diagnostic!(error),
        Level::WARN => log_diagnostic!(warn),
        Level::INFO => log_diagnostic!(info),
        Level::DEBUG => log_diagnostic!(debug),
        Level::TRACE => log_diagnostic!(trace),
    }
}

fn effective_strict_policy(cli: &Cli) -> bool {
    if cli.strict_policy {
        true
    } else if cli.no_strict_policy {
        false
    } else {
        env_flag("COPYBOOK_STRICT_POLICY")
    }
}

/// Get effective dialect from CLI flag or environment variable
///
/// Precedence: CLI flag > `COPYBOOK_DIALECT` env var > default (Normative)
fn effective_dialect(cli_dialect: Option<DialectPreference>) -> DialectPreference {
    if let Some(dialect) = cli_dialect {
        return dialect;
    }
    if let Ok(env_val) = std::env::var("COPYBOOK_DIALECT") {
        match env_val.trim().to_ascii_lowercase().as_str() {
            "0" => DialectPreference::Zero,
            "1" => DialectPreference::One,
            _ => DialectPreference::N, // Default to normative on invalid value
        }
    } else {
        DialectPreference::N // Default to normative
    }
}

fn env_flag(name: &str) -> bool {
    std::env::var(name).ok().is_some_and(|value| {
        matches!(
            value.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        )
    })
}

fn panic_caused_by_std_pipe(panic_payload: &dyn std::any::Any) -> bool {
    let message = if let Some(&msg) = panic_payload.downcast_ref::<&str>() {
        msg
    } else if let Some(msg) = panic_payload.downcast_ref::<String>() {
        msg.as_str()
    } else {
        return false;
    };

    let lower = message.to_ascii_lowercase();
    let is_std_stream =
        lower.contains("failed printing to stdout") || lower.contains("failed printing to stderr");
    if !is_std_stream {
        return false;
    }

    let is_broken_pipe = lower.contains("broken pipe")
        || lower.contains("os error 32")
        || lower.contains("error_broken_pipe")
        || lower.contains("error_no_data");
    let is_write_zero = lower.contains("write zero") || lower.contains("writezero");

    is_broken_pipe || is_write_zero
}

fn extract_panic_message(panic_payload: &dyn std::any::Any) -> Cow<'_, str> {
    if let Some(&msg) = panic_payload.downcast_ref::<&str>() {
        return Cow::Borrowed(msg);
    }
    if let Some(msg) = panic_payload.downcast_ref::<String>() {
        return Cow::Borrowed(msg.as_str());
    }
    Cow::Borrowed("unknown panic")
}

#[cfg(feature = "audit")]
pub(crate) fn write_stdout_line(line: &str) -> Result<(), io::Error> {
    let mut buffer = String::with_capacity(line.len() + 1);
    buffer.push_str(line);
    buffer.push('\n');
    write_stdout_all(buffer.as_bytes())
}

#[cfg_attr(not(feature = "audit"), allow(dead_code))] // audit CLI helper retained for enterprise workflows (tracked in ROADMAP phase 6)
pub(crate) fn write_stderr_line(line: &str) -> Result<(), io::Error> {
    let mut buffer = String::with_capacity(line.len() + 1);
    buffer.push_str(line);
    buffer.push('\n');
    write_stderr_all(buffer.as_bytes())
}

pub(crate) fn write_stdout_all(bytes: &[u8]) -> Result<(), io::Error> {
    let mut stdout = io::stdout().lock();
    match stdout.write_all(bytes) {
        Ok(()) => Ok(()),
        Err(err) if is_consumer_closed(&err) => Ok(()),
        Err(err) => Err(err),
    }
}

pub(crate) fn write_stderr_all(bytes: &[u8]) -> Result<(), io::Error> {
    let mut stderr = io::stderr().lock();
    match stderr.write_all(bytes) {
        Ok(()) => Ok(()),
        Err(err) if is_consumer_closed(&err) => Ok(()),
        Err(err) => Err(err),
    }
}

#[inline]
fn is_consumer_closed(err: &io::Error) -> bool {
    matches!(err.kind(), ErrorKind::BrokenPipe | ErrorKind::WriteZero)
        || err.raw_os_error() == Some(109)
        || err.raw_os_error() == Some(232)
}

mod commands {
    #[cfg(feature = "audit")]
    pub mod audit;
    pub mod decode;
    pub mod determinism;
    pub mod encode;
    pub mod inspect;
    pub mod parse;
    pub mod support;
    pub mod verify;
    pub mod verify_report;
}

mod exit_codes;
mod utils;

#[cfg(test)]
#[allow(clippy::expect_used)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use copybook_core::ErrorCode;
    use proptest::prelude::*;

    #[test]
    fn maps_cbkf_family_to_exit_code() {
        let core_error = CoreError::new(
            ErrorCode::CBKF221_RDW_UNDERFLOW,
            "RDW payload underflow detected",
        );
        let io_error = std::io::Error::other(core_error);
        let anyhow_error: AnyhowError = io_error.into();
        assert_eq!(map_error_to_exit_code(&anyhow_error), ExitCode::Format);
    }

    #[test]
    fn selects_highest_precedence_exit_code_from_error_chain() {
        let data_error = CoreError::new(ErrorCode::CBKD301_RECORD_TOO_SHORT, "Record too short");
        let format_error =
            CoreError::new(ErrorCode::CBKF221_RDW_UNDERFLOW, "RDW underflow detected");
        let internal_error =
            CoreError::new(ErrorCode::CBKI001_INVALID_STATE, "Iterator invalid state");

        let chained = AnyhowError::from(data_error)
            .context(format_error.to_string())
            .context(internal_error.to_string());

        assert_eq!(map_error_to_exit_code(&chained), ExitCode::Internal);
    }

    #[test]
    fn exit_code_precedence_is_deterministic() {
        let scenarios = vec![
            (vec![ExitCode::Data, ExitCode::Encode], ExitCode::Encode),
            (vec![ExitCode::Data, ExitCode::Format], ExitCode::Format),
            (
                vec![ExitCode::Format, ExitCode::Internal],
                ExitCode::Internal,
            ),
            (
                vec![ExitCode::Encode, ExitCode::Internal, ExitCode::Data],
                ExitCode::Internal,
            ),
        ];

        for (inputs, expected) in scenarios {
            let err = build_error_stack(&inputs);
            assert_eq!(map_error_to_exit_code(&err), expected);
        }
    }

    proptest! {
        #[test]
        fn exit_code_precedence_respects_permutations(codes in proptest::collection::vec(
            proptest::sample::select(vec![
                ExitCode::Data,
                ExitCode::Encode,
                ExitCode::Format,
                ExitCode::Internal,
            ]),
            1..5
        )) {
            let mut expected = codes[0];
            for code in &codes[1..] {
                if code.precedence() > expected.precedence() {
                    expected = *code;
                }
            }
            for perm in permutations(&codes) {
                let err = build_error_stack(&perm);
                prop_assert_eq!(map_error_to_exit_code(&err), expected);
            }
        }
    }

    fn permutations(codes: &[ExitCode]) -> Vec<Vec<ExitCode>> {
        let mut out = Vec::new();
        let mut current = Vec::with_capacity(codes.len());
        let mut used = vec![false; codes.len()];
        backtrack(codes, &mut used, &mut current, &mut out);
        out
    }

    fn backtrack(
        codes: &[ExitCode],
        used: &mut [bool],
        current: &mut Vec<ExitCode>,
        out: &mut Vec<Vec<ExitCode>>,
    ) {
        if current.len() == codes.len() {
            out.push(current.clone());
            return;
        }
        for (idx, code) in codes.iter().enumerate() {
            if used[idx] {
                continue;
            }
            used[idx] = true;
            current.push(*code);
            backtrack(codes, used, current, out);
            current.pop();
            used[idx] = false;
        }
    }

    fn sample_core_error(code: ExitCode) -> CoreError {
        match code {
            ExitCode::Data => {
                CoreError::new(ErrorCode::CBKD301_RECORD_TOO_SHORT, "Record too short")
            }
            ExitCode::Encode => {
                CoreError::new(ErrorCode::CBKE501_JSON_TYPE_MISMATCH, "JSON type mismatch")
            }
            ExitCode::Format => CoreError::new(ErrorCode::CBKF221_RDW_UNDERFLOW, "RDW underflow"),
            ExitCode::Internal => {
                CoreError::new(ErrorCode::CBKI001_INVALID_STATE, "Iterator invalid state")
            }
            _ => CoreError::new(ErrorCode::CBKD301_RECORD_TOO_SHORT, "Record too short"),
        }
    }

    fn build_error_stack(codes: &[ExitCode]) -> AnyhowError {
        assert!(
            !codes.is_empty(),
            "at least one exit code required for stack"
        );
        let mut err = AnyhowError::from(sample_core_error(codes[0]));
        for code in &codes[1..] {
            err = err.context(sample_core_error(*code).to_string());
        }
        err
    }
}