syster-base 0.3.5-alpha

Core library for SysML v2 and KerML parsing, AST, and semantic analysis
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
//! Standalone model representation for interchange.
//!
//! This module provides a `Model` type that represents a SysML/KerML model
//! independently of the Salsa database. This enables:
//!
//! - Loading models from XMI/KPAR without text parsing
//! - Exporting models to various formats
//! - Transferring models between tools
//!
//! ## Design
//!
//! The `Model` stores elements by ID, with relationships as separate edges.
//! This matches the OMG metamodel structure and enables efficient serialization.
//!
//! ```text
//! Model
//! ├── elements: IndexMap<ElementId, Element>  (preserves insertion order)
//! ├── relationships: Vec<Relationship>
//! └── metadata: ModelMetadata
//! ```

use indexmap::IndexMap;
use std::sync::Arc;

// ============================================================================
// IDs
// ============================================================================

/// Unique identifier for a model element.
///
/// This corresponds to `xmi:id` in XMI and `@id` in JSON-LD.
/// UUIDs are preferred for global uniqueness.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ElementId(pub Arc<str>);

impl ElementId {
    /// Create a new element ID.
    pub fn new(id: impl Into<Arc<str>>) -> Self {
        Self(id.into())
    }

    /// Generate a new UUID-based ID.
    pub fn generate() -> Self {
        // Simple UUID v4 generation (would use uuid crate in real impl)
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        Self(format!("{:032x}", nanos).into())
    }

    /// Get the ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for ElementId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for ElementId {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

impl From<String> for ElementId {
    fn from(s: String) -> Self {
        Self::new(s)
    }
}

// ============================================================================
// ELEMENT KINDS
// ============================================================================

/// The metatype of a model element.
///
/// Maps to SysML v2 / KerML metaclasses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElementKind {
    // Namespaces and Packages
    Namespace,
    Package,
    LibraryPackage,

    // KerML Classifiers
    Class,
    DataType,
    Structure,
    Association,
    AssociationStructure,
    Interaction,
    Behavior,
    Function,
    Predicate,

    // SysML Definitions
    PartDefinition,
    ItemDefinition,
    ActionDefinition,
    PortDefinition,
    AttributeDefinition,
    ConnectionDefinition,
    InterfaceDefinition,
    AllocationDefinition,
    RequirementDefinition,
    ConstraintDefinition,
    StateDefinition,
    CalculationDefinition,
    UseCaseDefinition,
    AnalysisCaseDefinition,
    ConcernDefinition,
    ViewDefinition,
    ViewpointDefinition,
    RenderingDefinition,
    EnumerationDefinition,
    MetadataDefinition,

    // SysML Usages
    PartUsage,
    ItemUsage,
    ActionUsage,
    PortUsage,
    AttributeUsage,
    ConnectionUsage,
    InterfaceUsage,
    AllocationUsage,
    RequirementUsage,
    ConstraintUsage,
    StateUsage,
    TransitionUsage,
    CalculationUsage,
    ReferenceUsage,
    OccurrenceUsage,
    FlowConnectionUsage,
    SuccessionFlowConnectionUsage,

    // KerML Features
    Feature,
    Step,
    Expression,
    BooleanExpression,
    Invariant,
    Connector,
    BindingConnector,
    Succession,
    Flow,

    // Multiplicity and Literals
    MultiplicityRange,
    LiteralInteger,
    LiteralInfinity,
    LiteralBoolean,
    LiteralString,
    NullExpression,

    // Expressions
    FeatureReferenceExpression,
    OperatorExpression,
    InvocationExpression,
    FeatureChainExpression,
    ConstructorExpression,

    // Relationships (first-class)
    Membership,
    OwningMembership,
    FeatureMembership,
    ReturnParameterMembership,
    ParameterMembership,
    EndFeatureMembership,
    ResultExpressionMembership,
    Import,
    NamespaceImport,
    MembershipImport,
    Specialization,
    FeatureTyping,
    Subsetting,
    ReferenceSubsetting,
    CrossSubsetting,
    Redefinition,
    Conjugation,
    FeatureValue,
    FeatureChaining,
    FeatureInverting,
    Intersecting,
    Disjoining,
    Unioning,

    // Comments and documentation
    Comment,
    Documentation,
    TextualRepresentation,

    // Annotations
    MetadataUsage,
    AnnotatingElement,
    Annotation,

    // Classifiers
    Classifier,
    Metaclass,

    // Generic
    Other,
}

impl ElementKind {
    /// Returns true if this is a definition (type-like).
    pub fn is_definition(&self) -> bool {
        matches!(
            self,
            Self::Package
                | Self::LibraryPackage
                | Self::Class
                | Self::DataType
                | Self::Structure
                | Self::Association
                | Self::AssociationStructure
                | Self::Interaction
                | Self::Behavior
                | Self::Function
                | Self::Predicate
                | Self::PartDefinition
                | Self::ItemDefinition
                | Self::ActionDefinition
                | Self::PortDefinition
                | Self::AttributeDefinition
                | Self::ConnectionDefinition
                | Self::InterfaceDefinition
                | Self::AllocationDefinition
                | Self::RequirementDefinition
                | Self::ConstraintDefinition
                | Self::StateDefinition
                | Self::CalculationDefinition
                | Self::UseCaseDefinition
                | Self::AnalysisCaseDefinition
                | Self::ConcernDefinition
                | Self::ViewDefinition
                | Self::ViewpointDefinition
                | Self::RenderingDefinition
                | Self::EnumerationDefinition
                | Self::MetadataDefinition
        )
    }

    /// Returns true if this is a usage (instance-like).
    pub fn is_usage(&self) -> bool {
        matches!(
            self,
            Self::PartUsage
                | Self::ItemUsage
                | Self::ActionUsage
                | Self::PortUsage
                | Self::AttributeUsage
                | Self::ConnectionUsage
                | Self::InterfaceUsage
                | Self::AllocationUsage
                | Self::RequirementUsage
                | Self::ConstraintUsage
                | Self::StateUsage
                | Self::TransitionUsage
                | Self::CalculationUsage
                | Self::ReferenceUsage
                | Self::OccurrenceUsage
                | Self::FlowConnectionUsage
                | Self::SuccessionFlowConnectionUsage
                | Self::Feature
                | Self::Step
                | Self::Expression
                | Self::BooleanExpression
                | Self::Invariant
        )
    }

    /// Returns true if this is a relationship.
    pub fn is_relationship(&self) -> bool {
        matches!(
            self,
            Self::Membership
                | Self::OwningMembership
                | Self::FeatureMembership
                | Self::ReturnParameterMembership
                | Self::ParameterMembership
                | Self::EndFeatureMembership
                | Self::ResultExpressionMembership
                | Self::Import
                | Self::NamespaceImport
                | Self::MembershipImport
                | Self::Specialization
                | Self::FeatureTyping
                | Self::Subsetting
                | Self::ReferenceSubsetting
                | Self::CrossSubsetting
                | Self::Redefinition
                | Self::Conjugation
                | Self::FeatureValue
                | Self::FeatureChaining
                | Self::FeatureInverting
                | Self::Intersecting
                | Self::Disjoining
                | Self::Unioning
                | Self::Annotation
        )
    }

    /// Returns true if this is a SysML (not KerML) element kind.
    /// SysML elements use `declaredName` instead of `name`.
    pub fn is_sysml(&self) -> bool {
        matches!(
            self,
            Self::Namespace
                | Self::Package
                | Self::LibraryPackage
                | Self::PartDefinition
                | Self::ItemDefinition
                | Self::ActionDefinition
                | Self::PortDefinition
                | Self::AttributeDefinition
                | Self::ConnectionDefinition
                | Self::InterfaceDefinition
                | Self::AllocationDefinition
                | Self::RequirementDefinition
                | Self::ConstraintDefinition
                | Self::UseCaseDefinition
                | Self::ConcernDefinition
                | Self::ViewDefinition
                | Self::ViewpointDefinition
                | Self::RenderingDefinition
                | Self::StateDefinition
                | Self::TransitionUsage
                | Self::CalculationDefinition
                | Self::AnalysisCaseDefinition
                | Self::EnumerationDefinition
                | Self::MetadataDefinition
                | Self::PartUsage
                | Self::ItemUsage
                | Self::ActionUsage
                | Self::PortUsage
                | Self::AttributeUsage
                | Self::ConnectionUsage
                | Self::InterfaceUsage
                | Self::AllocationUsage
                | Self::RequirementUsage
                | Self::ConstraintUsage
                | Self::StateUsage
                | Self::CalculationUsage
                | Self::ReferenceUsage
                | Self::OccurrenceUsage
                | Self::FlowConnectionUsage
                | Self::SuccessionFlowConnectionUsage
                | Self::MetadataUsage
        )
    }

    /// Get the XMI type name for this kind.
    pub fn xmi_type(&self) -> &'static str {
        match self {
            Self::Namespace => "sysml:Namespace",
            Self::Package => "sysml:Package",
            Self::LibraryPackage => "sysml:LibraryPackage",
            Self::Class => "kerml:Class",
            Self::DataType => "kerml:DataType",
            Self::Structure => "kerml:Structure",
            Self::Association => "kerml:Association",
            Self::AssociationStructure => "kerml:AssociationStructure",
            Self::Interaction => "kerml:Interaction",
            Self::Behavior => "kerml:Behavior",
            Self::Function => "kerml:Function",
            Self::Predicate => "kerml:Predicate",
            Self::PartDefinition => "sysml:PartDefinition",
            Self::ItemDefinition => "sysml:ItemDefinition",
            Self::ActionDefinition => "sysml:ActionDefinition",
            Self::PortDefinition => "sysml:PortDefinition",
            Self::AttributeDefinition => "sysml:AttributeDefinition",
            Self::ConnectionDefinition => "sysml:ConnectionDefinition",
            Self::InterfaceDefinition => "sysml:InterfaceDefinition",
            Self::AllocationDefinition => "sysml:AllocationDefinition",
            Self::RequirementDefinition => "sysml:RequirementDefinition",
            Self::ConstraintDefinition => "sysml:ConstraintDefinition",
            Self::StateDefinition => "sysml:StateDefinition",
            Self::CalculationDefinition => "sysml:CalculationDefinition",
            Self::UseCaseDefinition => "sysml:UseCaseDefinition",
            Self::AnalysisCaseDefinition => "sysml:AnalysisCaseDefinition",
            Self::ConcernDefinition => "sysml:ConcernDefinition",
            Self::ViewDefinition => "sysml:ViewDefinition",
            Self::ViewpointDefinition => "sysml:ViewpointDefinition",
            Self::RenderingDefinition => "sysml:RenderingDefinition",
            Self::EnumerationDefinition => "sysml:EnumerationDefinition",
            Self::MetadataDefinition => "sysml:MetadataDefinition",
            Self::PartUsage => "sysml:PartUsage",
            Self::ItemUsage => "sysml:ItemUsage",
            Self::ActionUsage => "sysml:ActionUsage",
            Self::PortUsage => "sysml:PortUsage",
            Self::AttributeUsage => "sysml:AttributeUsage",
            Self::ConnectionUsage => "sysml:ConnectionUsage",
            Self::InterfaceUsage => "sysml:InterfaceUsage",
            Self::AllocationUsage => "sysml:AllocationUsage",
            Self::RequirementUsage => "sysml:RequirementUsage",
            Self::ConstraintUsage => "sysml:ConstraintUsage",
            Self::StateUsage => "sysml:StateUsage",
            Self::TransitionUsage => "sysml:TransitionUsage",
            Self::CalculationUsage => "sysml:CalculationUsage",
            Self::ReferenceUsage => "sysml:ReferenceUsage",
            Self::OccurrenceUsage => "sysml:OccurrenceUsage",
            Self::FlowConnectionUsage => "sysml:FlowConnectionUsage",
            Self::SuccessionFlowConnectionUsage => "sysml:SuccessionFlowConnectionUsage",
            Self::Feature => "kerml:Feature",
            Self::Step => "kerml:Step",
            Self::Expression => "kerml:Expression",
            Self::BooleanExpression => "kerml:BooleanExpression",
            Self::Invariant => "kerml:Invariant",
            Self::Connector => "kerml:Connector",
            Self::BindingConnector => "kerml:BindingConnector",
            Self::Succession => "kerml:Succession",
            Self::Flow => "kerml:Flow",
            Self::MultiplicityRange => "kerml:MultiplicityRange",
            Self::LiteralInteger => "kerml:LiteralInteger",
            Self::LiteralInfinity => "kerml:LiteralInfinity",
            Self::LiteralBoolean => "kerml:LiteralBoolean",
            Self::LiteralString => "kerml:LiteralString",
            Self::NullExpression => "kerml:NullExpression",
            Self::FeatureReferenceExpression => "kerml:FeatureReferenceExpression",
            Self::OperatorExpression => "kerml:OperatorExpression",
            Self::InvocationExpression => "kerml:InvocationExpression",
            Self::FeatureChainExpression => "kerml:FeatureChainExpression",
            Self::ConstructorExpression => "kerml:ConstructorExpression",
            Self::Membership => "kerml:Membership",
            Self::OwningMembership => "kerml:OwningMembership",
            Self::FeatureMembership => "kerml:FeatureMembership",
            Self::ReturnParameterMembership => "kerml:ReturnParameterMembership",
            Self::ParameterMembership => "kerml:ParameterMembership",
            Self::EndFeatureMembership => "kerml:EndFeatureMembership",
            Self::ResultExpressionMembership => "kerml:ResultExpressionMembership",
            Self::Import => "kerml:Import",
            Self::NamespaceImport => "kerml:NamespaceImport",
            Self::MembershipImport => "kerml:MembershipImport",
            Self::Specialization => "kerml:Specialization",
            Self::FeatureTyping => "kerml:FeatureTyping",
            Self::Subsetting => "kerml:Subsetting",
            Self::ReferenceSubsetting => "kerml:ReferenceSubsetting",
            Self::CrossSubsetting => "kerml:CrossSubsetting",
            Self::Redefinition => "kerml:Redefinition",
            Self::Conjugation => "kerml:Conjugation",
            Self::FeatureValue => "kerml:FeatureValue",
            Self::FeatureChaining => "kerml:FeatureChaining",
            Self::FeatureInverting => "kerml:FeatureInverting",
            Self::Intersecting => "kerml:Intersecting",
            Self::Disjoining => "kerml:Disjoining",
            Self::Unioning => "kerml:Unioning",
            Self::Comment => "kerml:Comment",
            Self::Documentation => "kerml:Documentation",
            Self::TextualRepresentation => "kerml:TextualRepresentation",
            Self::MetadataUsage => "sysml:MetadataUsage",
            Self::AnnotatingElement => "kerml:AnnotatingElement",
            Self::Annotation => "kerml:Annotation",
            Self::Classifier => "kerml:Classifier",
            Self::Metaclass => "kerml:Metaclass",
            Self::Other => "kerml:Element",
        }
    }

    /// Get the xsi:type value for this kind (official XMI format).
    pub fn xsi_type(&self) -> &'static str {
        match self {
            Self::Package => "sysml:Package",
            Self::LibraryPackage => "sysml:LibraryPackage",
            Self::Class => "sysml:Class",
            Self::DataType => "sysml:DataType",
            Self::Structure => "sysml:Structure",
            Self::Association => "sysml:Association",
            Self::AssociationStructure => "sysml:AssociationStructure",
            Self::Interaction => "sysml:Interaction",
            Self::Behavior => "sysml:Behavior",
            Self::Function => "sysml:Function",
            Self::Predicate => "sysml:Predicate",
            Self::PartDefinition => "sysml:PartDefinition",
            Self::ItemDefinition => "sysml:ItemDefinition",
            Self::ActionDefinition => "sysml:ActionDefinition",
            Self::PortDefinition => "sysml:PortDefinition",
            Self::AttributeDefinition => "sysml:AttributeDefinition",
            Self::ConnectionDefinition => "sysml:ConnectionDefinition",
            Self::InterfaceDefinition => "sysml:InterfaceDefinition",
            Self::AllocationDefinition => "sysml:AllocationDefinition",
            Self::RequirementDefinition => "sysml:RequirementDefinition",
            Self::ConstraintDefinition => "sysml:ConstraintDefinition",
            Self::StateDefinition => "sysml:StateDefinition",
            Self::CalculationDefinition => "sysml:CalculationDefinition",
            Self::UseCaseDefinition => "sysml:UseCaseDefinition",
            Self::AnalysisCaseDefinition => "sysml:AnalysisCaseDefinition",
            Self::ConcernDefinition => "sysml:ConcernDefinition",
            Self::ViewDefinition => "sysml:ViewDefinition",
            Self::ViewpointDefinition => "sysml:ViewpointDefinition",
            Self::RenderingDefinition => "sysml:RenderingDefinition",
            Self::EnumerationDefinition => "sysml:EnumerationDefinition",
            Self::MetadataDefinition => "sysml:MetadataDefinition",
            Self::PartUsage => "sysml:PartUsage",
            Self::ItemUsage => "sysml:ItemUsage",
            Self::ActionUsage => "sysml:ActionUsage",
            Self::PortUsage => "sysml:PortUsage",
            Self::AttributeUsage => "sysml:AttributeUsage",
            Self::ConnectionUsage => "sysml:ConnectionUsage",
            Self::InterfaceUsage => "sysml:InterfaceUsage",
            Self::AllocationUsage => "sysml:AllocationUsage",
            Self::RequirementUsage => "sysml:RequirementUsage",
            Self::ConstraintUsage => "sysml:ConstraintUsage",
            Self::StateUsage => "sysml:StateUsage",
            Self::TransitionUsage => "sysml:TransitionUsage",
            Self::CalculationUsage => "sysml:CalculationUsage",
            Self::ReferenceUsage => "sysml:ReferenceUsage",
            Self::OccurrenceUsage => "sysml:OccurrenceUsage",
            Self::FlowConnectionUsage => "sysml:FlowConnectionUsage",
            Self::SuccessionFlowConnectionUsage => "sysml:SuccessionFlowConnectionUsage",
            Self::Feature => "sysml:Feature",
            Self::Step => "sysml:Step",
            Self::Expression => "sysml:Expression",
            Self::BooleanExpression => "sysml:BooleanExpression",
            Self::Invariant => "sysml:Invariant",
            Self::Connector => "sysml:Connector",
            Self::BindingConnector => "sysml:BindingConnector",
            Self::Succession => "sysml:Succession",
            Self::Flow => "sysml:Flow",
            Self::MultiplicityRange => "sysml:MultiplicityRange",
            Self::LiteralInteger => "sysml:LiteralInteger",
            Self::LiteralInfinity => "sysml:LiteralInfinity",
            Self::LiteralBoolean => "sysml:LiteralBoolean",
            Self::LiteralString => "sysml:LiteralString",
            Self::NullExpression => "sysml:NullExpression",
            Self::FeatureReferenceExpression => "sysml:FeatureReferenceExpression",
            Self::OperatorExpression => "sysml:OperatorExpression",
            Self::InvocationExpression => "sysml:InvocationExpression",
            Self::FeatureChainExpression => "sysml:FeatureChainExpression",
            Self::ConstructorExpression => "sysml:ConstructorExpression",
            Self::Membership => "sysml:Membership",
            Self::OwningMembership => "sysml:OwningMembership",
            Self::FeatureMembership => "sysml:FeatureMembership",
            Self::ReturnParameterMembership => "sysml:ReturnParameterMembership",
            Self::ParameterMembership => "sysml:ParameterMembership",
            Self::EndFeatureMembership => "sysml:EndFeatureMembership",
            Self::ResultExpressionMembership => "sysml:ResultExpressionMembership",
            Self::Import => "sysml:Import",
            Self::NamespaceImport => "sysml:NamespaceImport",
            Self::MembershipImport => "sysml:MembershipImport",
            Self::Specialization => "sysml:Subclassification",
            Self::FeatureTyping => "sysml:FeatureTyping",
            Self::Subsetting => "sysml:Subsetting",
            Self::ReferenceSubsetting => "sysml:ReferenceSubsetting",
            Self::CrossSubsetting => "sysml:CrossSubsetting",
            Self::Redefinition => "sysml:Redefinition",
            Self::Conjugation => "sysml:Conjugation",
            Self::FeatureValue => "sysml:FeatureValue",
            Self::FeatureChaining => "sysml:FeatureChaining",
            Self::FeatureInverting => "sysml:FeatureInverting",
            Self::Intersecting => "sysml:Intersecting",
            Self::Disjoining => "sysml:Disjoining",
            Self::Unioning => "sysml:Unioning",
            Self::Comment => "sysml:Comment",
            Self::Documentation => "sysml:Documentation",
            Self::TextualRepresentation => "sysml:TextualRepresentation",
            Self::MetadataUsage => "sysml:MetadataUsage",
            Self::AnnotatingElement => "sysml:AnnotatingElement",
            Self::Annotation => "sysml:Annotation",
            Self::Classifier => "sysml:Classifier",
            Self::Metaclass => "sysml:Metaclass",
            Self::Other => "sysml:Element",
            Self::Namespace => "sysml:Namespace",
        }
    }

    /// Parse from XMI type name.
    pub fn from_xmi_type(xmi_type: &str) -> Self {
        // Strip namespace prefix if present
        let type_name = xmi_type.rsplit(':').next().unwrap_or(xmi_type);

        match type_name {
            "Namespace" => Self::Namespace,
            "Package" => Self::Package,
            "LibraryPackage" => Self::LibraryPackage,
            "Class" => Self::Class,
            "DataType" => Self::DataType,
            "Structure" => Self::Structure,
            "Association" => Self::Association,
            "AssociationStructure" => Self::AssociationStructure,
            "Interaction" => Self::Interaction,
            "Behavior" => Self::Behavior,
            "Function" => Self::Function,
            "Predicate" => Self::Predicate,
            "PartDefinition" => Self::PartDefinition,
            "ItemDefinition" => Self::ItemDefinition,
            "ActionDefinition" => Self::ActionDefinition,
            "PortDefinition" => Self::PortDefinition,
            "AttributeDefinition" => Self::AttributeDefinition,
            "ConnectionDefinition" => Self::ConnectionDefinition,
            "InterfaceDefinition" => Self::InterfaceDefinition,
            "AllocationDefinition" => Self::AllocationDefinition,
            "RequirementDefinition" => Self::RequirementDefinition,
            "ConstraintDefinition" => Self::ConstraintDefinition,
            "StateDefinition" => Self::StateDefinition,
            "CalculationDefinition" => Self::CalculationDefinition,
            "UseCaseDefinition" => Self::UseCaseDefinition,
            "AnalysisCaseDefinition" => Self::AnalysisCaseDefinition,
            "ConcernDefinition" => Self::ConcernDefinition,
            "ViewDefinition" => Self::ViewDefinition,
            "ViewpointDefinition" => Self::ViewpointDefinition,
            "RenderingDefinition" => Self::RenderingDefinition,
            "EnumerationDefinition" => Self::EnumerationDefinition,
            "MetadataDefinition" => Self::MetadataDefinition,
            "PartUsage" => Self::PartUsage,
            "ItemUsage" => Self::ItemUsage,
            "ActionUsage" => Self::ActionUsage,
            "PortUsage" => Self::PortUsage,
            "AttributeUsage" => Self::AttributeUsage,
            "ConnectionUsage" => Self::ConnectionUsage,
            "InterfaceUsage" => Self::InterfaceUsage,
            "AllocationUsage" => Self::AllocationUsage,
            "RequirementUsage" => Self::RequirementUsage,
            "ConstraintUsage" => Self::ConstraintUsage,
            "StateUsage" => Self::StateUsage,
            "TransitionUsage" => Self::TransitionUsage,
            "CalculationUsage" => Self::CalculationUsage,
            "ReferenceUsage" => Self::ReferenceUsage,
            "OccurrenceUsage" => Self::OccurrenceUsage,
            "FlowConnectionUsage" => Self::FlowConnectionUsage,
            "SuccessionFlowConnectionUsage" => Self::SuccessionFlowConnectionUsage,
            "Feature" => Self::Feature,
            "Step" => Self::Step,
            "Expression" => Self::Expression,
            "BooleanExpression" => Self::BooleanExpression,
            "Invariant" => Self::Invariant,
            "Connector" => Self::Connector,
            "BindingConnector" => Self::BindingConnector,
            "Succession" => Self::Succession,
            "Flow" => Self::Flow,
            "MultiplicityRange" => Self::MultiplicityRange,
            "LiteralInteger" => Self::LiteralInteger,
            "LiteralInfinity" => Self::LiteralInfinity,
            "LiteralBoolean" => Self::LiteralBoolean,
            "LiteralString" => Self::LiteralString,
            "NullExpression" => Self::NullExpression,
            "FeatureReferenceExpression" => Self::FeatureReferenceExpression,
            "OperatorExpression" => Self::OperatorExpression,
            "InvocationExpression" => Self::InvocationExpression,
            "FeatureChainExpression" => Self::FeatureChainExpression,
            "ConstructorExpression" => Self::ConstructorExpression,
            "Membership" => Self::Membership,
            "OwningMembership" => Self::OwningMembership,
            "FeatureMembership" => Self::FeatureMembership,
            "ReturnParameterMembership" => Self::ReturnParameterMembership,
            "ParameterMembership" => Self::ParameterMembership,
            "EndFeatureMembership" => Self::EndFeatureMembership,
            "ResultExpressionMembership" => Self::ResultExpressionMembership,
            "Import" => Self::Import,
            "NamespaceImport" => Self::NamespaceImport,
            "MembershipImport" => Self::MembershipImport,
            "Specialization" | "Subclassification" => Self::Specialization,
            "FeatureTyping" => Self::FeatureTyping,
            "Subsetting" => Self::Subsetting,
            "ReferenceSubsetting" => Self::ReferenceSubsetting,
            "CrossSubsetting" => Self::CrossSubsetting,
            "Redefinition" => Self::Redefinition,
            "Conjugation" => Self::Conjugation,
            "FeatureValue" => Self::FeatureValue,
            "FeatureChaining" => Self::FeatureChaining,
            "FeatureInverting" => Self::FeatureInverting,
            "Intersecting" => Self::Intersecting,
            "Disjoining" => Self::Disjoining,
            "Unioning" => Self::Unioning,
            "Comment" => Self::Comment,
            "Documentation" => Self::Documentation,
            "TextualRepresentation" => Self::TextualRepresentation,
            "MetadataUsage" => Self::MetadataUsage,
            "AnnotatingElement" => Self::AnnotatingElement,
            "Annotation" => Self::Annotation,
            "Classifier" => Self::Classifier,
            "Metaclass" => Self::Metaclass,
            _ => Self::Other,
        }
    }

    /// Get the JSON-LD @type value.
    pub fn jsonld_type(&self) -> &'static str {
        // JSON-LD uses the same type names without namespace prefix
        self.xmi_type().rsplit(':').next().unwrap_or("Element")
    }
}

// ============================================================================
// ELEMENT
// ============================================================================

/// A model element with its properties.
#[derive(Clone, Debug)]
pub struct Element {
    /// Unique identifier.
    pub id: ElementId,
    /// The metatype.
    pub kind: ElementKind,
    /// The declared name (may be None for anonymous elements).
    pub name: Option<Arc<str>>,
    /// Short name alias.
    pub short_name: Option<Arc<str>>,
    /// Qualified name (computed from ownership hierarchy).
    pub qualified_name: Option<Arc<str>>,
    /// The owning element's ID (None for root elements).
    pub owner: Option<ElementId>,
    /// IDs of directly owned elements.
    pub owned_elements: Vec<ElementId>,
    /// Documentation text.
    pub documentation: Option<Arc<str>>,
    /// Whether this element is abstract.
    pub is_abstract: bool,
    /// Whether this is a variation (SysML).
    pub is_variation: bool,
    /// Whether this feature is derived.
    pub is_derived: bool,
    /// Whether this feature is read-only.
    pub is_readonly: bool,
    /// Whether this state is parallel (SysML).
    pub is_parallel: bool,
    /// Whether this is an individual (singleton occurrence).
    pub is_individual: bool,
    /// Whether this is an end feature (connector endpoint).
    pub is_end: bool,
    /// Whether this has a default value.
    pub is_default: bool,
    /// Whether values are ordered.
    pub is_ordered: bool,
    /// Whether values are nonunique (can have duplicates).
    pub is_nonunique: bool,
    /// Whether this is a portion (slice of occurrence).
    pub is_portion: bool,
    /// Visibility (public, private, protected).
    pub visibility: Visibility,
    /// Additional properties as key-value pairs (IndexMap preserves order).
    pub properties: IndexMap<Arc<str>, PropertyValue>,
}

impl Element {
    /// Create a new element with the given ID and kind.
    pub fn new(id: impl Into<ElementId>, kind: ElementKind) -> Self {
        Self {
            id: id.into(),
            kind,
            name: None,
            short_name: None,
            qualified_name: None,
            owner: None,
            owned_elements: Vec::new(),
            documentation: None,
            is_abstract: false,
            is_variation: false,
            is_derived: false,
            is_readonly: false,
            is_parallel: false,
            is_individual: false,
            is_end: false,
            is_default: false,
            is_ordered: false,
            is_nonunique: false,
            is_portion: false,
            visibility: Visibility::Public,
            properties: IndexMap::new(),
        }
    }

    /// Set the name.
    pub fn with_name(mut self, name: impl Into<Arc<str>>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the qualified name.
    pub fn with_qualified_name(mut self, qualified_name: impl Into<Arc<str>>) -> Self {
        self.qualified_name = Some(qualified_name.into());
        self
    }

    /// Set the short name.
    pub fn with_short_name(mut self, short_name: impl Into<Arc<str>>) -> Self {
        self.short_name = Some(short_name.into());
        self
    }

    /// Set the owner.
    pub fn with_owner(mut self, owner: impl Into<ElementId>) -> Self {
        self.owner = Some(owner.into());
        self
    }

    /// Add an owned element ID.
    pub fn with_owned(mut self, owned: impl Into<ElementId>) -> Self {
        self.owned_elements.push(owned.into());
        self
    }

    /// Set a property value.
    pub fn with_property(mut self, key: impl Into<Arc<str>>, value: PropertyValue) -> Self {
        self.properties.insert(key.into(), value);
        self
    }

    /// Set isAbstract (syncs to property for roundtrip fidelity).
    pub fn set_abstract(&mut self, value: bool) {
        self.is_abstract = value;
        self.properties
            .insert(Arc::from("isAbstract"), PropertyValue::Boolean(value));
    }

    /// Set isVariation (syncs to property for roundtrip fidelity).
    pub fn set_variation(&mut self, value: bool) {
        self.is_variation = value;
        self.properties
            .insert(Arc::from("isVariation"), PropertyValue::Boolean(value));
    }

    /// Set isDerived (syncs to property for roundtrip fidelity).
    pub fn set_derived(&mut self, value: bool) {
        self.is_derived = value;
        self.properties
            .insert(Arc::from("isDerived"), PropertyValue::Boolean(value));
    }

    /// Set isReadOnly (syncs to property for roundtrip fidelity).
    pub fn set_readonly(&mut self, value: bool) {
        self.is_readonly = value;
        self.properties
            .insert(Arc::from("isReadOnly"), PropertyValue::Boolean(value));
    }

    /// Set isParallel (syncs to property for roundtrip fidelity).
    pub fn set_parallel(&mut self, value: bool) {
        self.is_parallel = value;
        self.properties
            .insert(Arc::from("isParallel"), PropertyValue::Boolean(value));
    }

    /// Set isIndividual (syncs to property for roundtrip fidelity).
    pub fn set_individual(&mut self, value: bool) {
        self.is_individual = value;
        self.properties
            .insert(Arc::from("isIndividual"), PropertyValue::Boolean(value));
    }

    /// Set isEnd (syncs to property for roundtrip fidelity).
    pub fn set_end(&mut self, value: bool) {
        self.is_end = value;
        self.properties
            .insert(Arc::from("isEnd"), PropertyValue::Boolean(value));
    }

    /// Set isDefault (syncs to property for roundtrip fidelity).
    pub fn set_default(&mut self, value: bool) {
        self.is_default = value;
        self.properties
            .insert(Arc::from("isDefault"), PropertyValue::Boolean(value));
    }

    /// Set isOrdered (syncs to property for roundtrip fidelity).
    pub fn set_ordered(&mut self, value: bool) {
        self.is_ordered = value;
        self.properties
            .insert(Arc::from("isOrdered"), PropertyValue::Boolean(value));
    }

    /// Set isNonunique (syncs to property for roundtrip fidelity).
    pub fn set_nonunique(&mut self, value: bool) {
        self.is_nonunique = value;
        self.properties
            .insert(Arc::from("isNonunique"), PropertyValue::Boolean(value));
    }

    /// Set isPortion (syncs to property for roundtrip fidelity).
    pub fn set_portion(&mut self, value: bool) {
        self.is_portion = value;
        self.properties
            .insert(Arc::from("isPortion"), PropertyValue::Boolean(value));
    }
}

/// Visibility of an element.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Visibility {
    #[default]
    Public,
    Private,
    Protected,
}

/// A property value that can be stored on an element.
#[derive(Clone, Debug, PartialEq)]
pub enum PropertyValue {
    /// String value.
    String(Arc<str>),
    /// Integer value.
    Integer(i64),
    /// Floating-point value.
    Real(f64),
    /// Boolean value.
    Boolean(bool),
    /// Reference to another element by ID.
    Reference(ElementId),
    /// List of values.
    List(Vec<PropertyValue>),
}

impl From<&str> for PropertyValue {
    fn from(s: &str) -> Self {
        Self::String(s.into())
    }
}

impl From<String> for PropertyValue {
    fn from(s: String) -> Self {
        Self::String(s.into())
    }
}

impl From<i64> for PropertyValue {
    fn from(v: i64) -> Self {
        Self::Integer(v)
    }
}

impl From<f64> for PropertyValue {
    fn from(v: f64) -> Self {
        Self::Real(v)
    }
}

impl From<bool> for PropertyValue {
    fn from(v: bool) -> Self {
        Self::Boolean(v)
    }
}

impl From<ElementId> for PropertyValue {
    fn from(id: ElementId) -> Self {
        Self::Reference(id)
    }
}

// ============================================================================
// RELATIONSHIP
// ============================================================================

/// A relationship between two elements.
///
/// In the KerML/SysML metamodel, relationships are first-class elements.
/// This struct captures the essential information for interchange.
#[derive(Clone, Debug)]
pub struct Relationship {
    /// Unique identifier for the relationship itself.
    pub id: ElementId,
    /// The kind of relationship.
    pub kind: RelationshipKind,
    /// The source element ID.
    pub source: ElementId,
    /// The target element ID.
    pub target: ElementId,
    /// The owning element (usually the source).
    pub owner: Option<ElementId>,
}

impl Relationship {
    /// Create a new relationship.
    pub fn new(
        id: impl Into<ElementId>,
        kind: RelationshipKind,
        source: impl Into<ElementId>,
        target: impl Into<ElementId>,
    ) -> Self {
        Self {
            id: id.into(),
            kind,
            source: source.into(),
            target: target.into(),
            owner: None,
        }
    }
}

/// The kind of relationship.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelationshipKind {
    /// Specialization (general → specific).
    Specialization,
    /// Feature typing (feature → type).
    FeatureTyping,
    /// Subsetting (feature → subsetted feature).
    Subsetting,
    /// Redefinition (feature → redefined feature).
    Redefinition,
    /// Conjugation (conjugated port → original).
    Conjugation,
    /// Membership (namespace → member).
    Membership,
    /// Owning membership (owner → owned).
    OwningMembership,
    /// Feature membership (type → feature).
    FeatureMembership,
    /// Namespace import.
    NamespaceImport,
    /// Membership import.
    MembershipImport,
    /// Dependency.
    Dependency,
    /// Requirement satisfaction.
    Satisfaction,
    /// Requirement verification.
    Verification,
    /// Allocation.
    Allocation,
    /// Connection.
    Connection,
    /// Flow connection.
    FlowConnection,
    /// Succession.
    Succession,
    /// Feature chaining.
    FeatureChaining,
    /// Disjoining (type disjoint from another type).
    Disjoining,
}

impl RelationshipKind {
    /// Get the XMI type name.
    pub fn xmi_type(&self) -> &'static str {
        match self {
            Self::Specialization => "kerml:Specialization",
            Self::FeatureTyping => "kerml:FeatureTyping",
            Self::Subsetting => "kerml:Subsetting",
            Self::Redefinition => "kerml:Redefinition",
            Self::Conjugation => "kerml:Conjugation",
            Self::Membership => "kerml:Membership",
            Self::OwningMembership => "kerml:OwningMembership",
            Self::FeatureMembership => "kerml:FeatureMembership",
            Self::NamespaceImport => "kerml:NamespaceImport",
            Self::MembershipImport => "kerml:MembershipImport",
            Self::Dependency => "kerml:Dependency",
            Self::Satisfaction => "sysml:SatisfyRequirementUsage",
            Self::Verification => "sysml:RequirementVerificationMembership",
            Self::Allocation => "sysml:AllocationUsage",
            Self::Connection => "sysml:ConnectionUsage",
            Self::FlowConnection => "sysml:FlowConnectionUsage",
            Self::Succession => "sysml:SuccessionAsUsage",
            Self::FeatureChaining => "kerml:FeatureChaining",
            Self::Disjoining => "kerml:Disjoining",
        }
    }

    /// Parse from XMI type name.
    pub fn from_xmi_type(xmi_type: &str) -> Option<Self> {
        let type_name = xmi_type.rsplit(':').next().unwrap_or(xmi_type);
        match type_name {
            "Specialization" => Some(Self::Specialization),
            "FeatureTyping" => Some(Self::FeatureTyping),
            "Subsetting" => Some(Self::Subsetting),
            "Redefinition" => Some(Self::Redefinition),
            "Conjugation" => Some(Self::Conjugation),
            "Membership" => Some(Self::Membership),
            "OwningMembership" => Some(Self::OwningMembership),
            "FeatureMembership" => Some(Self::FeatureMembership),
            "NamespaceImport" => Some(Self::NamespaceImport),
            "MembershipImport" => Some(Self::MembershipImport),
            "Dependency" => Some(Self::Dependency),
            "SatisfyRequirementUsage" => Some(Self::Satisfaction),
            "RequirementVerificationMembership" => Some(Self::Verification),
            "AllocationUsage" => Some(Self::Allocation),
            "ConnectionUsage" => Some(Self::Connection),
            "FlowConnectionUsage" => Some(Self::FlowConnection),
            "SuccessionAsUsage" => Some(Self::Succession),
            "FeatureChaining" => Some(Self::FeatureChaining),
            "Disjoining" => Some(Self::Disjoining),
            _ => None,
        }
    }
}

// ============================================================================
// MODEL
// ============================================================================

/// A complete SysML/KerML model.
///
/// This is a standalone representation that can be:
/// - Loaded from XMI, KPAR, or JSON-LD
/// - Exported to various formats
/// - Integrated into a `RootDatabase` for IDE features
#[derive(Clone, Debug, Default)]
pub struct Model {
    /// All elements by ID (IndexMap preserves insertion order for deterministic serialization).
    pub elements: IndexMap<ElementId, Element>,
    /// All relationships.
    pub relationships: Vec<Relationship>,
    /// Root element IDs (top-level packages).
    pub roots: Vec<ElementId>,
    /// Metadata about the model.
    pub metadata: ModelMetadata,
}

impl Model {
    /// Create a new empty model.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an element to the model.
    pub fn add_element(&mut self, element: Element) -> &ElementId {
        let id = element.id.clone();
        if element.owner.is_none() {
            self.roots.push(id.clone());
        }
        self.elements.insert(id.clone(), element);
        // Return reference to the ID in the map
        &self.elements.get(&id).unwrap().id
    }

    /// Add a relationship to the model.
    pub fn add_relationship(&mut self, relationship: Relationship) {
        self.relationships.push(relationship);
    }

    /// Get an element by ID.
    pub fn get(&self, id: &ElementId) -> Option<&Element> {
        self.elements.get(id)
    }

    /// Get a mutable element by ID.
    pub fn get_mut(&mut self, id: &ElementId) -> Option<&mut Element> {
        self.elements.get_mut(id)
    }

    /// Iterate over all elements.
    pub fn iter_elements(&self) -> impl Iterator<Item = &Element> {
        self.elements.values()
    }

    /// Iterate over root elements.
    pub fn iter_roots(&self) -> impl Iterator<Item = &Element> {
        self.roots.iter().filter_map(|id| self.elements.get(id))
    }

    /// Get relationships where the given element is the source.
    pub fn relationships_from<'a>(
        &'a self,
        source: &'a ElementId,
    ) -> impl Iterator<Item = &'a Relationship> {
        self.relationships
            .iter()
            .filter(move |r| &r.source == source)
    }

    /// Get relationships where the given element is the target.
    pub fn relationships_to<'a>(
        &'a self,
        target: &'a ElementId,
    ) -> impl Iterator<Item = &'a Relationship> {
        self.relationships
            .iter()
            .filter(move |r| &r.target == target)
    }

    /// Get the number of elements.
    pub fn element_count(&self) -> usize {
        self.elements.len()
    }

    /// Get the number of relationships.
    pub fn relationship_count(&self) -> usize {
        self.relationships.len()
    }
}

/// Metadata about a model.
#[derive(Clone, Debug, Default)]
pub struct ModelMetadata {
    /// Name of the model/project.
    pub name: Option<String>,
    /// Version string.
    pub version: Option<String>,
    /// Description.
    pub description: Option<String>,
    /// URI of the model.
    pub uri: Option<String>,
    /// SysML/KerML version this model conforms to.
    pub sysml_version: Option<String>,
    /// Tool that created this model.
    pub tool: Option<String>,
    /// Creation timestamp.
    pub created: Option<String>,
    /// Last modified timestamp.
    pub modified: Option<String>,
    /// Declared XML namespaces (for roundtrip fidelity).
    /// Maps prefix -> namespace URI (e.g., "sysml" -> "https://www.omg.org/spec/SysML/20250201").
    pub declared_namespaces: std::collections::HashMap<String, String>,
}

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

    #[test]
    fn test_element_id_generation() {
        let id1 = ElementId::generate();
        let id2 = ElementId::generate();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_element_builder() {
        let element = Element::new("pkg1", ElementKind::Package)
            .with_name("MyPackage")
            .with_short_name("mp");

        assert_eq!(element.id.as_str(), "pkg1");
        assert_eq!(element.name.as_deref(), Some("MyPackage"));
        assert_eq!(element.short_name.as_deref(), Some("mp"));
        assert_eq!(element.kind, ElementKind::Package);
    }

    #[test]
    fn test_model_add_elements() {
        let mut model = Model::new();

        let pkg = Element::new("pkg1", ElementKind::Package).with_name("Root");
        model.add_element(pkg);

        let part = Element::new("part1", ElementKind::PartDefinition)
            .with_name("Vehicle")
            .with_owner("pkg1");
        model.add_element(part);

        assert_eq!(model.element_count(), 2);
        assert_eq!(model.roots.len(), 1);
        assert_eq!(
            model.get(&ElementId::new("pkg1")).unwrap().name.as_deref(),
            Some("Root")
        );
    }

    #[test]
    fn test_model_relationships() {
        let mut model = Model::new();

        model.add_element(Element::new("def1", ElementKind::PartDefinition).with_name("Base"));
        model.add_element(Element::new("def2", ElementKind::PartDefinition).with_name("Derived"));

        model.add_relationship(Relationship::new(
            "rel1",
            RelationshipKind::Specialization,
            "def2",
            "def1",
        ));

        assert_eq!(model.relationship_count(), 1);
        let source_id = ElementId::new("def2");
        let rels: Vec<_> = model.relationships_from(&source_id).collect();
        assert_eq!(rels.len(), 1);
        assert_eq!(rels[0].target.as_str(), "def1");
    }

    #[test]
    fn test_element_kind_xmi_roundtrip() {
        let kinds = [
            ElementKind::Package,
            ElementKind::PartDefinition,
            ElementKind::ActionUsage,
            ElementKind::Specialization,
        ];

        for kind in kinds {
            let xmi_type = kind.xmi_type();
            let parsed = ElementKind::from_xmi_type(xmi_type);
            assert_eq!(kind, parsed, "Failed roundtrip for {xmi_type}");
        }
    }
}