cadmpeg 0.6.8

Convert and inspect native CAD files.
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
// SPDX-License-Identifier: Apache-2.0
//! Typed conversion refusals.
//!
//! The command-report envelope serializes [`RefusalCode`] under `refusal.code`
//! with `status: "refused"`. [`ConversionRefusal::evidence`] is the one
//! projection every surface reads.

use std::borrow::Cow;
use std::fmt;
use std::path::Path;

use cadmpeg_core::decode::{DecodeDepth, ResourceDimension, ResourceFailure, ResourceLimit};
use cadmpeg_core::dialect::DialectLayers;
use cadmpeg_core::target::TargetRefusal;
use cadmpeg_ir::codec::DecodeFailure;
use cadmpeg_ir::report::{check::ValidationReport, decode::DecodeReport, export::ExportReport};
use cadmpeg_registry::Format;
use serde::Serialize;

/// A conversion workflow either refuses a modeled request or fails
/// operationally.
#[derive(Debug)]
pub(crate) enum ApplicationError {
    /// A modeled conversion policy or capability refusal.
    Refusal(Box<ConversionRefusal>),
    /// Filesystem, I/O, malformed implementation, or artifact failure.
    Operational(anyhow::Error),
}

impl ApplicationError {
    /// Returns the typed refusal when this is a modeled verdict.
    #[must_use]
    pub(crate) fn refusal(&self) -> Option<&ConversionRefusal> {
        match self {
            Self::Refusal(refusal) => Some(refusal.as_ref()),
            Self::Operational(_) => None,
        }
    }

    /// Preserve resource evidence while assigning the stage that requested it.
    #[must_use]
    pub(crate) fn at_stage(mut self, stage: RefusalStage) -> Self {
        if let Self::Refusal(ref mut refusal) = self {
            if let ConversionRefusal::ResourceLimit { stage: current, .. } = refusal.as_mut() {
                *current = stage;
            }
        }
        self
    }

    /// Process exit status for this application result.
    #[must_use]
    pub(crate) fn exit_code(&self) -> u8 {
        self.refusal().map_or(2, ConversionRefusal::exit_code)
    }
}

impl From<ConversionRefusal> for ApplicationError {
    fn from(refusal: ConversionRefusal) -> Self {
        Self::Refusal(Box::new(refusal))
    }
}

impl From<anyhow::Error> for ApplicationError {
    fn from(error: anyhow::Error) -> Self {
        if let Some(cadmpeg_core::CodecError::ResourceLimit(limit)) =
            error.downcast_ref::<cadmpeg_core::CodecError>()
        {
            return cadmpeg_core::CodecError::ResourceLimit(*limit).into();
        }
        Self::Operational(error)
    }
}

impl From<std::io::Error> for ApplicationError {
    fn from(error: std::io::Error) -> Self {
        Self::Operational(error.into())
    }
}

impl From<cadmpeg_registry::RegistryLoadError> for ApplicationError {
    fn from(error: cadmpeg_registry::RegistryLoadError) -> Self {
        Self::Operational(error.into())
    }
}

impl From<serde_json::Error> for ApplicationError {
    fn from(error: serde_json::Error) -> Self {
        Self::Operational(error.into())
    }
}

impl From<cadmpeg_core::CodecError> for ApplicationError {
    fn from(error: cadmpeg_core::CodecError) -> Self {
        match error {
            cadmpeg_core::CodecError::ResourceLimit(limit) => ConversionRefusal::ResourceLimit {
                limit,
                stage: RefusalStage::Decode,
            }
            .into(),
            error => Self::Operational(error.into()),
        }
    }
}

impl fmt::Display for ApplicationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Refusal(refusal) => fmt::Display::fmt(refusal.as_ref(), f),
            Self::Operational(error) if f.alternate() => write!(f, "{error:#}"),
            Self::Operational(error) => fmt::Display::fmt(error, f),
        }
    }
}

impl std::error::Error for ApplicationError {}

impl ApplicationError {
    /// Classifies a native codec's decode failure at the load site.
    ///
    /// I/O stays operational; a dialect the codec cannot admit and a strict
    /// floor keep their typed evidence; every other codec error is a decode
    /// refusal carrying the codec's message.
    #[must_use]
    pub(crate) fn from_decode_failure(
        path: &Path,
        format_id: cadmpeg_ir::codec::FormatId,
        failure: DecodeFailure,
    ) -> Self {
        match failure {
            DecodeFailure::StrictRejected { rejection } => {
                ConversionRefusal::StrictDecodeRejected { rejection }.into()
            }
            DecodeFailure::Codec(error) => {
                Self::from_codec_failure(path, format_id, "decoding", error)
            }
            failure => ConversionRefusal::DecodeFailed {
                message: format!(
                    "decode failed: decoding {} as {format_id}: {failure}",
                    path.display()
                ),
            }
            .into(),
        }
    }

    /// Classifies a codec failure while retaining the operation's input context.
    #[must_use]
    pub(crate) fn from_codec_failure(
        path: &Path,
        format_id: cadmpeg_ir::codec::FormatId,
        operation: &'static str,
        error: cadmpeg_core::CodecError,
    ) -> Self {
        match error {
            cadmpeg_core::CodecError::ResourceLimit(limit) => {
                cadmpeg_core::CodecError::ResourceLimit(limit).into()
            }
            cadmpeg_core::CodecError::Io(error) => Self::Operational(
                anyhow::Error::new(cadmpeg_core::CodecError::Io(error))
                    .context(format!("{operation} {} as {format_id}", path.display())),
            ),
            cadmpeg_core::CodecError::UnsupportedDialect { dialects, message } => {
                ConversionRefusal::unsupported_dialect(dialects, message).into()
            }
            error => ConversionRefusal::DecodeFailed {
                message: format!(
                    "decode failed: {operation} {} as {format_id}: {error}",
                    path.display()
                ),
            }
            .into(),
        }
    }
}

/// Stable refusal code written into command reports and used by tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefusalCode {
    /// A resource policy or allocator refused an operation.
    ResourceLimit,
    /// Native input decoding failed with a classified codec error.
    DecodeFailed,
    /// The input was identified but its dialect has no decode grammar.
    UnsupportedDialect,
    /// Strict decode policy rejected a reported loss.
    StrictDecodeRejected,
    /// The check found errors and `--allow-errors` was not set.
    CheckFailed,
    /// Decode reported losses under `--reject-lossy`.
    DecodeLossRejected,
    /// Export planning reported losses under `--reject-lossy`.
    ExportLossRejected,
    /// The encoder cannot write the dialect `--to` named.
    UnsupportedTarget,
    /// The document records less of its source than the encoder plans from.
    InsufficientDepth,
    /// The selected format has no encoder in this build.
    UnsupportedOutputFormat,
    /// Binary container would stream to stdout without `--binary-stdout`.
    BinaryStdoutRejected,
}

impl RefusalCode {
    /// Stable workflow metadata shared by every refusal carrying this code.
    const fn disposition(self) -> RefusalDisposition {
        let (stage, exit_code) = match self {
            Self::ResourceLimit | Self::DecodeFailed => (RefusalStage::Decode, 2),
            Self::UnsupportedDialect | Self::StrictDecodeRejected | Self::DecodeLossRejected => {
                (RefusalStage::Decode, 1)
            }
            Self::CheckFailed => (RefusalStage::Check, 1),
            Self::ExportLossRejected => (RefusalStage::Export, 1),
            Self::UnsupportedTarget | Self::InsufficientDepth | Self::UnsupportedOutputFormat => {
                (RefusalStage::Plan, 1)
            }
            Self::BinaryStdoutRejected => (RefusalStage::Plan, 2),
        };
        RefusalDisposition { stage, exit_code }
    }
}

impl fmt::Display for RefusalCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::ResourceLimit => "resource_limit",
            Self::DecodeFailed => "decode_failed",
            Self::UnsupportedDialect => "unsupported_dialect",
            Self::StrictDecodeRejected => "strict_decode_rejected",
            Self::CheckFailed => "check_failed",
            Self::DecodeLossRejected => "decode_loss_rejected",
            Self::ExportLossRejected => "export_loss_rejected",
            Self::UnsupportedTarget => "unsupported_target",
            Self::InsufficientDepth => "insufficient_depth",
            Self::UnsupportedOutputFormat => "unsupported_output_format",
            Self::BinaryStdoutRejected => "binary_stdout_rejected",
        })
    }
}

impl Serialize for RefusalCode {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

/// Workflow stage that produced the refusal (`refusal.stage` on the wire).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefusalStage {
    /// Input resolved but conversion planning rejected the request.
    Plan,
    /// Input acquisition or decode refused.
    Decode,
    /// Validation refused.
    Check,
    /// Export loss policy or artifact emission refused.
    Export,
    /// Measurement of a loaded document refused.
    Measure,
}

impl fmt::Display for RefusalStage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Plan => "plan",
            Self::Decode => "decode",
            Self::Check => "check",
            Self::Export => "export",
            Self::Measure => "measure",
        })
    }
}

impl Serialize for RefusalStage {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

/// The operation whose validation failed.
#[derive(Debug, Clone, Copy)]
pub(crate) enum CheckOperation {
    /// Report validation findings without an export.
    Check,
    /// Refuse an export after validation.
    Export {
        /// The number of error findings located in what the export writes.
        carried: usize,
    },
}

/// Typed refusal from the conversion workflow.
///
/// Presentation messages, codes, typed detail, and retained reports are all
/// projected once by [`ConversionRefusal::evidence`].
#[derive(Debug)]
pub(crate) enum ConversionRefusal {
    /// An operation exhausted a policy budget or failed to allocate.
    ResourceLimit {
        /// Original resource evidence from the operation that refused.
        limit: ResourceLimit,
        /// Workflow stage that made the resource request.
        stage: RefusalStage,
    },
    /// Native input decoding failed before a document could be produced.
    DecodeFailed {
        /// Human-readable message.
        message: String,
    },
    /// Input identity was recovered before the codec refused its dialect.
    UnsupportedDialect {
        /// Every format layer identified before refusal.
        dialects: Box<DialectLayers>,
        /// Codec-owned reason no decode grammar can admit it.
        reason: String,
    },
    /// Decode completed, but strict mode rejected a loss in its report.
    StrictDecodeRejected {
        /// Completed decode report bound to the loss that caused refusal.
        rejection: cadmpeg_ir::codec::StrictDecodeRejection,
    },
    /// The check found errors and `--allow-errors` was not set.
    CheckFailed {
        /// Operation rejected by validation.
        operation: CheckOperation,
        /// Decode report available for an optional `--report`.
        decode_report: Option<DecodeReport>,
        /// Validation report available for an optional `--report`.
        validation: ValidationReport,
    },
    /// Decode reported losses under `--reject-lossy`.
    DecodeLossRejected {
        /// Requested output format.
        format: Format,
        /// Decode report available for an optional `--report`.
        decode_report: DecodeReport,
    },
    /// Export planning reported losses under `--reject-lossy`.
    ExportLossRejected {
        /// Decode report available for an optional `--report`.
        decode_report: Option<DecodeReport>,
        /// Validation report available for an optional `--report`.
        validation: ValidationReport,
        /// Export report computed by encoder planning before rejection.
        export_report: ExportReport,
    },
    /// The command-line target cannot select a writable output format.
    UnsupportedOutputFormat {
        /// Human-readable selection failure.
        message: String,
    },
    /// The encoder could not resolve or deliver the requested target.
    UnsupportedTarget {
        /// Typed request state and the encoder's structured catalog.
        refusal: Box<TargetRefusal>,
        /// Decode report available for an optional `--report`.
        decode_report: Option<DecodeReport>,
        /// Validation report available for an optional `--report`.
        validation: ValidationReport,
    },
    /// The document records less of its source than the encoder plans from.
    InsufficientDepth {
        /// Output format of the refusing encoder.
        format: &'static str,
        /// The depth the encoder needs and the depth the document records.
        depth: DepthReport,
        /// Decode report available for an optional `--report`.
        decode_report: Option<DecodeReport>,
        /// Validation report available for an optional `--report`.
        validation: ValidationReport,
    },
    /// Binary container would write to stdout without an override.
    BinaryStdoutRejected {
        /// Human-readable message.
        message: String,
    },
    /// The document records less of its source than measurement needs.
    InsufficientMeasureDepth {
        /// The depth measurement needs and the depth the document records.
        depth: DepthReport,
        /// Decode report available for an optional `--report`.
        decode_report: Option<DecodeReport>,
    },
}

/// Stable typed contents of the command-report `refusal` object.
#[derive(Debug, Serialize)]
pub(crate) struct RefusalReport<'a> {
    stage: RefusalStage,
    code: RefusalCode,
    message: Cow<'a, str>,
    #[serde(flatten)]
    detail: Option<RefusalDetail<'a>>,
}

/// Everything a surface may show or serialize about one refusal, projected
/// once from the variant.
#[derive(Debug)]
pub(crate) struct RefusalEvidence<'a> {
    /// Stable code for the report envelope and tests.
    code: RefusalCode,
    /// Presentation message for stderr and `refusal.message`.
    pub(super) message: Cow<'a, str>,
    /// Typed evidence the refusal carries beyond its message.
    detail: Option<RefusalDetail<'a>>,
    /// Reports completed before the refusal, for an optional `--report`.
    pub(crate) reports: RefusalReports<'a>,
}

/// Typed evidence serialized beside the refusal code.
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
enum RefusalDetail<'a> {
    /// The resource request and the budget that refused it.
    Resource(ResourceReport),
    /// Every format layer identified before the codec refused.
    Dialects(&'a DialectLayers),
    /// The encoder's typed target refusal and catalog.
    Target(&'a TargetRefusal),
    /// The depth the encoder needs and the depth the document records.
    Depth(DepthReport),
}

/// Depth evidence carried by an insufficient-depth refusal.
#[derive(Debug, Clone, Copy, Serialize)]
pub(crate) struct DepthReport {
    /// The least depth the consumer needs.
    pub(crate) needed: DecodeDepth,
    /// The depth the document records.
    pub(crate) recorded: DecodeDepth,
}

/// Resource evidence carried by a command refusal.
#[derive(Debug, Serialize)]
struct ResourceReport {
    dimension: &'static str,
    reason: &'static str,
    limit: u64,
    used: u64,
    requested: u64,
    operation: &'static str,
}

impl From<&ResourceLimit> for ResourceReport {
    fn from(limit: &ResourceLimit) -> Self {
        let dimension = match limit.dimension {
            ResourceDimension::InputBytes => "input_bytes",
            ResourceDimension::DecompressedBytes => "decompressed_bytes",
            ResourceDimension::RetainedBytes => "retained_bytes",
            ResourceDimension::Entities => "entities",
            ResourceDimension::RecursionDepth => "recursion_depth",
        };
        let reason = match limit.reason {
            ResourceFailure::BudgetExceeded => "budget_exceeded",
            ResourceFailure::AllocationFailed => "allocation_failed",
        };
        Self {
            dimension,
            reason,
            limit: limit.limit,
            used: limit.used,
            requested: limit.additional,
            operation: limit.operation,
        }
    }
}

/// Reports a refusal retains from the stages that completed before it.
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct RefusalReports<'a> {
    /// Completed decode report.
    pub(crate) decode: Option<&'a DecodeReport>,
    /// Completed validation report.
    pub(crate) check: Option<&'a ValidationReport>,
    /// Export report computed by encoder planning before rejection.
    pub(crate) export: Option<&'a ExportReport>,
}

/// Variant metadata that does not depend on a refusal's carried reports.
#[derive(Debug, Clone, Copy)]
struct RefusalDisposition {
    stage: RefusalStage,
    exit_code: u8,
}

impl ConversionRefusal {
    /// Constructs a decode refusal without duplicating ownership and wording at
    /// each surface that can inspect or load a native container.
    #[must_use]
    pub(crate) fn unsupported_dialect(
        dialects: Box<DialectLayers>,
        reason: impl Into<String>,
    ) -> Self {
        Self::UnsupportedDialect {
            dialects,
            reason: reason.into(),
        }
    }

    /// Projects code, message, typed detail, and retained reports at once.
    #[must_use]
    pub(crate) fn evidence(&self) -> RefusalEvidence<'_> {
        match self {
            Self::ResourceLimit { limit, .. } => RefusalEvidence {
                code: RefusalCode::ResourceLimit,
                message: Cow::Owned(format!(
                    "{} during {}",
                    cadmpeg_core::CodecError::ResourceLimit(*limit),
                    limit.operation
                )),
                detail: Some(RefusalDetail::Resource(limit.into())),
                reports: RefusalReports::default(),
            },
            Self::DecodeFailed { message } => RefusalEvidence {
                code: RefusalCode::DecodeFailed,
                message: Cow::Borrowed(message),
                detail: None,
                reports: RefusalReports::default(),
            },
            Self::UnsupportedDialect { dialects, reason } => RefusalEvidence {
                code: RefusalCode::UnsupportedDialect,
                message: Cow::Owned(unsupported_dialect_message(dialects, reason)),
                detail: Some(RefusalDetail::Dialects(dialects)),
                reports: RefusalReports::default(),
            },
            Self::StrictDecodeRejected { rejection } => {
                let loss = rejection.loss();
                RefusalEvidence {
                    code: RefusalCode::StrictDecodeRejected,
                    message: Cow::Owned(format!(
                        "strict mode rejects {}: {}",
                        loss.code, loss.message
                    )),
                    detail: None,
                    reports: RefusalReports {
                        decode: Some(rejection.report()),
                        check: None,
                        export: None,
                    },
                }
            }
            Self::CheckFailed {
                operation,
                decode_report,
                validation,
            } => RefusalEvidence {
                code: RefusalCode::CheckFailed,
                message: Cow::Owned(match operation {
                    CheckOperation::Check => {
                        format!("check found {} error(s)", validation.error_count())
                    }
                    CheckOperation::Export { carried } if *carried == validation.error_count() => format!(
                        "check found {} error(s); refusing to export (use --allow-errors to override)",
                        validation.error_count()
                    ),
                    CheckOperation::Export { carried } => format!(
                        "check found {} error(s), {carried} in what the export writes; refusing to export (use --allow-errors to override)",
                        validation.error_count()
                    ),
                }),
                detail: None,
                reports: RefusalReports {
                    decode: decode_report.as_ref(),
                    check: Some(validation),
                    export: None,
                },
            },
            Self::DecodeLossRejected {
                format,
                decode_report,
            } => RefusalEvidence {
                code: RefusalCode::DecodeLossRejected,
                message: Cow::Owned(format!(
                    "decode reported {} loss(es); refusing to write a lossy {} (omit --reject-lossy to allow)",
                    decode_report.losses.len(),
                    format.name()
                )),
                detail: None,
                reports: RefusalReports {
                    decode: Some(decode_report),
                    check: None,
                    export: None,
                },
            },
            Self::ExportLossRejected {
                decode_report,
                validation,
                export_report,
            } => RefusalEvidence {
                code: RefusalCode::ExportLossRejected,
                message: Cow::Owned(format!(
                    "export planning reported {} loss(es): {}; refusing to write a lossy {} (omit --reject-lossy to allow)",
                    export_report.losses.len(),
                    export_report
                        .losses
                        .iter()
                        .map(|loss| loss.message.as_str())
                        .collect::<Vec<_>>()
                        .join("; "),
                    export_report.format()
                )),
                detail: None,
                reports: RefusalReports {
                    decode: decode_report.as_ref(),
                    check: Some(validation),
                    export: Some(export_report),
                },
            },
            Self::UnsupportedOutputFormat { message } => RefusalEvidence {
                code: RefusalCode::UnsupportedOutputFormat,
                message: Cow::Borrowed(message),
                detail: None,
                reports: RefusalReports::default(),
            },
            Self::UnsupportedTarget {
                refusal,
                decode_report,
                validation,
            } => RefusalEvidence {
                code: RefusalCode::UnsupportedTarget,
                message: Cow::Owned(refusal.to_string()),
                detail: Some(RefusalDetail::Target(refusal)),
                reports: RefusalReports {
                    decode: decode_report.as_ref(),
                    check: Some(validation),
                    export: None,
                },
            },
            Self::InsufficientDepth {
                format,
                depth,
                decode_report,
                validation,
            } => RefusalEvidence {
                code: RefusalCode::InsufficientDepth,
                message: Cow::Owned(format!(
                    "the {format} encoder needs a {}-depth decode, but the document records {} depth",
                    depth.needed, depth.recorded
                )),
                detail: Some(RefusalDetail::Depth(*depth)),
                reports: RefusalReports {
                    decode: decode_report.as_ref(),
                    check: Some(validation),
                    export: None,
                },
            },
            Self::BinaryStdoutRejected { message } => RefusalEvidence {
                code: RefusalCode::BinaryStdoutRejected,
                message: Cow::Borrowed(message),
                detail: None,
                reports: RefusalReports::default(),
            },
            Self::InsufficientMeasureDepth {
                depth,
                decode_report,
            } => RefusalEvidence {
                code: RefusalCode::InsufficientDepth,
                message: Cow::Owned(format!(
                    "measurement needs a {}-depth decode, but the document records {} depth",
                    depth.needed, depth.recorded
                )),
                detail: Some(RefusalDetail::Depth(*depth)),
                reports: RefusalReports {
                    decode: decode_report.as_ref(),
                    check: None,
                    export: None,
                },
            },
        }
    }

    /// Stable code for tests and the report envelope.
    #[must_use]
    pub(crate) fn code(&self) -> RefusalCode {
        self.evidence().code
    }

    /// Typed `refusal` object for a command report.
    #[must_use]
    pub(crate) fn report(&self) -> RefusalReport<'_> {
        let evidence = self.evidence();
        RefusalReport {
            stage: match self {
                Self::ResourceLimit { stage, .. } => *stage,
                _ => evidence.code.disposition().stage,
            },
            code: evidence.code,
            message: evidence.message,
            detail: evidence.detail,
        }
    }

    /// Process exit status for this refusal.
    ///
    /// Semantic model refusals exit 1. Resource, codec, and binary-stdout
    /// failures exit 2.
    #[must_use]
    fn exit_code(&self) -> u8 {
        self.code().disposition().exit_code
    }
}

fn unsupported_dialect_message(dialects: &DialectLayers, reason: &str) -> String {
    let primary = dialects.primary();
    let carried = dialects
        .iter()
        .skip(1)
        .map(|layer| layer.dialect().as_str())
        .collect::<Vec<_>>();
    if carried.is_empty() {
        format!(
            "unsupported {} dialect {}: {reason}",
            primary.format(),
            primary.dialect()
        )
    } else {
        format!(
            "unsupported {} dialect {}; carried layers: {}; {reason}",
            primary.format(),
            primary.dialect(),
            carried.join(", ")
        )
    }
}

impl fmt::Display for ConversionRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.evidence().message.as_ref())
    }
}

impl std::error::Error for ConversionRefusal {}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    use cadmpeg_core::decode::DecodeDepth;
    use cadmpeg_core::dialect::{DialectLayers, DialectMatch};
    use cadmpeg_core::target::{TargetCatalog, TargetDescriptor};

    use super::{ApplicationError, CheckOperation, ConversionRefusal, DepthReport, RefusalCode};
    use crate::application::transcoder::TargetSelection;
    use cadmpeg_core::target::TargetRefusal;
    use cadmpeg_ir::codec::DecodeFailure;
    use cadmpeg_ir::report::check::ValidationReport;

    const IGES_TARGETS: &[TargetDescriptor] = &[TargetDescriptor {
        id: cadmpeg_core::dialect_id!("iges:5.3-fixed-ascii"),
        aliases: &[],
    }];
    const IGES_CATALOG: TargetCatalog = TargetCatalog::new(IGES_TARGETS, Some(0));

    fn report_value(refusal: &ConversionRefusal) -> serde_json::Value {
        serde_json::to_value(refusal.report()).expect("serialize refusal report")
    }

    fn classify(failure: DecodeFailure) -> ApplicationError {
        ApplicationError::from_decode_failure(
            &PathBuf::from("part.step"),
            cadmpeg_ir::codec::FormatId::new("step"),
            failure,
        )
    }

    #[test]
    fn refusal_codes_are_stable_for_tests_and_absent_from_display() {
        let refusal = ConversionRefusal::UnsupportedTarget {
            refusal: Box::new(TargetRefusal::unknown_explicit("iges:9.9", IGES_CATALOG)),
            decode_report: None,
            validation: ValidationReport {
                entity_counts: BTreeMap::new(),
                findings: Vec::new(),
                losses: Vec::new(),
            },
        };
        assert_eq!(refusal.code(), RefusalCode::UnsupportedTarget);
        assert_eq!(report_value(&refusal)["stage"], "plan");
        assert_eq!(refusal.exit_code(), 1);
        assert_eq!(
            refusal.to_string(),
            "iges cannot write iges:9.9: not a target this encoder can synthesize; available targets: iges:5.3-fixed-ascii"
        );
        let report = report_value(&refusal);
        assert_eq!(report["code"], "unsupported_target");
        assert_eq!(report["stage"], "plan");
        assert_eq!(report["target"]["refusal"]["kind"], "unknown_explicit");
        assert_eq!(report["target"]["format"], "iges");
        assert_eq!(report["target"]["refusal"]["requested"], "iges:9.9");
        assert_eq!(
            report["target"]["available"][0]["id"],
            "iges:5.3-fixed-ascii"
        );
    }

    #[test]
    fn an_insufficient_depth_refusal_reports_both_depths_at_plan() {
        let refusal = ConversionRefusal::InsufficientDepth {
            format: "f3d",
            depth: DepthReport {
                needed: DecodeDepth::Full,
                recorded: DecodeDepth::Geometry,
            },
            decode_report: None,
            validation: ValidationReport {
                entity_counts: BTreeMap::new(),
                findings: Vec::new(),
                losses: Vec::new(),
            },
        };
        assert_eq!(refusal.code(), RefusalCode::InsufficientDepth);
        assert_eq!(refusal.exit_code(), 1);
        assert_eq!(
            refusal.to_string(),
            "the f3d encoder needs a full-depth decode, but the document records geometry depth"
        );
        let report = report_value(&refusal);
        assert_eq!(report["code"], "insufficient_depth");
        assert_eq!(report["stage"], "plan");
        assert_eq!(report["depth"]["needed"], "full");
        assert_eq!(report["depth"]["recorded"], "geometry");
    }

    #[test]
    fn a_measure_depth_refusal_reports_both_depths_at_plan() {
        let refusal = ConversionRefusal::InsufficientMeasureDepth {
            depth: DepthReport {
                needed: DecodeDepth::Geometry,
                recorded: DecodeDepth::Container,
            },
            decode_report: None,
        };
        assert_eq!(refusal.code(), RefusalCode::InsufficientDepth);
        assert_eq!(refusal.exit_code(), 1);
        assert_eq!(
            refusal.to_string(),
            "measurement needs a geometry-depth decode, but the document records container depth"
        );
        let report = report_value(&refusal);
        assert_eq!(report["code"], "insufficient_depth");
        assert_eq!(report["stage"], "plan");
        assert_eq!(report["depth"]["needed"], "geometry");
        assert_eq!(report["depth"]["recorded"], "container");
    }

    #[test]
    fn unsupported_decode_keeps_the_identification() {
        let matched = DialectMatch::refused(cadmpeg_core::dialect_id!("step:part-28-xml"));
        let refusal = ConversionRefusal::UnsupportedDialect {
            dialects: Box::new(DialectLayers::of(matched.clone())),
            reason: "the XML encoding has no decode grammar".into(),
        };

        let ConversionRefusal::UnsupportedDialect { dialects, .. } = &refusal else {
            panic!("the variant just constructed is preserved");
        };
        assert_eq!(dialects.primary(), &matched);
        assert_eq!(refusal.code(), RefusalCode::UnsupportedDialect);
        assert_eq!(report_value(&refusal)["stage"], "decode");
        assert_eq!(refusal.exit_code(), 1);
        assert_eq!(report_value(&refusal)["code"], "unsupported_dialect");
    }

    #[test]
    fn unsupported_decode_serializes_every_identified_layer() {
        let layers = DialectLayers::of(DialectMatch::refused(cadmpeg_core::dialect_id!(
            "sldprt:sw-2024"
        )))
        .with(DialectMatch::residual(cadmpeg_core::dialect_id!(
            "parasolid:unknown"
        )))
        .expect("distinct dialect layer keys");
        let refusal = ConversionRefusal::UnsupportedDialect {
            dialects: Box::new(layers),
            reason: "no decoder admits the host dialect".into(),
        };

        let report = report_value(&refusal);
        assert_eq!(report["dialects"]["primary"]["dialect"], "sldprt:sw-2024");
        assert_eq!(
            report["dialects"]["extra"][0]["dialect"],
            "parasolid:unknown"
        );
        assert!(refusal.to_string().contains("parasolid:unknown"));
    }

    #[test]
    fn unwritable_format_has_its_own_wire_code() {
        let refusal = ConversionRefusal::UnsupportedOutputFormat {
            message: "catia is not writable".into(),
        };

        assert_eq!(refusal.code(), RefusalCode::UnsupportedOutputFormat);
        assert_eq!(report_value(&refusal)["code"], "unsupported_output_format");
    }

    #[test]
    fn decode_classifier_preserves_an_unsupported_dialect_variant() {
        let matched = DialectMatch::refused(cadmpeg_core::dialect_id!("step:part-28-xml"));
        let classified = classify(DecodeFailure::Codec(
            cadmpeg_core::CodecError::UnsupportedDialect {
                dialects: Box::new(DialectLayers::of(matched.clone())),
                message: "the XML encoding has no decode grammar".into(),
            },
        ));
        let refusal = classified
            .refusal()
            .expect("codec refusal becomes an application refusal");

        let ConversionRefusal::UnsupportedDialect { dialects, .. } = refusal else {
            panic!("unsupported identity must not be flattened to DecodeFailed");
        };
        assert_eq!(dialects.primary(), &matched);
    }

    #[test]
    fn decode_classifier_keeps_io_operational() {
        let classified = classify(DecodeFailure::Codec(cadmpeg_core::CodecError::Io(
            std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read"),
        )));

        assert!(classified.refusal().is_none());
        assert_eq!(classified.exit_code(), 2);
        assert_eq!(classified.to_string(), "decoding part.step as step");
        assert!(format!("{classified:#}").contains("short read"));
    }

    #[test]
    fn binary_stdout_keeps_operational_exit_two() {
        let refusal = ConversionRefusal::BinaryStdoutRejected {
            message: "refusing to write binary sldprt to standard output".into(),
        };
        assert_eq!(refusal.code(), RefusalCode::BinaryStdoutRejected);
        assert_eq!(report_value(&refusal)["stage"], "plan");
        assert_eq!(refusal.exit_code(), 2);
    }

    #[test]
    fn decode_failure_is_a_structured_decode_refusal() {
        let refusal = ConversionRefusal::DecodeFailed {
            message: "decode failed: malformed container: test".into(),
        };
        assert_eq!(refusal.code(), RefusalCode::DecodeFailed);
        assert_eq!(report_value(&refusal)["stage"], "decode");
        assert_eq!(refusal.exit_code(), 2);
        let evidence = refusal.evidence();
        assert!(evidence.reports.decode.is_none());
        assert!(evidence.reports.check.is_none());
        assert!(evidence.detail.is_none());
        let report = report_value(&refusal);
        assert_eq!(report["code"], "decode_failed");
        assert_eq!(report["stage"], "decode");
    }

    #[test]
    fn check_refusal_maps_to_check_stage() {
        let refusal = ConversionRefusal::CheckFailed {
            operation: CheckOperation::Check,
            decode_report: None,
            validation: ValidationReport {
                entity_counts: BTreeMap::new(),
                findings: Vec::new(),
                losses: Vec::new(),
            },
        };
        assert_eq!(report_value(&refusal)["stage"], "check");
        assert_eq!(refusal.code().to_string(), "check_failed");
    }

    #[test]
    fn an_unwritable_format_is_a_typed_plan_refusal() {
        let error = TargetSelection::resolve(Some("catia:v5"), None).unwrap_err();
        let refusal = error
            .refusal()
            .expect("unsupported output formats are semantic plan refusals");
        assert!(matches!(
            refusal,
            ConversionRefusal::UnsupportedOutputFormat { .. }
        ));
        assert_eq!(
            refusal.code(),
            crate::application::refusal::RefusalCode::UnsupportedOutputFormat
        );
        assert_eq!(
            serde_json::to_value(refusal.report()).unwrap()["stage"],
            "plan"
        );
        assert_eq!(refusal.exit_code(), 1);
    }

    #[test]
    fn resource_refusals_preserve_each_dimension_reason_and_request() {
        use cadmpeg_core::decode::{ResourceDimension, ResourceFailure, ResourceLimit};
        let dimensions = [
            (ResourceDimension::InputBytes, "input_bytes"),
            (ResourceDimension::DecompressedBytes, "decompressed_bytes"),
            (ResourceDimension::RetainedBytes, "retained_bytes"),
            (ResourceDimension::Entities, "entities"),
            (ResourceDimension::RecursionDepth, "recursion_depth"),
        ];
        for (dimension, name) in dimensions {
            for (reason, reason_name) in [
                (ResourceFailure::BudgetExceeded, "budget_exceeded"),
                (ResourceFailure::AllocationFailed, "allocation_failed"),
            ] {
                let limit = ResourceLimit {
                    dimension,
                    reason,
                    limit: u64::MAX,
                    used: u64::MAX - 1,
                    additional: 2,
                    operation: "synthetic resource request",
                };
                let error = classify(DecodeFailure::Codec(
                    cadmpeg_core::CodecError::ResourceLimit(limit),
                ));
                let refusal = error.refusal().expect("resources are reportable refusals");
                assert_eq!(error.exit_code(), 2);
                assert_eq!(refusal.code(), RefusalCode::ResourceLimit);
                let report = report_value(refusal);
                assert_eq!(report["stage"], "decode");
                assert_eq!(
                    report["resource"],
                    serde_json::json!({
                        "dimension": name, "reason": reason_name, "limit": u64::MAX,
                        "used": u64::MAX - 1, "requested": 2, "operation": limit.operation,
                    })
                );
                assert!(error
                    .to_string()
                    .contains("during synthetic resource request"));
            }
        }
    }

    #[test]
    fn contextual_resource_errors_retain_evidence_and_the_requesting_stage() {
        use cadmpeg_core::decode::{ResourceDimension, ResourceLimit};
        let limit = ResourceLimit::allocation_failed(
            ResourceDimension::RetainedBytes,
            8,
            4,
            "synthetic allocation",
        );
        for (stage, label) in [
            (super::RefusalStage::Check, "check"),
            (super::RefusalStage::Plan, "plan"),
            (super::RefusalStage::Export, "export"),
            (super::RefusalStage::Measure, "measure"),
        ] {
            let error = anyhow::Error::new(cadmpeg_core::CodecError::ResourceLimit(limit))
                .context("writing an artifact");
            let error = ApplicationError::from(error).at_stage(stage);
            assert_eq!(error.exit_code(), 2);
            let report = report_value(
                error
                    .refusal()
                    .expect("resource evidence survives anyhow context"),
            );
            assert_eq!(report["stage"], label);
            assert_eq!(report["code"], "resource_limit");
            assert_eq!(report["resource"]["reason"], "allocation_failed");
            assert_eq!(report["resource"]["limit"], 8);
            assert_eq!(report["resource"]["used"], 0);
            assert_eq!(report["resource"]["requested"], 4);
            assert_eq!(report["resource"]["operation"], "synthetic allocation");
        }
    }
}