openehr 0.6.0

openEHR Reference Model types, validation, paths, AQL parsing, and change-control security primitives
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
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
//! `OBJECT_ID` and its descendants.
//!
//! These are the identifiers openEHR uses to name things rather than to name
//! *values*: the record, the version, the archetype, the terminology. Each one
//! has a grammar, and each grammar is load-bearing — an `OBJECT_VERSION_ID` is
//! parsed into three parts by every server that implements the REST API,
//! because the middle part says which system created the version and the last
//! part says where it sits in the version tree.
//!
//! # Why these are parsed and not just held as strings
//!
//! It is tempting to keep `"87284370-…::ehr1.nhs.uk::2"` as a `String` and be
//! done. The cost shows up later and elsewhere: an unparsed version id makes
//! `preceding_version_uid` unverifiable, so a client can commit a version whose
//! parent belongs to a different versioned object and no layer notices until
//! the history is read back and does not connect. Parsing at the boundary is
//! what makes [`crate::rm::common::VersionedObject`] able to refuse that.

use crate::base::uid::Uid;
use crate::error::ParseError;
use core::fmt;
use core::str::FromStr;

/// A globally unique identifier for a versioned container, optionally with a
/// local extension.
///
/// Lexical form: `uid [ '::' extension ]`.
///
/// The extension exists for identifiers minted by a system that has its own
/// numbering inside a namespace — a hospital's MRN inside an issuing
/// authority's OID. It is an opaque string; openEHR places no grammar on it.
///
/// ```
/// use openehr::base::HierObjectId;
///
/// let plain: HierObjectId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B".parse().unwrap();
/// assert!(plain.extension().is_none());
///
/// let extended: HierObjectId = "2.16.840.1.113883.2.1.4.3::M123456".parse().unwrap();
/// assert_eq!(extended.extension(), Some("M123456"));
/// assert_eq!(extended.to_string(), "2.16.840.1.113883.2.1.4.3::M123456");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HierObjectId {
    root: Uid,
    extension: Option<String>,
}

impl HierObjectId {
    /// Builds an identifier from a root and an optional extension.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the extension is empty (an empty extension is
    /// not the same as no extension: `x::` and `x` would print differently and
    /// compare unequal, which is a distinction with no meaning) or contains
    /// `::` (which would make the printed form re-parse into different parts).
    pub fn new(root: Uid, extension: Option<String>) -> Result<Self, ParseError> {
        if let Some(ext) = &extension {
            if ext.is_empty() {
                return Err(ParseError::new("HIER_OBJECT_ID", "empty extension", ""));
            }
            if ext.contains("::") {
                return Err(ParseError::new(
                    "HIER_OBJECT_ID",
                    "extension contains the `::` separator",
                    ext,
                ));
            }
        }
        Ok(Self { root, extension })
    }

    /// Convenience constructor for the common case of a bare UUID.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the text is not a valid `UID`.
    pub fn from_uid_str(uid: &str) -> Result<Self, ParseError> {
        Ok(Self {
            root: uid.parse()?,
            extension: None,
        })
    }

    /// The identifying part.
    #[must_use]
    pub fn root(&self) -> &Uid {
        &self.root
    }

    /// The local extension, if any.
    #[must_use]
    pub fn extension(&self) -> Option<&str> {
        self.extension.as_deref()
    }
}

impl fmt::Display for HierObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.extension {
            Some(ext) => write!(f, "{}::{ext}", self.root),
            None => write!(f, "{}", self.root),
        }
    }
}

impl FromStr for HierObjectId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the root is not a valid `UID`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // split_once, not splitn(3): an extension containing `::` would be
        // silently truncated by a three-way split, and `new` rejects it.
        match s.split_once("::") {
            Some((root, ext)) => Self::new(root.parse()?, Some(ext.to_owned())),
            None => Self::new(s.parse()?, None),
        }
    }
}

crate::impl_valued_serde!(HierObjectId, "HIER_OBJECT_ID");

/// The identifier of one version of one versioned object.
///
/// Lexical form: `object_id '::' creating_system_id '::' version_tree_id`.
///
/// ```
/// use openehr::base::ObjectVersionId;
///
/// let id: ObjectVersionId =
///     "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.nhs.uk::2".parse().unwrap();
/// assert_eq!(id.object_id().to_string(), "87284370-2D4B-4E3D-A3F3-F303D2F4F34B");
/// assert_eq!(id.creating_system_id().to_string(), "ehr1.nhs.uk");
/// assert_eq!(id.version_tree_id().trunk_version(), 2);
/// assert!(!id.is_branch());
/// ```
///
/// A branch version carries three numbers in the last part:
///
/// ```
/// use openehr::base::ObjectVersionId;
///
/// let branch: ObjectVersionId =
///     "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.nhs.uk::2.1.4".parse().unwrap();
/// assert!(branch.is_branch());
/// assert_eq!(branch.version_tree_id().branch_number(), Some(1));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
// The `_id` suffix on all three fields is openEHR's naming, not redundancy this
// crate introduced. Renaming them to `object`, `creating_system`, `version_tree`
// would break the correspondence between this struct and the class definition a
// reader is holding open next to it, which is the one thing that makes an RM
// port checkable.
#[allow(clippy::struct_field_names)]
pub struct ObjectVersionId {
    object_id: Uid,
    creating_system_id: Uid,
    version_tree_id: VersionTreeId,
}

impl ObjectVersionId {
    /// Builds a version identifier from its three parts.
    #[must_use]
    pub fn new(object_id: Uid, creating_system_id: Uid, version_tree_id: VersionTreeId) -> Self {
        Self {
            object_id,
            creating_system_id,
            version_tree_id,
        }
    }

    /// The identifier of the versioned object this version belongs to.
    ///
    /// This is the part that must match across every version in one history,
    /// and the part `VERSIONED_OBJECT.uid` repeats.
    #[must_use]
    pub fn object_id(&self) -> &Uid {
        &self.object_id
    }

    /// The system that created this version.
    ///
    /// Two systems editing the same versioned object offline both produce
    /// `…::2`; the creating system id is what keeps those distinct, which is
    /// why openEHR puts it in the identifier rather than in an attribute.
    #[must_use]
    pub fn creating_system_id(&self) -> &Uid {
        &self.creating_system_id
    }

    /// Where this version sits in the version tree.
    #[must_use]
    pub fn version_tree_id(&self) -> &VersionTreeId {
        &self.version_tree_id
    }

    /// Whether this version is on a branch rather than the trunk.
    #[must_use]
    pub fn is_branch(&self) -> bool {
        self.version_tree_id.is_branch()
    }

    /// Whether two version ids name versions of the same versioned object.
    ///
    /// ```
    /// use openehr::base::ObjectVersionId;
    ///
    /// let v1: ObjectVersionId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::a.example::1".parse().unwrap();
    /// let v2: ObjectVersionId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::b.example::2".parse().unwrap();
    /// assert!(v1.same_object_as(&v2)); // different systems, same record
    /// ```
    #[must_use]
    pub fn same_object_as(&self, other: &Self) -> bool {
        self.object_id == other.object_id
    }
}

impl fmt::Display for ObjectVersionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}::{}::{}",
            self.object_id, self.creating_system_id, self.version_tree_id
        )
    }
}

impl FromStr for ObjectVersionId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] unless the text has exactly three `::`-separated
    /// parts, the first two are valid `UID`s, and the third is a valid
    /// [`VersionTreeId`].
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split("::").collect();
        let [object_id, creating_system_id, version_tree_id] = parts.as_slice() else {
            return Err(ParseError::new(
                "OBJECT_VERSION_ID",
                "expected object_id::creating_system_id::version_tree_id",
                s,
            ));
        };
        Ok(Self {
            object_id: object_id.parse()?,
            creating_system_id: creating_system_id.parse()?,
            version_tree_id: version_tree_id.parse()?,
        })
    }
}

crate::impl_valued_serde!(ObjectVersionId, "OBJECT_VERSION_ID");

/// A position in a version tree: `trunk [ '.' branch_number '.' branch_version ]`.
///
/// # Why leading zeros are refused
///
/// `01` and `1` denote the same trunk version, so accepting both would make two
/// distinct strings name one version. Every REST path, `preceding_version_uid`,
/// and `LOCATABLE_REF` in the system carries the identifier as text and
/// compares it as text. This type therefore stores the numbers and prints the
/// canonical form, and refuses input that would not survive that round trip.
///
/// ```
/// use openehr::base::VersionTreeId;
///
/// assert!("1".parse::<VersionTreeId>().is_ok());
/// assert!("2.1.4".parse::<VersionTreeId>().is_ok());
/// assert!("01".parse::<VersionTreeId>().is_err());  // would not round-trip
/// assert!("0".parse::<VersionTreeId>().is_err());   // trunk starts at 1
/// assert!("2.1".parse::<VersionTreeId>().is_err()); // branch parts come in pairs
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VersionTreeId {
    trunk_version: u32,
    branch: Option<(u32, u32)>,
}

impl VersionTreeId {
    /// The first version of a new versioned object: `1`.
    ///
    /// ```
    /// use openehr::base::VersionTreeId;
    /// assert_eq!(VersionTreeId::FIRST.to_string(), "1");
    /// ```
    pub const FIRST: Self = Self {
        trunk_version: 1,
        branch: None,
    };

    /// Builds a trunk version.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if `trunk_version` is zero.
    pub fn trunk(trunk_version: u32) -> Result<Self, ParseError> {
        if trunk_version == 0 {
            return Err(ParseError::new(
                "VERSION_TREE_ID",
                "trunk_version is 0",
                "0",
            ));
        }
        Ok(Self {
            trunk_version,
            branch: None,
        })
    }

    /// Builds a branch version.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if any of the three numbers is zero.
    pub fn branch(
        trunk_version: u32,
        branch_number: u32,
        branch_version: u32,
    ) -> Result<Self, ParseError> {
        if trunk_version == 0 || branch_number == 0 || branch_version == 0 {
            return Err(ParseError::new(
                "VERSION_TREE_ID",
                "version numbers start at 1",
                "",
            ));
        }
        Ok(Self {
            trunk_version,
            branch: Some((branch_number, branch_version)),
        })
    }

    /// The trunk version number.
    #[must_use]
    pub fn trunk_version(&self) -> u32 {
        self.trunk_version
    }

    /// The branch number, if this is a branch version.
    #[must_use]
    pub fn branch_number(&self) -> Option<u32> {
        self.branch.map(|(n, _)| n)
    }

    /// The version within the branch, if this is a branch version.
    #[must_use]
    pub fn branch_version(&self) -> Option<u32> {
        self.branch.map(|(_, v)| v)
    }

    /// Whether this is a branch version.
    #[must_use]
    pub fn is_branch(&self) -> bool {
        self.branch.is_some()
    }

    /// Whether this is the very first version, `1`.
    #[must_use]
    pub fn is_first(&self) -> bool {
        *self == Self::FIRST
    }

    /// The next version along the same line.
    ///
    /// Trunk `2` follows trunk `1`; branch `2.1.4` is followed by `2.1.5`. The
    /// trunk number of a branch never advances — that is what makes it a
    /// branch.
    ///
    /// ```
    /// use openehr::base::VersionTreeId;
    ///
    /// assert_eq!(VersionTreeId::FIRST.next().to_string(), "2");
    /// assert_eq!("2.1.4".parse::<VersionTreeId>().unwrap().next().to_string(), "2.1.5");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the relevant counter is `u32::MAX`. A versioned object with
    /// four billion versions is a runaway writer, and silently wrapping to
    /// version `0` would corrupt the history rather than surface the bug.
    #[must_use]
    pub fn next(&self) -> Self {
        match self.branch {
            None => Self {
                trunk_version: self
                    .trunk_version
                    .checked_add(1)
                    .expect("version tree trunk overflowed u32"),
                branch: None,
            },
            Some((n, v)) => Self {
                trunk_version: self.trunk_version,
                branch: Some((
                    n,
                    v.checked_add(1)
                        .expect("version tree branch overflowed u32"),
                )),
            },
        }
    }
}

impl fmt::Display for VersionTreeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.branch {
            None => write!(f, "{}", self.trunk_version),
            Some((n, v)) => write!(f, "{}.{n}.{v}", self.trunk_version),
        }
    }
}

impl FromStr for VersionTreeId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the text is not one or three dot-separated
    /// numbers, if any number is zero, or if any number carries a leading zero.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn num(part: &str, whole: &str) -> Result<u32, ParseError> {
            if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
                return Err(ParseError::new("VERSION_TREE_ID", "not a number", whole));
            }
            if part.len() > 1 && part.starts_with('0') {
                return Err(ParseError::new(
                    "VERSION_TREE_ID",
                    "leading zero would not round-trip",
                    whole,
                ));
            }
            part.parse().map_err(|_| {
                ParseError::new("VERSION_TREE_ID", "number does not fit in u32", whole)
            })
        }

        let parts: Vec<&str> = s.split('.').collect();
        match parts.as_slice() {
            [trunk] => Self::trunk(num(trunk, s)?),
            [trunk, branch_number, branch_version] => Self::branch(
                num(trunk, s)?,
                num(branch_number, s)?,
                num(branch_version, s)?,
            ),
            _ => Err(ParseError::new(
                "VERSION_TREE_ID",
                "expected `trunk` or `trunk.branch_number.branch_version`",
                s,
            )),
        }
    }
}

crate::impl_string_serde!(VersionTreeId, "VERSION_TREE_ID");

/// An archetype identifier such as
/// `openEHR-EHR-OBSERVATION.blood_pressure.v2`.
///
/// Lexical form:
/// `rm_originator '-' rm_name '-' rm_entity '.' concept_name {'-' specialisation}* '.' version`
///
/// # The version part accepts both `v2` and `v2.1.0`
///
/// The BASE specification's grammar gives `'v' number`, which is what ADL 1.4
/// archetypes carry. ADL 2 archetypes carry a full three-part semantic version,
/// and the CKM publishes both. Accepting only the narrower grammar would reject
/// identifiers that appear in real instance data, so this type accepts one to
/// three numeric components and preserves which it was given.
///
/// ```
/// use openehr::base::ArchetypeId;
///
/// let id: ArchetypeId = "openEHR-EHR-OBSERVATION.blood_pressure.v2".parse().unwrap();
/// assert_eq!(id.rm_originator(), "openEHR");
/// assert_eq!(id.rm_name(), "EHR");
/// assert_eq!(id.rm_entity(), "OBSERVATION");
/// assert_eq!(id.concept_name(), "blood_pressure");
/// assert!(id.specialisations().next().is_none());
///
/// let adl2: ArchetypeId = "openEHR-EHR-OBSERVATION.blood_pressure.v2.1.0".parse().unwrap();
/// assert_eq!(adl2.version_id(), "v2.1.0");
/// assert_eq!(adl2.major_version(), 2);
///
/// let spec: ArchetypeId =
///     "openEHR-EHR-OBSERVATION.progress_note-naturopathy.v2".parse().unwrap();
/// assert_eq!(spec.concept_name(), "progress_note");
/// assert_eq!(spec.specialisations().collect::<Vec<_>>(), ["naturopathy"]);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArchetypeId {
    rm_originator: String,
    rm_name: String,
    rm_entity: String,
    domain_concept: String,
    version_id: String,
}

impl ArchetypeId {
    /// The organisation that issued the reference model, usually `openEHR`.
    #[must_use]
    pub fn rm_originator(&self) -> &str {
        &self.rm_originator
    }

    /// The reference model name, such as `EHR` or `DEMOGRAPHIC`.
    #[must_use]
    pub fn rm_name(&self) -> &str {
        &self.rm_name
    }

    /// The RM class the archetype constrains, such as `OBSERVATION`.
    ///
    /// This is the attribute that makes an archetype id checkable against the
    /// object it annotates: an `ARCHETYPED` on a `COMPOSITION` whose archetype
    /// id says `OBSERVATION` is a defect, and
    /// [`crate::validation`] reports it.
    #[must_use]
    pub fn rm_entity(&self) -> &str {
        &self.rm_entity
    }

    /// The domain concept including any specialisations, such as
    /// `progress_note-naturopathy`.
    #[must_use]
    pub fn domain_concept(&self) -> &str {
        &self.domain_concept
    }

    /// The concept name without its specialisations.
    #[must_use]
    pub fn concept_name(&self) -> &str {
        self.domain_concept
            .split_once('-')
            .map_or(self.domain_concept.as_str(), |(head, _)| head)
    }

    /// The specialisation segments, outermost first.
    pub fn specialisations(&self) -> impl Iterator<Item = &str> {
        let mut parts = self.domain_concept.split('-');
        parts.next();
        parts
    }

    /// The version part including its leading `v`, such as `v2` or `v2.1.0`.
    #[must_use]
    pub fn version_id(&self) -> &str {
        &self.version_id
    }

    /// The major version number.
    ///
    /// This is the number that matters for compatibility: openEHR's archetype
    /// versioning rules make a major-version bump the only breaking change, so
    /// data archetyped `v1` is readable against `v1.9.3` and not against `v2`.
    ///
    /// # Panics
    ///
    /// Never: the parser guarantees the major component is numeric.
    #[must_use]
    pub fn major_version(&self) -> u32 {
        self.version_id[1..]
            .split('.')
            .next()
            .and_then(|n| n.parse().ok())
            .expect("parser guarantees a numeric major version")
    }

    /// Whether this archetype constrains the given RM class name.
    ///
    /// ```
    /// use openehr::base::ArchetypeId;
    ///
    /// let id: ArchetypeId = "openEHR-EHR-OBSERVATION.blood_pressure.v2".parse().unwrap();
    /// assert!(id.constrains("OBSERVATION"));
    /// assert!(!id.constrains("EVALUATION"));
    /// ```
    #[must_use]
    pub fn constrains(&self, rm_class: &str) -> bool {
        self.rm_entity == rm_class
    }
}

impl fmt::Display for ArchetypeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}-{}-{}.{}.{}",
            self.rm_originator, self.rm_name, self.rm_entity, self.domain_concept, self.version_id
        )
    }
}

impl FromStr for ArchetypeId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the text does not have the three dot-separated
    /// sections, if the first is not three hyphen-separated names, or if the
    /// version is not `v` followed by one to three numbers.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // The domain concept cannot contain a dot, so the section boundaries
        // are unambiguous even though both the qualified entity and the domain
        // concept may contain hyphens.
        let mut sections = s.splitn(3, '.');
        let (Some(qualified), Some(domain_concept), Some(version_id)) =
            (sections.next(), sections.next(), sections.next())
        else {
            return Err(ParseError::new(
                "ARCHETYPE_ID",
                "expected rm_entity.domain_concept.version",
                s,
            ));
        };

        let rm: Vec<&str> = qualified.split('-').collect();
        let [rm_originator, rm_name, rm_entity] = rm.as_slice() else {
            return Err(ParseError::new(
                "ARCHETYPE_ID",
                "expected rm_originator-rm_name-rm_entity",
                s,
            ));
        };
        for part in [rm_originator, rm_name, rm_entity] {
            if part.is_empty() || !part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
                return Err(ParseError::new(
                    "ARCHETYPE_ID",
                    "reference model name is empty or has an illegal character",
                    s,
                ));
            }
        }

        if domain_concept.is_empty()
            || !domain_concept
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
        {
            return Err(ParseError::new(
                "ARCHETYPE_ID",
                "domain concept is empty or has an illegal character",
                s,
            ));
        }
        if domain_concept.split('-').any(str::is_empty) {
            return Err(ParseError::new(
                "ARCHETYPE_ID",
                "empty specialisation segment",
                s,
            ));
        }

        let Some(numbers) = version_id.strip_prefix('v') else {
            return Err(ParseError::new("ARCHETYPE_ID", "version lacks `v`", s));
        };
        let components: Vec<&str> = numbers.split('.').collect();
        if components.is_empty() || components.len() > 3 {
            return Err(ParseError::new(
                "ARCHETYPE_ID",
                "version has more than three components",
                s,
            ));
        }
        for c in &components {
            if c.is_empty() || !c.bytes().all(|b| b.is_ascii_digit()) {
                return Err(ParseError::new(
                    "ARCHETYPE_ID",
                    "version component is not a number",
                    s,
                ));
            }
            if c.parse::<u32>().is_err() {
                return Err(ParseError::new(
                    "ARCHETYPE_ID",
                    "version component does not fit in u32",
                    s,
                ));
            }
        }

        Ok(Self {
            rm_originator: (*rm_originator).to_owned(),
            rm_name: (*rm_name).to_owned(),
            rm_entity: (*rm_entity).to_owned(),
            domain_concept: domain_concept.to_owned(),
            version_id: version_id.to_owned(),
        })
    }
}

crate::impl_valued_serde!(ArchetypeId, "ARCHETYPE_ID");

/// A template identifier.
///
/// openEHR states the lexical form as "to be determined", so this type stores
/// the text verbatim and requires only that it be non-empty and free of
/// whitespace. Inventing a stricter grammar would reject valid identifiers from
/// conformant tools; accepting anything at all, including an empty string,
/// would let a missing template id look like a present one.
///
/// ```
/// use openehr::base::TemplateId;
///
/// assert!("Blood pressure.v1".parse::<TemplateId>().is_err()); // whitespace
/// assert!("blood_pressure.v1".parse::<TemplateId>().is_ok());
/// assert!("".parse::<TemplateId>().is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TemplateId(String);

impl TemplateId {
    /// The identifier's text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl FromStr for TemplateId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the text is empty or contains whitespace.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(ParseError::new("TEMPLATE_ID", "empty", s));
        }
        if s.chars().any(char::is_whitespace) {
            return Err(ParseError::new("TEMPLATE_ID", "contains whitespace", s));
        }
        Ok(Self(s.to_owned()))
    }
}

crate::impl_valued_serde!(TemplateId, "TEMPLATE_ID");

/// A terminology identifier such as `SNOMED-CT`, `openehr`, or
/// `ICD10AM(3rd_ed)`.
///
/// Lexical form: `name [ '(' version ')' ]`.
///
/// ```
/// use openehr::base::TerminologyId;
///
/// let plain: TerminologyId = "SNOMED-CT".parse().unwrap();
/// assert_eq!(plain.name(), "SNOMED-CT");
/// assert!(plain.version_id().is_none());
///
/// let versioned: TerminologyId = "ICD10AM(3rd_ed)".parse().unwrap();
/// assert_eq!(versioned.name(), "ICD10AM");
/// assert_eq!(versioned.version_id(), Some("3rd_ed"));
/// assert_eq!(versioned.to_string(), "ICD10AM(3rd_ed)");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TerminologyId {
    name: String,
    version_id: Option<String>,
}

impl TerminologyId {
    /// The openEHR support terminology, which supplies null flavours, change
    /// types, lifecycle states, and the other coded vocabularies the reference
    /// model refers to by code.
    ///
    /// ```
    /// use openehr::base::TerminologyId;
    /// assert_eq!(TerminologyId::openehr().name(), "openehr");
    /// ```
    #[must_use]
    #[allow(non_snake_case)]
    pub fn openehr() -> Self {
        Self {
            name: "openehr".to_owned(),
            version_id: None,
        }
    }

    /// The terminology's name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The terminology's version, if the identifier carries one.
    #[must_use]
    pub fn version_id(&self) -> Option<&str> {
        self.version_id.as_deref()
    }

    /// Whether this identifies the openEHR support terminology.
    ///
    /// Compared case-insensitively: instances carry `openehr`, `openEHR`, and
    /// `OpenEHR`, and a code-lookup that missed on case would report a valid
    /// null flavour as an unknown code.
    #[must_use]
    pub fn is_openehr(&self) -> bool {
        self.name.eq_ignore_ascii_case("openehr")
    }
}

impl fmt::Display for TerminologyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.version_id {
            Some(v) => write!(f, "{}({v})", self.name),
            None => f.write_str(&self.name),
        }
    }
}

impl FromStr for TerminologyId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the name is empty, if a `(` is unclosed, or if
    /// the parenthesised version is empty.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (name, version_id) = match s.split_once('(') {
            None => (s, None),
            Some((name, rest)) => {
                let Some(version) = rest.strip_suffix(')') else {
                    return Err(ParseError::new("TERMINOLOGY_ID", "unclosed `(`", s));
                };
                if version.is_empty() {
                    return Err(ParseError::new("TERMINOLOGY_ID", "empty version", s));
                }
                (name, Some(version.to_owned()))
            }
        };
        if name.is_empty() {
            return Err(ParseError::new("TERMINOLOGY_ID", "empty name", s));
        }
        Ok(Self {
            name: name.to_owned(),
            version_id,
        })
    }
}

crate::impl_valued_serde!(TerminologyId, "TERMINOLOGY_ID");

/// An identifier in a scheme openEHR does not define.
///
/// The escape hatch, and the only `OBJECT_ID` whose grammar is not checkable:
/// the scheme names an authority, and this crate has no registry of authorities
/// to check the value against. It requires both parts to be non-empty, so that
/// a `GENERIC_ID` at least says *which* uncontrolled scheme it belongs to.
///
/// ```
/// use openehr::base::GenericId;
///
/// let id = GenericId::new("NHS-UK-1234567890", "uk.nhs.nhs_number").unwrap();
/// assert_eq!(id.scheme(), "uk.nhs.nhs_number");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct GenericId {
    #[serde(rename = "_type", default = "generic_id_type")]
    _type: GenericIdType,
    value: String,
    scheme: String,
}

fn generic_id_type() -> GenericIdType {
    GenericIdType::GenericId
}

/// The `_type` discriminator of [`GenericId`], as a type so that a payload
/// declaring some other class fails to deserialize rather than being quietly
/// reinterpreted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum GenericIdType {
    /// `GENERIC_ID`.
    #[serde(rename = "GENERIC_ID")]
    GenericId,
}

impl GenericId {
    /// Builds a generic identifier.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if either part is empty.
    pub fn new(value: impl Into<String>, scheme: impl Into<String>) -> Result<Self, ParseError> {
        let value = value.into();
        let scheme = scheme.into();
        if value.is_empty() {
            return Err(ParseError::new("GENERIC_ID", "empty value", &value));
        }
        if scheme.is_empty() {
            return Err(ParseError::new("GENERIC_ID", "empty scheme", &scheme));
        }
        Ok(Self {
            _type: GenericIdType::GenericId,
            value,
            scheme,
        })
    }

    /// The identifier text.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// The naming scheme.
    #[must_use]
    pub fn scheme(&self) -> &str {
        &self.scheme
    }
}

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

/// Any `OBJECT_ID`.
///
/// # Deserialization without a `_type`
///
/// `_type` is required by openEHR wherever the static type is abstract, and
/// `OBJECT_ID` always is. Real payloads omit it anyway. When it is missing this
/// type infers from the lexical shape — three `::` parts means
/// `OBJECT_VERSION_ID`, otherwise `HIER_OBJECT_ID` — and never guesses
/// `ARCHETYPE_ID`, `TEMPLATE_ID`, or `GENERIC_ID`, because those are not
/// distinguishable from a `HIER_OBJECT_ID` extension by shape alone and a wrong
/// guess is worse than a rejection.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ObjectId {
    /// A versioned-container identifier.
    HierObjectId(HierObjectId),
    /// A version identifier.
    ObjectVersionId(ObjectVersionId),
    /// An archetype identifier.
    ArchetypeId(ArchetypeId),
    /// A template identifier.
    TemplateId(TemplateId),
    /// A terminology identifier.
    TerminologyId(TerminologyId),
    /// An identifier in an externally defined scheme.
    GenericId(GenericId),
}

impl ObjectId {
    /// The identifier's lexical form.
    #[must_use]
    pub fn value(&self) -> String {
        self.to_string()
    }

    /// The openEHR class name, as it appears in `_type`.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::HierObjectId(_) => "HIER_OBJECT_ID",
            Self::ObjectVersionId(_) => "OBJECT_VERSION_ID",
            Self::ArchetypeId(_) => "ARCHETYPE_ID",
            Self::TemplateId(_) => "TEMPLATE_ID",
            Self::TerminologyId(_) => "TERMINOLOGY_ID",
            Self::GenericId(_) => "GENERIC_ID",
        }
    }
}

impl fmt::Display for ObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HierObjectId(v) => v.fmt(f),
            Self::ObjectVersionId(v) => v.fmt(f),
            Self::ArchetypeId(v) => v.fmt(f),
            Self::TemplateId(v) => v.fmt(f),
            Self::TerminologyId(v) => v.fmt(f),
            Self::GenericId(v) => v.fmt(f),
        }
    }
}

/// Either kind of identifier that can appear in `LOCATABLE.uid`.
///
/// `LOCATABLE.uid` is typed `UID_BASED_ID`, which admits exactly two of the six
/// `OBJECT_ID` classes. Modelling that as its own enum rather than reusing
/// [`ObjectId`] means an archetype id cannot be put in a `uid` field by mistake
/// — a class of error that would otherwise only surface at validation time.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UidBasedId {
    /// A versioned-container identifier.
    HierObjectId(HierObjectId),
    /// A version identifier.
    ObjectVersionId(ObjectVersionId),
}

impl UidBasedId {
    /// The identifying root, shared by both forms.
    ///
    /// For a [`HierObjectId`] this is its root; for an [`ObjectVersionId`] it
    /// is the `object_id`. Both answer the same question — *which* record —
    /// which is what makes the abstraction worth having.
    #[must_use]
    pub fn root(&self) -> &Uid {
        match self {
            Self::HierObjectId(id) => id.root(),
            Self::ObjectVersionId(id) => id.object_id(),
        }
    }

    /// The extension, which only a [`HierObjectId`] can carry.
    #[must_use]
    pub fn extension(&self) -> Option<&str> {
        match self {
            Self::HierObjectId(id) => id.extension(),
            Self::ObjectVersionId(_) => None,
        }
    }

    /// The openEHR class name, as it appears in `_type`.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::HierObjectId(_) => "HIER_OBJECT_ID",
            Self::ObjectVersionId(_) => "OBJECT_VERSION_ID",
        }
    }
}

impl fmt::Display for UidBasedId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HierObjectId(v) => v.fmt(f),
            Self::ObjectVersionId(v) => v.fmt(f),
        }
    }
}

impl FromStr for UidBasedId {
    type Err = ParseError;

    /// # Errors
    ///
    /// Returns [`ParseError`] if the text is neither a `HIER_OBJECT_ID` nor an
    /// `OBJECT_VERSION_ID`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.matches("::").count() == 2 {
            return Ok(Self::ObjectVersionId(s.parse()?));
        }
        Ok(Self::HierObjectId(s.parse()?))
    }
}

impl From<HierObjectId> for UidBasedId {
    fn from(v: HierObjectId) -> Self {
        Self::HierObjectId(v)
    }
}

impl From<ObjectVersionId> for UidBasedId {
    fn from(v: ObjectVersionId) -> Self {
        Self::ObjectVersionId(v)
    }
}

mod uid_based_id_serde {
    use super::{HierObjectId, ObjectVersionId, UidBasedId};
    use serde::de::{Error as _, MapAccess, Visitor};
    use serde::ser::SerializeStruct as _;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for UidBasedId {
        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
            let mut st = s.serialize_struct("UID_BASED_ID", 2)?;
            st.serialize_field("_type", self.type_name())?;
            st.serialize_field("value", &self.to_string())?;
            st.end()
        }
    }

    impl<'de> Deserialize<'de> for UidBasedId {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            struct V;

            impl<'de> Visitor<'de> for V {
                type Value = UidBasedId;

                fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                    f.write_str("a UID_BASED_ID as a string or a typed object")
                }

                fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<UidBasedId, E> {
                    v.parse().map_err(E::custom)
                }

                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<UidBasedId, A::Error> {
                    let mut ty: Option<String> = None;
                    let mut value: Option<String> = None;
                    while let Some(key) = map.next_key::<String>()? {
                        match key.as_str() {
                            "_type" => ty = Some(map.next_value()?),
                            "value" => value = Some(map.next_value()?),
                            _ => {
                                map.next_value::<serde::de::IgnoredAny>()?;
                            }
                        }
                    }
                    let value = value.ok_or_else(|| A::Error::missing_field("value"))?;
                    match ty.as_deref() {
                        Some("HIER_OBJECT_ID") => Ok(UidBasedId::HierObjectId(
                            value.parse::<HierObjectId>().map_err(A::Error::custom)?,
                        )),
                        Some("OBJECT_VERSION_ID") => Ok(UidBasedId::ObjectVersionId(
                            value.parse::<ObjectVersionId>().map_err(A::Error::custom)?,
                        )),
                        Some(other) => Err(A::Error::custom(format!(
                            "_type is {other}, expected HIER_OBJECT_ID or OBJECT_VERSION_ID"
                        ))),
                        None => value.parse().map_err(A::Error::custom),
                    }
                }
            }

            d.deserialize_any(V)
        }
    }
}

mod object_id_serde {
    use super::{
        ArchetypeId, GenericId, HierObjectId, ObjectId, ObjectVersionId, TemplateId, TerminologyId,
        UidBasedId,
    };
    use serde::de::{Error as _, MapAccess, Visitor};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for ObjectId {
        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
            match self {
                ObjectId::HierObjectId(v) => v.serialize(s),
                ObjectId::ObjectVersionId(v) => v.serialize(s),
                ObjectId::ArchetypeId(v) => v.serialize(s),
                ObjectId::TemplateId(v) => v.serialize(s),
                ObjectId::TerminologyId(v) => v.serialize(s),
                ObjectId::GenericId(v) => v.serialize(s),
            }
        }
    }

    impl<'de> Deserialize<'de> for ObjectId {
        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
            struct V;

            impl<'de> Visitor<'de> for V {
                type Value = ObjectId;

                fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                    f.write_str("an OBJECT_ID as a string or a typed object")
                }

                fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<ObjectId, E> {
                    infer(v).map_err(E::custom)
                }

                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<ObjectId, A::Error> {
                    let mut ty: Option<String> = None;
                    let mut value: Option<String> = None;
                    let mut scheme: Option<String> = None;
                    while let Some(key) = map.next_key::<String>()? {
                        match key.as_str() {
                            "_type" => ty = Some(map.next_value()?),
                            "value" => value = Some(map.next_value()?),
                            "scheme" => scheme = Some(map.next_value()?),
                            _ => {
                                map.next_value::<serde::de::IgnoredAny>()?;
                            }
                        }
                    }
                    let value = value.ok_or_else(|| A::Error::missing_field("value"))?;
                    match ty.as_deref() {
                        Some("HIER_OBJECT_ID") => Ok(ObjectId::HierObjectId(
                            value.parse::<HierObjectId>().map_err(A::Error::custom)?,
                        )),
                        Some("OBJECT_VERSION_ID") => Ok(ObjectId::ObjectVersionId(
                            value.parse::<ObjectVersionId>().map_err(A::Error::custom)?,
                        )),
                        Some("ARCHETYPE_ID") => Ok(ObjectId::ArchetypeId(
                            value.parse::<ArchetypeId>().map_err(A::Error::custom)?,
                        )),
                        Some("TEMPLATE_ID") => Ok(ObjectId::TemplateId(
                            value.parse::<TemplateId>().map_err(A::Error::custom)?,
                        )),
                        Some("TERMINOLOGY_ID") => Ok(ObjectId::TerminologyId(
                            value.parse::<TerminologyId>().map_err(A::Error::custom)?,
                        )),
                        Some("GENERIC_ID") => {
                            let scheme = scheme.ok_or_else(|| A::Error::missing_field("scheme"))?;
                            Ok(ObjectId::GenericId(
                                GenericId::new(value, scheme).map_err(A::Error::custom)?,
                            ))
                        }
                        Some(other) => Err(A::Error::custom(format!(
                            "{other} is not an OBJECT_ID class"
                        ))),
                        None => infer(&value).map_err(A::Error::custom),
                    }
                }
            }

            fn infer(value: &str) -> Result<ObjectId, crate::ParseError> {
                Ok(match value.parse::<UidBasedId>()? {
                    UidBasedId::HierObjectId(v) => ObjectId::HierObjectId(v),
                    UidBasedId::ObjectVersionId(v) => ObjectId::ObjectVersionId(v),
                })
            }

            d.deserialize_any(V)
        }
    }
}

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

    #[test]
    fn version_id_round_trips_exactly() {
        for text in [
            "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.nhs.uk::1",
            "87284370-2d4b-4e3d-a3f3-f303d2f4f34b::2.16.840.1::12.3.7",
        ] {
            assert_eq!(text.parse::<ObjectVersionId>().unwrap().to_string(), text);
        }
    }

    #[test]
    fn hier_object_id_rejects_a_double_colon_extension() {
        // Otherwise `a::b::c` would parse as root `a`, extension `b::c`, and
        // print back as something that re-parses into three parts.
        assert!("2.16.840::b::c".parse::<HierObjectId>().is_err());
    }

    #[test]
    fn uid_based_id_infers_by_separator_count() {
        assert!(matches!(
            "1.2.3::x".parse::<UidBasedId>().unwrap(),
            UidBasedId::HierObjectId(_)
        ));
        assert!(matches!(
            "1.2.3::sys.example::4".parse::<UidBasedId>().unwrap(),
            UidBasedId::ObjectVersionId(_)
        ));
    }

    #[test]
    fn archetype_id_round_trips_and_splits() {
        let text = "openEHR-EHR-OBSERVATION.blood_pressure-mine-yours.v1.2.3";
        let id: ArchetypeId = text.parse().unwrap();
        assert_eq!(id.to_string(), text);
        assert_eq!(id.concept_name(), "blood_pressure");
        assert_eq!(id.specialisations().collect::<Vec<_>>(), ["mine", "yours"]);
        assert_eq!(id.major_version(), 1);
    }

    #[test]
    fn archetype_id_rejects_malformed_forms() {
        for text in [
            "openEHR-EHR.blood_pressure.v1",            // two-part rm entity
            "openEHR-EHR-OBSERVATION.blood_pressure",   // no version
            "openEHR-EHR-OBSERVATION.blood_pressure.1", // version without v
            "openEHR-EHR-OBSERVATION.blood_pressure.v", // v without number
            "openEHR-EHR-OBSERVATION..v1",              // empty concept
            "openEHR-EHR-OBSERVATION.a-.v1",            // empty specialisation
            "openEHR-EHR-OBSERVATION.a.v1.2.3.4",       // four version parts
        ] {
            assert!(text.parse::<ArchetypeId>().is_err(), "accepted {text}");
        }
    }

    #[test]
    fn version_tree_next_advances_the_right_counter() {
        let trunk: VersionTreeId = "3".parse().unwrap();
        assert_eq!(trunk.next().to_string(), "4");
        let branch: VersionTreeId = "3.2.9".parse().unwrap();
        assert_eq!(branch.next().to_string(), "3.2.10");
    }

    /// A `VERSION_TREE_ID`'s three numbers, each refused at zero on its own
    /// account, and each readable back.
    ///
    /// `trunk_version == 0 || branch_number == 0 || branch_version == 0` could
    /// become `&&`, admitting `1.0.3` and `1.2.0`; and both branch accessors
    /// could return a constant (`lib:A-09`). This identifier is the position of
    /// a version in its tree, which the store enforces uniqueness on
    /// (`ix_version_container_trunk`, `db:H5.10`), so an accessor that answers
    /// a fixed number puts two different versions at one position.
    #[test]
    fn every_number_in_a_version_tree_id_is_read_and_none_may_be_zero() {
        let v = VersionTreeId::branch(1, 2, 3).expect("1.2.3 is a branch");
        assert_eq!(v.trunk_version(), 1);
        assert_eq!(v.branch_number(), Some(2));
        assert_eq!(v.branch_version(), Some(3));
        assert!(v.is_branch());
        assert_eq!(v.to_string(), "1.2.3");

        // Different numbers in each position, so no accessor can answer from
        // the wrong field and still look right.
        let v = VersionTreeId::branch(7, 8, 9).unwrap();
        assert_eq!(
            (v.trunk_version(), v.branch_number(), v.branch_version()),
            (7, Some(8), Some(9))
        );

        // Each zero refused separately: `&&` would accept two of these three.
        for (t, n, ver) in [(0, 2, 3), (1, 0, 3), (1, 2, 0), (0, 0, 0)] {
            assert!(
                VersionTreeId::branch(t, n, ver).is_err(),
                "{t}.{n}.{ver} was accepted"
            );
        }

        // A trunk version has no branch, and says so rather than answering 1.
        let trunk: VersionTreeId = "5".parse().unwrap();
        assert_eq!(trunk.trunk_version(), 5);
        assert_eq!(trunk.branch_number(), None);
        assert_eq!(trunk.branch_version(), None);
        assert!(!trunk.is_branch());
    }

    /// What a `VERSION_TREE_ID` refuses when parsed from text.
    ///
    /// `part.is_empty() || !all_digits` could become `&&`, accepting `1.x.3`;
    /// and `part.len() > 1` could become `>=`, which rejects a legitimate `0`
    /// prefix check on every single digit. A leading zero is refused because it
    /// would not round-trip, and this identifier is stored as text.
    #[test]
    fn a_version_tree_id_refuses_what_would_not_round_trip() {
        for text in ["1", "1.2.3", "10", "1.20.300"] {
            let v: VersionTreeId = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
            assert_eq!(v.to_string(), text, "{text} did not round-trip");
        }
        for bad in [
            "1.x.3",  // not a number
            "1..3",   // empty component
            "",       //
            "01",     // leading zero
            "1.02.3", //
            "1.2.03",
            "0",     // zero
            "1.2",   // two components
            "1.2.3.4",
            "-1",
        ] {
            assert!(
                bad.parse::<VersionTreeId>().is_err(),
                "{bad} was accepted as a version tree id"
            );
        }
    }

    /// Every part of an `ARCHETYPE_ID`, and every way one is malformed.
    ///
    /// Three `||`s in the parser could become `&&` — admitting an empty
    /// reference-model part, an empty domain concept, or a non-numeric version
    /// component — and `domain_concept` could return a constant. The archetype
    /// id is what an AQL query filters on (`db:P6.12`) and what an
    /// authorisation check reads (`Q12.13`), so an accessor answering the wrong
    /// string is a permission decision about the wrong archetype.
    #[test]
    fn an_archetype_id_is_read_in_full_and_refuses_each_malformation() {
        let id: ArchetypeId = "openEHR-EHR-OBSERVATION.blood_pressure.v2".parse().unwrap();
        assert_eq!(id.rm_originator(), "openEHR");
        assert_eq!(id.rm_name(), "EHR");
        assert_eq!(id.rm_entity(), "OBSERVATION");
        assert_eq!(id.domain_concept(), "blood_pressure");
        assert_eq!(id.concept_name(), "blood_pressure");
        assert_eq!(id.to_string(), "openEHR-EHR-OBSERVATION.blood_pressure.v2");

        // A specialised concept: `domain_concept` keeps the specialisation and
        // `concept_name` drops it. Returning a constant makes these agree when
        // they must not.
        let id: ArchetypeId = "openEHR-EHR-COMPOSITION.progress_note-naturopathy.v1"
            .parse()
            .unwrap();
        assert_eq!(id.domain_concept(), "progress_note-naturopathy");
        assert_eq!(id.concept_name(), "progress_note");

        for bad in [
            "-EHR-OBSERVATION.x.v1",         // empty rm_originator
            "openEHR--OBSERVATION.x.v1",     // empty rm_name
            "openEHR-EHR-.x.v1",             // empty rm_entity
            "openEHR-EHR-OBS!.x.v1",         // illegal character
            "openEHR-EHR-OBSERVATION..v1",   // empty domain concept
            "openEHR-EHR-OBSERVATION.x!.v1", // illegal character in it
            "openEHR-EHR-OBSERVATION.x-.v1", // empty specialisation segment
            "openEHR-EHR-OBSERVATION.-x.v1",
            "openEHR-EHR-OBSERVATION.x.1",   // version lacks `v`
            "openEHR-EHR-OBSERVATION.x.vx",  // version is not a number
            "openEHR-EHR-OBSERVATION.x.v",   // empty version
            "openEHR-EHR-OBSERVATION.x.v1.2.3.4",
        ] {
            assert!(
                bad.parse::<ArchetypeId>().is_err(),
                "{bad} was accepted as an archetype id"
            );
        }
    }

    /// An `OBJECT_ID` names its own class and prints its own value.
    ///
    /// `type_name` could return one wrong constant for every variant and
    /// `Display` could print nothing, with no test failing. `type_name` is what
    /// goes into `_type` in canonical JSON, so a wrong answer is a record that
    /// deserializes as the wrong class — and canonical JSON is what every
    /// digest in the system is taken over (`db:M3.16`).
    #[test]
    fn every_object_id_class_names_itself_and_round_trips_through_json() {
        let cases: Vec<(ObjectId, &str, &str)> = vec![
            (
                ObjectId::HierObjectId("6BA7B810-9DAD-11D1-80B4-00C04FD430C8".parse().unwrap()),
                "HIER_OBJECT_ID",
                "6BA7B810-9DAD-11D1-80B4-00C04FD430C8",
            ),
            (
                ObjectId::ObjectVersionId(
                    "6BA7B810-9DAD-11D1-80B4-00C04FD430C8::example.org::1"
                        .parse()
                        .unwrap(),
                ),
                "OBJECT_VERSION_ID",
                "6BA7B810-9DAD-11D1-80B4-00C04FD430C8::example.org::1",
            ),
            (
                ObjectId::ArchetypeId("openEHR-EHR-OBSERVATION.blood_pressure.v2".parse().unwrap()),
                "ARCHETYPE_ID",
                "openEHR-EHR-OBSERVATION.blood_pressure.v2",
            ),
            (
                ObjectId::TemplateId("vital_signs.v1".parse().unwrap()),
                "TEMPLATE_ID",
                "vital_signs.v1",
            ),
            (
                ObjectId::TerminologyId("SNOMED-CT".parse().unwrap()),
                "TERMINOLOGY_ID",
                "SNOMED-CT",
            ),
            (
                ObjectId::GenericId(GenericId::new("12345", "NHS").unwrap()),
                "GENERIC_ID",
                "12345",
            ),
        ];

        let mut seen: Vec<&str> = Vec::new();
        for (id, type_name, text) in &cases {
            assert_eq!(id.type_name(), *type_name);
            assert_eq!(id.to_string(), *text, "{type_name} printed the wrong value");
            assert_eq!(id.value(), *text);
            seen.push(type_name);

            // Through canonical JSON and back, which is the `_type` field's
            // only purpose: a `GENERIC_ID` also needs its `scheme`, and the
            // arm reading that key could be deleted unnoticed.
            let json = serde_json::to_string(id).expect("serialize");
            assert!(json.contains(type_name), "{type_name} missing from {json}");
            let back: ObjectId = serde_json::from_str(&json).expect(&json);
            assert_eq!(&back, id, "{type_name} did not round-trip: {json}");
        }
        seen.sort_unstable();
        seen.dedup();
        assert_eq!(seen.len(), cases.len(), "two classes share a `_type`");

        // A `GENERIC_ID` without its scheme is refused rather than defaulted.
        assert!(
            serde_json::from_str::<ObjectId>(r#"{"_type":"GENERIC_ID","value":"12345"}"#).is_err(),
            "a GENERIC_ID with no scheme was accepted"
        );
        // And an unknown `_type` is refused rather than inferred.
        assert!(
            serde_json::from_str::<ObjectId>(r#"{"_type":"XYZZY","value":"12345"}"#).is_err()
        );
    }

    /// Only a `HIER_OBJECT_ID` carries an extension.
    ///
    /// `UidBasedId::extension` could answer `Some("xyzzy")` for both variants.
    #[test]
    fn only_a_hier_object_id_carries_an_extension() {
        let plain: UidBasedId = "6BA7B810-9DAD-11D1-80B4-00C04FD430C8".parse().unwrap();
        assert_eq!(plain.extension(), None);

        let with_ext: UidBasedId = "6BA7B810-9DAD-11D1-80B4-00C04FD430C8::extension"
            .parse()
            .unwrap();
        assert_eq!(with_ext.extension(), Some("extension"));

        let version: UidBasedId = "6BA7B810-9DAD-11D1-80B4-00C04FD430C8::example.org::1"
            .parse()
            .unwrap();
        assert_eq!(version.extension(), None, "an OBJECT_VERSION_ID has none");
    }

    /// Two version ids name the same versioned object when their object ids
    /// agree, whatever else differs.
    ///
    /// `same_object_as` could return `true` unconditionally (`lib:A-09`). It is
    /// the question "are these two versions of one record", and answering yes
    /// for two unrelated records merges two patients' histories.
    #[test]
    fn two_version_ids_name_the_same_object_only_when_their_object_ids_agree() {
        let id = |s: &str| s.parse::<ObjectVersionId>().unwrap();
        let a = id("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::a.example::1");

        // Same object, different creating system and different version: still
        // the same record. This is the case the doc comment shows.
        assert!(a.same_object_as(&id("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::b.example::2")));
        assert!(a.same_object_as(&a));

        // A different object id, with the system and version identical, so
        // only the part that matters differs.
        assert!(
            !a.same_object_as(&id("6BA7B810-9DAD-11D1-80B4-00C04FD430C8::a.example::1")),
            "two unrelated records were called versions of one"
        );
    }

    /// Each malformation of a `VERSION_TREE_ID` is refused *for its own
    /// reason*.
    ///
    /// Two guards here survived mutation while the values stayed rejected: a
    /// non-numeric part is caught again by `parse`, and a bare `0` is caught
    /// again by the zero check. So refusal alone cannot tell the guards apart —
    /// only the reason can, and the reason is what a caller is shown when their
    /// identifier is refused.
    #[test]
    fn each_malformed_version_tree_id_is_refused_for_its_own_reason() {
        let reason = |text: &str| {
            text.parse::<VersionTreeId>()
                .expect_err(text)
                .reason
        };
        assert_eq!(reason("1.x.3"), "not a number");
        assert_eq!(reason("1..3"), "not a number", "an empty part is not a number");
        assert_eq!(reason("01"), "leading zero would not round-trip");
        assert_eq!(reason("1.02.3"), "leading zero would not round-trip");
        // A single `0` is not a leading-zero problem — it is one digit — and
        // must be refused as a version number instead.
        assert_eq!(reason("0"), "trunk_version is 0");
        assert_eq!(reason("1.2"), "expected `trunk` or `trunk.branch_number.branch_version`");
        // Larger than a u32.
        assert_eq!(reason("4294967296"), "number does not fit in u32");
    }
}