lib3mf 0.1.6

Pure Rust implementation for 3MF (3D Manufacturing Format) parsing and writing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
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
//! Core 3MF types and structures

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::extension::ExtensionRegistry;

use super::beam_lattice::BeamSet;
use super::boolean_ops::BooleanShape;
use super::production::ProductionInfo;

/// 3MF extension specification
///
/// Represents the various official 3MF extensions that can be used in 3MF files.
/// Extensions add additional capabilities beyond the core specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Extension {
    /// Core 3MF specification (always required)
    Core,
    /// Materials & Properties Extension
    Material,
    /// Production Extension
    Production,
    /// Slice Extension
    Slice,
    /// Beam Lattice Extension
    BeamLattice,
    /// Secure Content Extension
    SecureContent,
    /// Boolean Operations Extension
    BooleanOperations,
    /// Displacement Extension
    Displacement,
    /// Volumetric Extension
    Volumetric,
}

/// Controls how strictly the parser enforces OPC packaging rules.
///
/// # Examples
///
/// ```
/// use lib3mf::{ParserConfig, SpecConformance};
///
/// // Default is Strict — all OPC rules are enforced
/// let config = ParserConfig::new();
/// assert_eq!(config.spec_conformance(), SpecConformance::Strict);
///
/// // Lenient mode skips non-critical OPC packaging errors
/// let config = ParserConfig::new()
///     .with_spec_conformance(SpecConformance::Lenient);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SpecConformance {
    /// Enforce all OPC packaging and 3MF specification rules (default).
    #[default]
    Strict,
    /// Skip non-critical OPC packaging validation errors while still
    /// enforcing all 3D-model-critical checks. Use this to load files
    /// from slicers that use non-standard packaging conventions
    /// (e.g., BambuStudio, OrcaSlicer).
    Lenient,
}

impl Extension {
    /// Get the namespace URI for this extension
    pub fn namespace(&self) -> &'static str {
        match self {
            Extension::Core => "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
            Extension::Material => "http://schemas.microsoft.com/3dmanufacturing/material/2015/02",
            Extension::Production => {
                "http://schemas.microsoft.com/3dmanufacturing/production/2015/06"
            }
            Extension::Slice => "http://schemas.microsoft.com/3dmanufacturing/slice/2015/07",
            Extension::BeamLattice => {
                "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02"
            }
            Extension::SecureContent => {
                "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/07"
            }
            Extension::BooleanOperations => {
                "http://schemas.3mf.io/3dmanufacturing/booleanoperations/2023/07"
            }
            Extension::Displacement => {
                "http://schemas.microsoft.com/3dmanufacturing/displacement/2022/07"
            }
            Extension::Volumetric => "http://schemas.3mf.io/volumetric/2023/02",
        }
    }

    /// Get extension from namespace URI
    pub fn from_namespace(namespace: &str) -> Option<Self> {
        match namespace {
            "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" => Some(Extension::Core),
            "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" => {
                Some(Extension::Material)
            }
            "http://schemas.microsoft.com/3dmanufacturing/production/2015/06" => {
                Some(Extension::Production)
            }
            "http://schemas.microsoft.com/3dmanufacturing/slice/2015/07" => Some(Extension::Slice),
            "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02" => {
                Some(Extension::BeamLattice)
            }
            // Also accept the balls sub-extension namespace as part of BeamLattice
            "http://schemas.microsoft.com/3dmanufacturing/beamlattice/balls/2020/07" => {
                Some(Extension::BeamLattice)
            }
            "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/07" => {
                Some(Extension::SecureContent)
            }
            // Also accept the earlier 2019/04 namespace for backward compatibility
            "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/04" => {
                Some(Extension::SecureContent)
            }
            "http://schemas.3mf.io/3dmanufacturing/booleanoperations/2023/07" => {
                Some(Extension::BooleanOperations)
            }
            "http://schemas.microsoft.com/3dmanufacturing/displacement/2022/07" => {
                Some(Extension::Displacement)
            }
            // Also accept the newer 2023/10 namespace for displacement
            "http://schemas.3mf.io/3dmanufacturing/displacement/2023/10" => {
                Some(Extension::Displacement)
            }
            "http://schemas.3mf.io/volumetric/2023/02" => Some(Extension::Volumetric),
            _ => None,
        }
    }

    /// Get a human-readable name for this extension
    pub fn name(&self) -> &'static str {
        match self {
            Extension::Core => "Core",
            Extension::Material => "Material",
            Extension::Production => "Production",
            Extension::Slice => "Slice",
            Extension::BeamLattice => "BeamLattice",
            Extension::SecureContent => "SecureContent",
            Extension::BooleanOperations => "BooleanOperations",
            Extension::Displacement => "Displacement",
            Extension::Volumetric => "Volumetric",
        }
    }
}

/// Configuration for parsing 3MF files
///
/// Allows consumers to specify which extensions they support and register
/// custom extension handlers.
#[derive(Clone)]
pub struct ParserConfig {
    /// Set of extensions supported by the consumer
    /// Core is always implicitly supported
    supported_extensions: HashSet<Extension>,
    /// Registered custom extensions with their handlers
    custom_extensions: HashMap<String, CustomExtensionInfo>,
    /// Optional key provider for decrypting SecureContent
    /// If provided, this will be used to decrypt encrypted files
    /// If not provided, test keys will be used for Suite 8 conformance
    key_provider: Option<Arc<dyn crate::key_provider::KeyProvider>>,
    /// Extension registry for managing extension handlers
    registry: ExtensionRegistry,
    /// Controls how strictly the parser enforces OPC packaging rules.
    spec_conformance: SpecConformance,
}

impl ParserConfig {
    /// Create a new parser configuration with only core support
    pub fn new() -> Self {
        let mut supported = HashSet::new();
        supported.insert(Extension::Core);
        Self {
            supported_extensions: supported,
            custom_extensions: HashMap::new(),
            key_provider: None,
            registry: ExtensionRegistry::new(),
            spec_conformance: SpecConformance::Strict,
        }
    }

    /// Create a parser configuration that supports all known extensions
    ///
    /// Note: When new extensions are added to the Extension enum, they must
    /// be manually added here as well.
    pub fn with_all_extensions() -> Self {
        let mut supported = HashSet::new();
        supported.insert(Extension::Core);
        supported.insert(Extension::Material);
        supported.insert(Extension::Production);
        supported.insert(Extension::Slice);
        supported.insert(Extension::BeamLattice);
        supported.insert(Extension::SecureContent);
        supported.insert(Extension::BooleanOperations);
        supported.insert(Extension::Displacement);
        supported.insert(Extension::Volumetric);
        Self {
            supported_extensions: supported,
            custom_extensions: HashMap::new(),
            key_provider: None,
            registry: crate::extensions::create_default_registry(),
            spec_conformance: SpecConformance::Strict,
        }
    }

    /// Add support for a specific extension
    ///
    /// Automatically registers the default extension handler for known extensions.
    pub fn with_extension(mut self, extension: Extension) -> Self {
        self.supported_extensions.insert(extension);

        // Register the corresponding extension handler
        match extension {
            Extension::Material => {
                self.registry
                    .register(Arc::new(crate::extensions::MaterialExtensionHandler));
            }
            Extension::Production => {
                self.registry
                    .register(Arc::new(crate::extensions::ProductionExtensionHandler));
            }
            Extension::Slice => {
                self.registry
                    .register(Arc::new(crate::extensions::SliceExtensionHandler));
            }
            Extension::BeamLattice => {
                self.registry
                    .register(Arc::new(crate::extensions::BeamLatticeExtensionHandler));
            }
            Extension::SecureContent => {
                self.registry
                    .register(Arc::new(crate::extensions::SecureContentExtensionHandler));
            }
            Extension::BooleanOperations => {
                self.registry.register(Arc::new(
                    crate::extensions::BooleanOperationsExtensionHandler,
                ));
            }
            Extension::Displacement => {
                self.registry
                    .register(Arc::new(crate::extensions::DisplacementExtensionHandler));
            }
            Extension::Volumetric => {
                self.registry
                    .register(Arc::new(crate::extensions::VolumetricExtensionHandler));
            }
            Extension::Core => {
                // Core doesn't have a handler
            }
        }

        self
    }

    /// Register a custom extension with optional handlers
    ///
    /// # Arguments
    ///
    /// * `namespace` - The namespace URI of the custom extension
    /// * `name` - A human-readable name for the extension
    ///
    /// # Example
    ///
    /// ```
    /// use lib3mf::ParserConfig;
    /// use std::sync::Arc;
    ///
    /// let config = ParserConfig::new()
    ///     .with_custom_extension(
    ///         "http://example.com/myextension/2024/01",
    ///         "MyExtension"
    ///     );
    /// ```
    pub fn with_custom_extension(
        mut self,
        namespace: impl Into<String>,
        name: impl Into<String>,
    ) -> Self {
        let namespace = namespace.into();
        let name = name.into();
        self.custom_extensions.insert(
            namespace.clone(),
            CustomExtensionInfo {
                namespace,
                name,
                element_handler: None,
                validation_handler: None,
            },
        );
        self
    }

    /// Register a custom extension with an element handler
    ///
    /// # Arguments
    ///
    /// * `namespace` - The namespace URI of the custom extension
    /// * `name` - A human-readable name for the extension
    /// * `handler` - Callback function to handle elements from this extension
    ///
    /// # Example
    ///
    /// ```
    /// use lib3mf::{ParserConfig, CustomExtensionContext, CustomElementResult};
    /// use std::sync::Arc;
    ///
    /// let config = ParserConfig::new()
    ///     .with_custom_extension_handler(
    ///         "http://example.com/myextension/2024/01",
    ///         "MyExtension",
    ///         Arc::new(|ctx: &CustomExtensionContext| {
    ///             println!("Handling element: {}", ctx.element_name);
    ///             Ok(CustomElementResult::Handled)
    ///         })
    ///     );
    /// ```
    pub fn with_custom_extension_handler(
        mut self,
        namespace: impl Into<String>,
        name: impl Into<String>,
        handler: CustomElementHandler,
    ) -> Self {
        let namespace = namespace.into();
        let name = name.into();
        self.custom_extensions.insert(
            namespace.clone(),
            CustomExtensionInfo {
                namespace,
                name,
                element_handler: Some(handler),
                validation_handler: None,
            },
        );
        self
    }

    /// Register a custom extension with both element and validation handlers
    ///
    /// # Arguments
    ///
    /// * `namespace` - The namespace URI of the custom extension
    /// * `name` - A human-readable name for the extension
    /// * `element_handler` - Callback function to handle elements from this extension
    /// * `validation_handler` - Callback function to validate the model
    ///
    /// # Example
    ///
    /// ```
    /// use lib3mf::{ParserConfig, CustomExtensionContext, CustomElementResult};
    /// use std::sync::Arc;
    ///
    /// let config = ParserConfig::new()
    ///     .with_custom_extension_handlers(
    ///         "http://example.com/myextension/2024/01",
    ///         "MyExtension",
    ///         Arc::new(|ctx: &CustomExtensionContext| {
    ///             Ok(CustomElementResult::Handled)
    ///         }),
    ///         Arc::new(|model| {
    ///             Ok(())
    ///         })
    ///     );
    /// ```
    pub fn with_custom_extension_handlers(
        mut self,
        namespace: impl Into<String>,
        name: impl Into<String>,
        element_handler: CustomElementHandler,
        validation_handler: CustomValidationHandler,
    ) -> Self {
        let namespace = namespace.into();
        let name = name.into();
        self.custom_extensions.insert(
            namespace.clone(),
            CustomExtensionInfo {
                namespace,
                name,
                element_handler: Some(element_handler),
                validation_handler: Some(validation_handler),
            },
        );
        self
    }

    /// Check if an extension is supported
    pub fn supports(&self, extension: &Extension) -> bool {
        self.supported_extensions.contains(extension)
    }

    /// Set a custom key provider for SecureContent decryption
    ///
    /// # Arguments
    ///
    /// * `provider` - The key provider to use for decryption
    ///
    /// # Example
    ///
    /// ```no_run
    /// use lib3mf::{ParserConfig, KeyProvider};
    /// use std::sync::Arc;
    /// # use lib3mf::{Result, SecureContentInfo, AccessRight, CEKParams, KEKParams};
    ///
    /// # struct MyKeyProvider;
    /// # impl KeyProvider for MyKeyProvider {
    /// #     fn decrypt(&self, _: &[u8], _: &CEKParams, _: &AccessRight, _: &SecureContentInfo) -> Result<Vec<u8>> { Ok(vec![]) }
    /// #     fn encrypt(&self, _: &[u8], _: &str, _: bool) -> Result<(Vec<u8>, CEKParams, KEKParams, String)> { unimplemented!() }
    /// # }
    ///
    /// let provider: Arc<dyn KeyProvider> = Arc::new(MyKeyProvider);
    /// let config = ParserConfig::new()
    ///     .with_key_provider(provider);
    /// ```
    pub fn with_key_provider(
        mut self,
        provider: Arc<dyn crate::key_provider::KeyProvider>,
    ) -> Self {
        self.key_provider = Some(provider);
        self
    }

    /// Get the key provider if one is configured
    pub fn key_provider(&self) -> Option<&Arc<dyn crate::key_provider::KeyProvider>> {
        self.key_provider.as_ref()
    }

    /// Check if a custom extension is registered by namespace
    pub fn has_custom_extension(&self, namespace: &str) -> bool {
        self.custom_extensions.contains_key(namespace)
    }

    /// Get the set of supported extensions
    pub fn supported_extensions(&self) -> &HashSet<Extension> {
        &self.supported_extensions
    }

    /// Get information about a custom extension by namespace
    pub fn get_custom_extension(&self, namespace: &str) -> Option<&CustomExtensionInfo> {
        self.custom_extensions.get(namespace)
    }

    /// Get all registered custom extensions
    pub fn custom_extensions(&self) -> &HashMap<String, CustomExtensionInfo> {
        &self.custom_extensions
    }

    /// Register an extension handler
    ///
    /// # Arguments
    ///
    /// * `handler` - The extension handler to register
    ///
    /// # Example
    ///
    /// ```
    /// use lib3mf::{ParserConfig, Extension};
    /// use lib3mf::extensions::MaterialExtensionHandler;
    /// use std::sync::Arc;
    ///
    /// let config = ParserConfig::new()
    ///     .with_extension_handler(Arc::new(MaterialExtensionHandler));
    /// ```
    pub fn with_extension_handler(
        mut self,
        handler: Arc<dyn crate::extension::ExtensionHandler>,
    ) -> Self {
        self.registry.register(handler);
        self
    }

    /// Get a reference to the extension registry
    ///
    /// # Returns
    ///
    /// A reference to the internal extension registry
    pub fn registry(&self) -> &ExtensionRegistry {
        &self.registry
    }

    /// Get a mutable reference to the extension registry
    ///
    /// # Returns
    ///
    /// A mutable reference to the internal extension registry
    pub fn registry_mut(&mut self) -> &mut ExtensionRegistry {
        &mut self.registry
    }

    /// Set the spec conformance level for OPC packaging validation.
    ///
    /// `SpecConformance::Strict` (the default) enforces all OPC rules.
    /// `SpecConformance::Lenient` skips non-critical packaging errors
    /// such as non-standard thumbnail relationship types, duplicate content
    /// type mappings, and other checks that do not affect 3D model data.
    ///
    /// # Example
    ///
    /// ```
    /// use lib3mf::{ParserConfig, SpecConformance};
    ///
    /// let config = ParserConfig::with_all_extensions()
    ///     .with_spec_conformance(SpecConformance::Lenient);
    /// ```
    pub fn with_spec_conformance(mut self, conformance: SpecConformance) -> Self {
        self.spec_conformance = conformance;
        self
    }

    /// Get the current spec conformance level.
    pub fn spec_conformance(&self) -> SpecConformance {
        self.spec_conformance
    }

    /// Returns `true` when lenient OPC validation is active.
    pub(crate) fn is_lenient(&self) -> bool {
        self.spec_conformance == SpecConformance::Lenient
    }
}

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

impl std::fmt::Debug for ParserConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParserConfig")
            .field("supported_extensions", &self.supported_extensions)
            .field("custom_extensions_count", &self.custom_extensions.len())
            .field("spec_conformance", &self.spec_conformance)
            .finish()
    }
}

impl std::fmt::Debug for CustomExtensionInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomExtensionInfo")
            .field("namespace", &self.namespace)
            .field("name", &self.name)
            .field("has_element_handler", &self.element_handler.is_some())
            .field("has_validation_handler", &self.validation_handler.is_some())
            .finish()
    }
}

/// Context information passed to custom extension callbacks
#[derive(Debug, Clone)]
pub struct CustomExtensionContext {
    /// The element name (without namespace prefix)
    pub element_name: String,
    /// The namespace URI of the element
    pub namespace: String,
    /// Attributes of the element as key-value pairs
    pub attributes: HashMap<String, String>,
}

/// Result of a custom element handler
#[derive(Debug, Clone)]
pub enum CustomElementResult {
    /// Element was handled by the callback
    Handled,
    /// Element was not recognized/handled by the callback
    NotHandled,
}

/// Callback function for handling custom extension elements
///
/// This callback is invoked when the parser encounters an element from a namespace
/// that is not a known 3MF extension. The callback can inspect the element and
/// its attributes, and decide whether to handle it.
///
/// # Arguments
///
/// * `context` - Information about the element being parsed
///
/// # Returns
///
/// * `Ok(CustomElementResult::Handled)` - The element was recognized and handled
/// * `Ok(CustomElementResult::NotHandled)` - The element was not recognized
/// * `Err(error_message)` - An error occurred while handling the element
pub type CustomElementHandler =
    Arc<dyn Fn(&CustomExtensionContext) -> Result<CustomElementResult, String> + Send + Sync>;

/// Callback function for custom extension validation
///
/// This callback is invoked during model validation to allow custom validation
/// rules for custom extensions.
///
/// # Arguments
///
/// * `model` - The parsed 3MF model
///
/// # Returns
///
/// * `Ok(())` - Validation passed
/// * `Err(error_message)` - Validation failed with an error message
pub type CustomValidationHandler = Arc<dyn Fn(&Model) -> Result<(), String> + Send + Sync>;

/// Information about a registered custom extension
#[derive(Clone)]
pub struct CustomExtensionInfo {
    /// The namespace URI of the custom extension
    pub namespace: String,
    /// Human-readable name for the extension
    pub name: String,
    /// Optional element handler callback
    pub element_handler: Option<CustomElementHandler>,
    /// Optional validation handler callback
    pub validation_handler: Option<CustomValidationHandler>,
}

/// A 3D vertex with x, y, z coordinates
#[derive(Debug, Clone, PartialEq)]
pub struct Vertex {
    /// X coordinate
    pub x: f64,
    /// Y coordinate
    pub y: f64,
    /// Z coordinate
    pub z: f64,
}

impl Vertex {
    /// Create a new vertex
    pub fn new(x: f64, y: f64, z: f64) -> Self {
        Self { x, y, z }
    }
}

/// A triangle defined by three vertex indices
#[derive(Debug, Clone, PartialEq)]
pub struct Triangle {
    /// Index of first vertex
    pub v1: usize,
    /// Index of second vertex
    pub v2: usize,
    /// Index of third vertex
    pub v3: usize,
    /// Optional material ID (property ID)
    pub pid: Option<usize>,
    /// Optional material index for entire triangle (property index)
    pub pindex: Option<usize>,
    /// Optional material index for vertex 1 (property index)
    pub p1: Option<usize>,
    /// Optional material index for vertex 2 (property index)
    pub p2: Option<usize>,
    /// Optional material index for vertex 3 (property index)
    pub p3: Option<usize>,
}

impl Triangle {
    /// Create a new triangle
    pub fn new(v1: usize, v2: usize, v3: usize) -> Self {
        Self {
            v1,
            v2,
            v3,
            pid: None,
            pindex: None,
            p1: None,
            p2: None,
            p3: None,
        }
    }

    /// Create a new triangle with material ID
    pub fn with_material(v1: usize, v2: usize, v3: usize, pid: usize) -> Self {
        Self {
            v1,
            v2,
            v3,
            pid: Some(pid),
            pindex: None,
            p1: None,
            p2: None,
            p3: None,
        }
    }
}

/// A 3D mesh containing vertices and triangles
#[derive(Debug, Clone)]
pub struct Mesh {
    /// List of vertices
    pub vertices: Vec<Vertex>,
    /// List of triangles
    pub triangles: Vec<Triangle>,
    /// Optional beam lattice structure (Beam Lattice Extension)
    pub beamset: Option<BeamSet>,
}

impl Mesh {
    /// Create a new empty mesh
    pub fn new() -> Self {
        Self {
            vertices: Vec::new(),
            triangles: Vec::new(),
            beamset: None,
        }
    }

    /// Create a new mesh with pre-allocated capacity
    ///
    /// This is useful for performance when the number of vertices and triangles
    /// is known in advance, as it avoids multiple reallocations.
    pub fn with_capacity(vertices: usize, triangles: usize) -> Self {
        Self {
            vertices: Vec::with_capacity(vertices),
            triangles: Vec::with_capacity(triangles),
            beamset: None,
        }
    }
}

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

/// A triangle in a displacement mesh
#[derive(Debug, Clone, PartialEq)]
pub struct DisplacementTriangle {
    /// Index of first vertex
    pub v1: usize,
    /// Index of second vertex
    pub v2: usize,
    /// Index of third vertex
    pub v3: usize,
    /// Optional material ID (property ID)
    pub pid: Option<usize>,
    /// Optional material index for entire triangle (property index)
    pub pindex: Option<usize>,
    /// Optional material index for vertex 1 (property index)
    pub p1: Option<usize>,
    /// Optional material index for vertex 2 (property index)
    pub p2: Option<usize>,
    /// Optional material index for vertex 3 (property index)
    pub p3: Option<usize>,
    /// Optional disp2d group ID (referenced in triangles element or individual triangle)
    pub did: Option<usize>,
    /// Optional displacement coordinate index for vertex 1
    pub d1: Option<usize>,
    /// Optional displacement coordinate index for vertex 2
    pub d2: Option<usize>,
    /// Optional displacement coordinate index for vertex 3
    pub d3: Option<usize>,
}

impl DisplacementTriangle {
    /// Create a new displacement triangle
    pub fn new(v1: usize, v2: usize, v3: usize) -> Self {
        Self {
            v1,
            v2,
            v3,
            pid: None,
            pindex: None,
            p1: None,
            p2: None,
            p3: None,
            did: None,
            d1: None,
            d2: None,
            d3: None,
        }
    }
}

/// A displacement mesh containing vertices and displacement triangles
#[derive(Debug, Clone)]
pub struct DisplacementMesh {
    /// List of vertices
    pub vertices: Vec<Vertex>,
    /// List of displacement triangles
    pub triangles: Vec<DisplacementTriangle>,
}

impl DisplacementMesh {
    /// Create a new empty displacement mesh
    pub fn new() -> Self {
        Self {
            vertices: Vec::new(),
            triangles: Vec::new(),
        }
    }
}

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

/// A component that references another object with optional transformation
///
/// Components allow objects to reference other objects to create assemblies.
/// The referenced object can be transformed using a 4x3 affine transformation matrix.
#[derive(Debug, Clone)]
pub struct Component {
    /// ID of the referenced object
    pub objectid: usize,
    /// Optional 4x3 transformation matrix (12 floats in row-major order)
    ///
    /// Format: [m00 m01 m02 m10 m11 m12 m20 m21 m22 tx ty tz]
    ///
    /// The first 9 values form a 3x3 rotation/scale matrix:
    /// ```text
    /// | m00 m01 m02 |
    /// | m10 m11 m12 |
    /// | m20 m21 m22 |
    /// ```
    ///
    /// The last 3 values are translation components:
    /// - tx (index 9): translation along X axis
    /// - ty (index 10): translation along Y axis
    /// - tz (index 11): translation along Z axis
    pub transform: Option<[f64; 12]>,
    /// Optional path to external model file (Production extension: p:path attribute)
    ///
    /// When set, indicates the component references an object in an external model file
    /// rather than in the current file's resources. Used with Production extension
    /// to reference objects from separate model streams.
    pub path: Option<String>,
    /// Production extension information (UUID, path)
    pub production: Option<ProductionInfo>,
}

impl Component {
    /// Create a new component with the given object reference
    pub fn new(objectid: usize) -> Self {
        Self {
            objectid,
            transform: None,
            path: None,
            production: None,
        }
    }

    /// Create a new component with a transformation matrix
    pub fn with_transform(objectid: usize, transform: [f64; 12]) -> Self {
        Self {
            objectid,
            transform: Some(transform),
            path: None,
            production: None,
        }
    }
}

/// A 3D object that can be a mesh or reference other objects
#[derive(Debug, Clone)]
pub struct Object {
    /// Object ID
    pub id: usize,
    /// Object name (optional)
    pub name: Option<String>,
    /// Type of object
    pub object_type: ObjectType,
    /// Optional mesh data
    pub mesh: Option<Mesh>,
    /// Optional displacement mesh data (Displacement extension)
    /// An object can have either a regular mesh OR a displacement mesh, not both
    pub displacement_mesh: Option<DisplacementMesh>,
    /// Optional material ID (property ID)
    pub pid: Option<usize>,
    /// Optional material index (property index) - used with pid to select from color groups
    pub pindex: Option<usize>,
    /// Optional base material ID reference (materials extension)
    pub basematerialid: Option<usize>,
    /// Optional slice stack ID (slice extension)
    pub slicestackid: Option<usize>,
    /// Production extension information (UUID, path)
    pub production: Option<ProductionInfo>,
    /// Boolean shape definition (Boolean Operations extension)
    pub boolean_shape: Option<BooleanShape>,
    /// Components that reference other objects (assemblies)
    pub components: Vec<Component>,
    /// Thumbnail attribute (deprecated, should not be used with production extension)
    /// This is stored only for validation purposes - the attribute is accepted but not functional
    pub(crate) has_thumbnail_attribute: bool,
    /// Tracks if object has extension-specific shape elements (beamlattice, displacement, etc.)
    /// Used for validation - per Boolean Operations spec, operands must be simple meshes only
    pub(crate) has_extension_shapes: bool,
    /// Parse order (for validation of resource ordering)
    #[doc(hidden)]
    pub parse_order: usize,
}

/// Type of 3D object
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectType {
    /// A standard model object
    Model,
    /// A support structure
    Support,
    /// A solid support structure
    SolidSupport,
    /// A surface object
    Surface,
    /// Other types
    Other,
}

impl Object {
    /// Create a new object
    pub fn new(id: usize) -> Self {
        Self {
            id,
            name: None,
            object_type: ObjectType::Model,
            mesh: None,
            displacement_mesh: None,
            pid: None,
            pindex: None,
            basematerialid: None,
            slicestackid: None,
            production: None,
            boolean_shape: None,
            components: Vec::new(),
            has_thumbnail_attribute: false,
            has_extension_shapes: false,
            parse_order: 0,
        }
    }
}

/// Resources section containing objects and materials
#[derive(Debug, Clone)]
pub struct Resources {
    /// List of objects
    pub objects: Vec<Object>,
    /// List of materials
    pub materials: Vec<super::Material>,
    /// List of color groups (materials extension)
    pub color_groups: Vec<super::ColorGroup>,
    /// List of displacement maps (displacement extension)
    pub displacement_maps: Vec<super::Displacement2D>,
    /// List of normalized vector groups (displacement extension)
    pub norm_vector_groups: Vec<super::NormVectorGroup>,
    /// List of displacement coordinate groups (displacement extension)
    pub disp2d_groups: Vec<super::Disp2DGroup>,
    /// List of slice stacks (slice extension)
    pub slice_stacks: Vec<super::SliceStack>,
    /// List of base material groups (materials extension)
    pub base_material_groups: Vec<super::BaseMaterialGroup>,
    /// List of texture2d resources (materials extension)
    pub texture2d_resources: Vec<super::Texture2D>,
    /// List of texture2d groups (materials extension)
    pub texture2d_groups: Vec<super::Texture2DGroup>,
    /// List of composite materials groups (materials extension)
    pub composite_materials: Vec<super::CompositeMaterials>,
    /// List of multi-properties groups (materials extension)
    pub multi_properties: Vec<super::MultiProperties>,
    /// List of volumetric data resources (volumetric extension)
    pub volumetric_data: Vec<super::VolumetricData>,
    /// List of volumetric property groups (volumetric extension)
    pub volumetric_property_groups: Vec<super::VolumetricPropertyGroup>,
}

impl Resources {
    /// Create a new empty resources section
    pub fn new() -> Self {
        Self {
            objects: Vec::new(),
            materials: Vec::new(),
            color_groups: Vec::new(),
            displacement_maps: Vec::new(),
            norm_vector_groups: Vec::new(),
            disp2d_groups: Vec::new(),
            slice_stacks: Vec::new(),
            base_material_groups: Vec::new(),
            texture2d_resources: Vec::new(),
            texture2d_groups: Vec::new(),
            composite_materials: Vec::new(),
            multi_properties: Vec::new(),
            volumetric_data: Vec::new(),
            volumetric_property_groups: Vec::new(),
        }
    }
}

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

/// An item to be built, referencing an object
#[derive(Debug, Clone)]
pub struct BuildItem {
    /// Reference to object ID
    pub objectid: usize,
    /// Optional transformation matrix (4x3 affine transformation stored as 12 values)
    /// Represents a 3x4 matrix in row-major order for affine transformations
    pub transform: Option<[f64; 12]>,
    /// Production extension UUID (p:UUID attribute)
    pub production_uuid: Option<String>,
    /// Production extension path (p:path attribute) - references external file
    pub production_path: Option<String>,
}

impl BuildItem {
    /// Create a new build item
    pub fn new(objectid: usize) -> Self {
        Self {
            objectid,
            transform: None,
            production_uuid: None,
            production_path: None,
        }
    }
}

/// Build section specifying which objects to manufacture
#[derive(Debug, Clone)]
pub struct Build {
    /// List of items to build
    pub items: Vec<BuildItem>,
    /// Production extension UUID (p:UUID attribute)
    pub production_uuid: Option<String>,
}

impl Build {
    /// Create a new empty build section
    pub fn new() -> Self {
        Self {
            items: Vec::new(),
            production_uuid: None,
        }
    }
}

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

/// Metadata entry for 3MF package
///
/// Represents a metadata key-value pair with optional preservation flag.
/// According to the 3MF Core Specification Chapter 4, metadata elements
/// contain a required `name` attribute and text content value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetadataEntry {
    /// Name of the metadata entry (required by 3MF spec)
    pub name: String,
    /// Value of the metadata entry
    pub value: String,
    /// Preservation flag (optional attribute)
    /// When true, indicates this metadata should be preserved during editing
    pub preserve: Option<bool>,
}

impl MetadataEntry {
    /// Create a new metadata entry
    pub fn new(name: String, value: String) -> Self {
        Self {
            name,
            value,
            preserve: None,
        }
    }

    /// Create a new metadata entry with preservation flag
    pub fn new_with_preserve(name: String, value: String, preserve: bool) -> Self {
        Self {
            name,
            value,
            preserve: Some(preserve),
        }
    }
}

/// Thumbnail metadata for 3MF package
///
/// Represents a thumbnail image referenced in the package relationships.
/// Thumbnails are typically stored in `/Metadata/thumbnail.png` or similar paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Thumbnail {
    /// Path to the thumbnail file within the package
    pub path: String,
    /// Content type (e.g., "image/png", "image/jpeg")
    pub content_type: String,
}

impl Thumbnail {
    /// Create a new thumbnail metadata
    pub fn new(path: String, content_type: String) -> Self {
        Self { path, content_type }
    }
}

/// Complete 3MF model
#[derive(Debug, Clone)]
pub struct Model {
    /// Unit of measurement (e.g., "millimeter", "inch")
    pub unit: String,
    /// XML namespace
    pub xmlns: String,
    /// Required extensions for this model
    /// Extensions that the consumer must support to properly process this file
    pub required_extensions: Vec<Extension>,
    /// Required custom extension namespaces (not part of standard 3MF)
    pub required_custom_extensions: Vec<String>,
    /// Metadata entries with name, value, and optional preservation flag
    pub metadata: Vec<MetadataEntry>,
    /// Thumbnail metadata (if present in the package)
    pub thumbnail: Option<Thumbnail>,
    /// Resources (objects, materials)
    pub resources: Resources,
    /// Build specification
    pub build: Build,
    /// Secure content information (if secure content extension is used)
    pub secure_content: Option<super::SecureContentInfo>,
}

impl Model {
    /// Create a new empty model
    pub fn new() -> Self {
        Self {
            unit: "millimeter".to_string(),
            xmlns: "http://schemas.microsoft.com/3dmanufacturing/core/2015/02".to_string(),
            required_extensions: Vec::new(),
            required_custom_extensions: Vec::new(),
            metadata: Vec::new(),
            thumbnail: None,
            resources: Resources::new(),
            build: Build::new(),
            secure_content: None,
        }
    }

    /// Get metadata value by name (helper for backward compatibility)
    pub fn get_metadata(&self, name: &str) -> Option<&str> {
        self.metadata
            .iter()
            .find(|entry| entry.name == name)
            .map(|entry| entry.value.as_str())
    }

    /// Check if metadata entry exists with the given name
    pub fn has_metadata(&self, name: &str) -> bool {
        self.metadata.iter().any(|entry| entry.name == name)
    }
}

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

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

    #[test]
    fn test_parser_config_new_has_empty_registry() {
        let config = ParserConfig::new();
        assert_eq!(config.registry().handlers().len(), 0);
    }

    #[test]
    fn test_parser_config_with_all_extensions_has_default_registry() {
        let config = ParserConfig::with_all_extensions();
        // Should have all 8 standard extension handlers
        assert_eq!(config.registry().handlers().len(), 8);

        // Verify specific handlers are present
        assert!(config.registry().get_handler(Extension::Material).is_some());
        assert!(
            config
                .registry()
                .get_handler(Extension::Production)
                .is_some()
        );
        assert!(
            config
                .registry()
                .get_handler(Extension::BeamLattice)
                .is_some()
        );
        assert!(config.registry().get_handler(Extension::Slice).is_some());
        assert!(
            config
                .registry()
                .get_handler(Extension::BooleanOperations)
                .is_some()
        );
        assert!(
            config
                .registry()
                .get_handler(Extension::Displacement)
                .is_some()
        );
        assert!(
            config
                .registry()
                .get_handler(Extension::SecureContent)
                .is_some()
        );
    }

    #[test]
    fn test_parser_config_with_extension_handler() {
        let config = ParserConfig::new().with_extension_handler(Arc::new(MaterialExtensionHandler));

        assert_eq!(config.registry().handlers().len(), 1);
        assert!(config.registry().get_handler(Extension::Material).is_some());
    }

    #[test]
    fn test_parser_config_registry_mut() {
        let mut config = ParserConfig::new();
        assert_eq!(config.registry().handlers().len(), 0);

        config
            .registry_mut()
            .register(Arc::new(MaterialExtensionHandler));

        assert_eq!(config.registry().handlers().len(), 1);
        assert!(config.registry().get_handler(Extension::Material).is_some());
    }

    #[test]
    fn test_parser_config_clone() {
        let config1 =
            ParserConfig::new().with_extension_handler(Arc::new(MaterialExtensionHandler));

        let config2 = config1.clone();

        // Both should have the same handlers
        assert_eq!(
            config1.registry().handlers().len(),
            config2.registry().handlers().len()
        );
        assert_eq!(config1.registry().handlers().len(), 1);
        assert!(
            config2
                .registry()
                .get_handler(Extension::Material)
                .is_some()
        );
    }

    #[test]
    fn test_parser_config_chaining() {
        let config = ParserConfig::new()
            .with_extension(Extension::Material)
            .with_extension_handler(Arc::new(MaterialExtensionHandler));

        assert!(config.supports(&Extension::Material));
        // with_extension registers the handler automatically, and with_extension_handler adds it again
        // This is expected behavior - the handler will be called twice but that's okay since validation is idempotent
        assert_eq!(config.registry().handlers().len(), 2);
    }

    #[test]
    fn test_extension_from_namespace_beamlattice() {
        // Test main BeamLattice namespace
        assert_eq!(
            Extension::from_namespace(
                "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02"
            ),
            Some(Extension::BeamLattice)
        );
    }

    #[test]
    fn test_extension_from_namespace_beamlattice_balls() {
        // Test balls sub-extension namespace (should map to BeamLattice)
        assert_eq!(
            Extension::from_namespace(
                "http://schemas.microsoft.com/3dmanufacturing/beamlattice/balls/2020/07"
            ),
            Some(Extension::BeamLattice)
        );
    }

    #[test]
    fn test_extension_from_namespace_securecontent_variants() {
        // Test main SecureContent namespace
        assert_eq!(
            Extension::from_namespace(
                "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/07"
            ),
            Some(Extension::SecureContent)
        );
        // Test older SecureContent namespace for backward compatibility
        assert_eq!(
            Extension::from_namespace(
                "http://schemas.microsoft.com/3dmanufacturing/securecontent/2019/04"
            ),
            Some(Extension::SecureContent)
        );
    }

    #[test]
    fn test_extension_from_namespace_displacement_variants() {
        // Test main Displacement namespace
        assert_eq!(
            Extension::from_namespace(
                "http://schemas.microsoft.com/3dmanufacturing/displacement/2022/07"
            ),
            Some(Extension::Displacement)
        );
        // Test newer Displacement namespace
        assert_eq!(
            Extension::from_namespace("http://schemas.3mf.io/3dmanufacturing/displacement/2023/10"),
            Some(Extension::Displacement)
        );
    }
}