openehr-sdt 0.0.128

openEHR Simplified Data Template formats (FLAT / STRUCTURED / Web Template), and template-independent RM-instance validation, hand-written over the openehr-its wire layer
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
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! Example-COMPOSITION generation from a [`WebTemplate`] (the `adl1.4/{id}/example`
//! endpoint), and the example party of a demographic template
//! ([`example_party`]; [`example_instance`] picks by the root class).
//!
//! [`example_composition`] walks the web-template tree and produces a canonical
//! openEHR JSON COMPOSITION populated with **deterministic** placeholder data
//! (no randomness, no current-time), at one of three [`DetailLevel`]s:
//!
//! * [`Required`](DetailLevel::Required) — only the mandatory skeleton (nodes on
//!   a fully-mandatory chain, plus whatever a min-cardinality or a mandatory
//!   attribute existence forces). Intended to be committable as-is.
//! * [`Medium`](DetailLevel::Medium) — the fully-populated single-instance
//!   document: every optional branch descended to its leaves, one occurrence of
//!   each node, the first alternative of any choice. Intended to be committable
//!   as-is.
//! * [`Complete`](DetailLevel::Complete) — everything `medium` emits, plus a
//!   second occurrence of each repeating node (demonstrating repetition); not
//!   necessarily committable.
//!
//! The set of populated leaves is monotonic across the levels
//! (`required ⊆ medium ⊆ complete`).
//!
//! The generator emits a FLAT map of deterministic example values and hands it
//! to [`composition_from_flat`], which already materialises the compacted RM
//! structure and fills every RM-mandatory field FLAT never surfaces. The result
//! therefore round-trips through
//! [`composition_to_flat`](crate::flat::convert::composition_to_flat) and
//! deserialises as an `openehr-rm` `Composition`.
//!
//! NOTE: ITS-REST Release-1.1.0 states the example-generation algorithm is
//! non-normative ("vendors may produce different results"), so the value choices
//! here are ours; only the `required` level's mandatory-skeleton-is-committable
//! contract is load-bearing. Reachable `PARTY_*` value leaves are skipped rather
//! than fabricated — an unset `ENTRY.subject` defaults to PARTY_SELF (master05
//! §OBSERVATION `/subject` row Note), and an invented party would put a
//! fictitious identified person into an example document.

#![expect(
    clippy::disallowed_types,
    reason = "canonical JSON / Simplified Formats operate on the wire value by definition \
              (ITS-JSON; ITS-REST Simplified Formats) — serde_json::Value IS the subject matter \
              (#1694)"
)]

use std::collections::{BTreeMap, BTreeSet, HashSet};

use openehr_rm::v1_2::paths::{PathSegment, RmPath};
use serde_json::{Map, Value, json};

use crate::flat::build::{BuildOptions, structural_from};
use crate::flat::convert::composition_from_flat;
use crate::flat::error::FlatError;
use crate::flat::identity::{recorded_archetype_id, stamp_archetype_details};
use crate::flat::uid::deterministic_uuid;
use crate::flat::webtemplate::model::{
    WebTemplate, WebTemplateInput, WebTemplateInputType, WebTemplateNode, WebTemplateRange,
    WebTemplateStructuralStub,
};

/// Fixed example instants used for the RM temporal leaves (deterministic).
///
/// [`EXAMPLE_DATE_TIME`] doubles as the `now` supplied to
/// [`composition_from_flat`] for the
/// `ctx/time` default, so a generated example is reproducible across calls. No
/// openEHR spec governs an example's timestamps — our own design (examples must
/// be deterministic).
const EXAMPLE_DATE_TIME: &str = "2022-02-03T04:05:06Z";
const EXAMPLE_DURATION: &str = "PT1H";

/// The level of detail for a generated example (`detail_level` query parameter).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetailLevel {
    /// Mandatory skeleton only; intended to be committable without adjustment.
    Required,
    /// Fully populated, one occurrence of every node (first alternative of any
    /// choice); intended to be committable without adjustment.
    Medium,
    /// `Medium` plus a second occurrence of each repeating node; not expected
    /// to be committable.
    Complete,
}

impl DetailLevel {
    /// Parse the `detail_level` query value, absent meaning
    /// [`Required`](Self::Required).
    ///
    /// The enum is closed and matched exactly — a present value that is not
    /// one of its tokens (the empty string and padded spellings included) is
    /// refused, since the declared default applies only to an absent
    /// parameter (ITS-REST `parameters/query/example_detail_level.yaml`).
    ///
    /// # Errors
    /// A message (→ ITS-REST `400`) for a value outside `required|medium|complete`.
    pub fn from_query(value: Option<&str>) -> Result<Self, String> {
        match value {
            None | Some("required") => Ok(Self::Required),
            Some("medium") => Ok(Self::Medium),
            Some("complete") => Ok(Self::Complete),
            Some(other) => Err(format!(
                "unsupported detail_level '{other}' (expected one of required, medium, complete)"
            )),
        }
    }
}

/// The intended use of a generated example (`type` query parameter).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExampleType {
    /// As submitted to the repository (committable; no `uid`).
    Input,
    /// As retrieved from the repository (carries a populated `uid`).
    Output,
}

impl ExampleType {
    /// Parse the `type` query value, absent meaning [`Input`](Self::Input).
    ///
    /// The enum is closed and matched exactly — a present value that is not
    /// one of its tokens (the empty string and padded spellings included) is
    /// refused, since the declared default applies only to an absent
    /// parameter (ITS-REST `parameters/query/example_type.yaml`).
    ///
    /// # Errors
    /// A message (→ ITS-REST `400`) for a value outside `input|output`.
    pub fn from_query(value: Option<&str>) -> Result<Self, String> {
        match value {
            None | Some("input") => Ok(Self::Input),
            Some("output") => Ok(Self::Output),
            Some(other) => Err(format!(
                "unsupported type '{other}' (expected one of input, output)"
            )),
        }
    }
}

/// Generates an example (input-form) COMPOSITION from `wt` at `level`.
///
/// The result is canonical openEHR JSON that deserialises as an `openehr-rm`
/// `Composition`. Every attribute the template makes mandatory is present: a
/// leaf-bearing one through the forced walk, a content-less structural one (an
/// EVENT `state`, an ENTRY `protocol`) as the empty node its structural stub
/// constrains (AOM 1.4 `master04-constraint_model_package.adoc` §existence).
/// For the `output` form, additionally call [`apply_output_uid`].
///
/// Only a COMPOSITION-rooted template has a COMPOSITION example: the ITS-REST
/// example operation answers one of the versioned-object classes
/// (`responses/200_Template_example_retrieved.yaml` lists COMPOSITION,
/// EHR_STATUS, FOLDER and the five parties), and a template rooted at an
/// ENTRY or a SECTION admits none of them.
///
/// # Errors
///
/// [`FlatError::NoExampleForRoot`] for a template whose root is not a
/// COMPOSITION, and the build's own [`FlatError`] should the generated document
/// not build.
pub fn example_composition(wt: &WebTemplate, level: DetailLevel) -> Result<Value, FlatError> {
    if wt.tree.rm_type != "COMPOSITION" {
        return Err(FlatError::NoExampleForRoot {
            root: wt.tree.rm_type.clone(),
        });
    }
    let mut flat: Map<String, Value> = Map::new();

    // Composition-level housekeeping the tree does not carry as data leaves.
    // `from_flat`/`apply_ctx` turn these into the RM-mandatory language /
    // territory / composer / context (the tree's `default_language` drives the
    // language; territory has no template constraint, so a fixed valid default).
    flat.insert("ctx/language".to_owned(), json!(wt.default_language));
    flat.insert("ctx/territory".to_owned(), json!("US"));
    flat.insert("ctx/composer_name".to_owned(), json!("Example composer"));
    flat.insert("ctx/time".to_owned(), json!(EXAMPLE_DATE_TIME));

    // Walk the tree from the root (COMPOSITION); the root is never forced empty —
    // an empty-content composition is valid RM, and a real content cardinality is
    // honoured by the per-container cardinality pass in `walk`.
    walk(&wt.tree, &wt.tree.id, 0, level, false, &mut flat);

    let mut value = composition_from_flat(&flat, wt, EXAMPLE_DATE_TIME)?;
    fill_mandatory_structures(&mut value, &wt.tree);
    let rm_version = BuildOptions::for_template(wt).rm_version;
    fill_content_less_sections(&mut value, &wt.tree, rm_version);
    Ok(value)
}

/// Generates an example instance of a non-COMPOSITION template's root class.
///
/// The root is an ENTRY, a SECTION or a CLUSTER, for example; the instance is
/// built from `wt` at `level` by [`crate::flat::build::build_root`] without any
/// COMPOSITION member.
///
/// The ITS-REST example operation serves [`example_composition`]; this is the
/// library form for validating or exercising a non-COMPOSITION template.
///
/// # Errors
///
/// [`FlatError::Conversion`] for a COMPOSITION-rooted template (use
/// [`example_composition`]), and the build's own [`FlatError`].
pub fn example_root_instance(wt: &WebTemplate, level: DetailLevel) -> Result<Value, FlatError> {
    if wt.tree.rm_type == "COMPOSITION" {
        return Err(FlatError::Conversion(
            "a COMPOSITION-rooted template's example is example_composition".to_owned(),
        ));
    }
    let mut flat: Map<String, Value> = Map::new();
    walk(&wt.tree, &wt.tree.id, 0, level, false, &mut flat);
    let doc = crate::flat::sim::flat::parse_flat(&flat)?;
    let mut value = crate::flat::build::build_root(&doc, wt, &BuildOptions::for_template(wt))?;
    fill_mandatory_structures(&mut value, &wt.tree);
    Ok(value)
}

/// Generates an example party from a demographic template at `level`.
///
/// The template root is a party class (`PERSON`, `ORGANISATION`, `GROUP`,
/// `AGENT` or `ROLE`, RM demographic `master02-demographic_package.adoc`); the
/// result is canonical openEHR JSON that decodes as that class, built through
/// the same template walk as [`example_composition`] and the root builder
/// [`crate::flat::build::build_root`]. A `ROLE` gets a placeholder `performer`
/// reference, because the RM makes that attribute mandatory
/// (`UML/classes/org.openehr.rm.demographic.role.adoc`, `performer` 1..1) and a
/// template does not constrain it.
///
/// # Errors
///
/// [`FlatError::NotAPartyTemplate`] for a template whose root is not a party
/// class, the build's own [`FlatError`], and [`FlatError::PartyDecode`] should
/// the generated party not decode as its class.
pub fn example_party(wt: &WebTemplate, level: DetailLevel) -> Result<Value, FlatError> {
    let class = party_class(&wt.tree.rm_type).ok_or_else(|| FlatError::NotAPartyTemplate {
        root: wt.tree.rm_type.clone(),
    })?;
    let mut flat: Map<String, Value> = Map::new();
    walk(&wt.tree, &wt.tree.id, 0, level, false, &mut flat);
    if class == "ROLE" {
        let root = &wt.tree.id;
        flat.insert(
            format!("{root}/performer|id"),
            json!(deterministic_uuid(&format!("{root}/performer"))),
        );
        flat.insert(format!("{root}/performer|namespace"), json!("demographic"));
        flat.insert(format!("{root}/performer|type"), json!("PERSON"));
    }
    let doc = crate::flat::sim::flat::parse_flat(&flat)?;
    let mut value = crate::flat::build::build_root(&doc, wt, &BuildOptions::for_template(wt))?;
    fill_mandatory_structures(&mut value, &wt.tree);
    crate::flat::build::check_party_decodes(&value, class)?;
    Ok(value)
}

/// Generates the example instance the template's root class admits.
///
/// A COMPOSITION-rooted template gets [`example_composition`] and a party
/// template [`example_party`]: both are versioned-object classes the ITS-REST
/// example operation answers (`responses/200_Template_example_retrieved.yaml`).
///
/// # Errors
///
/// [`FlatError::NoExampleForRoot`] for a template rooted at any other class
/// (an ENTRY or a SECTION, for example), and the generators' own errors.
pub fn example_instance(wt: &WebTemplate, level: DetailLevel) -> Result<Value, FlatError> {
    if party_class(&wt.tree.rm_type).is_some() {
        example_party(wt, level)
    } else {
        example_composition(wt, level)
    }
}

/// The party class `rm_type` names, if it names one.
fn party_class(rm_type: &str) -> Option<&'static str> {
    crate::flat::build::PARTY_CLASSES
        .into_iter()
        .find(|class| *class == rm_type)
}

/// Populate a deterministic `uid` (an `OBJECT_VERSION_ID`) on an example
/// composition — the `type=output` form (as retrieved from the repository).
///
/// The version-object UUID is derived deterministically from `template_id` (no
/// randomness), so repeated calls yield an identical example.
pub fn apply_output_uid(composition: &mut Value, template_id: &str) {
    if let Value::Object(map) = composition {
        map.insert(
            "uid".to_owned(),
            json!({
                "_type": "OBJECT_VERSION_ID",
                "value": format!("{}::example.server::1", deterministic_uuid(template_id)),
            }),
        );
    }
}

// ── the tree walk ──────────────────────────────────────────────────────────────

/// Walks a container node, emitting the flat entries for its included leaves,
/// and returns whether anything was emitted under this node.
///
/// `opt_depth` is the number of optional (`min < 1`) nodes on the path to this
/// node inclusive; it drives which optional branches each level includes.
/// `force` requests that a (mandatory) container not be left empty. A child
/// under a mandatory container cardinality or a mandatory attribute existence
/// is walked even where the level would skip it. An ELEMENT's `null_flavour`
/// is emitted only when its `value` is not: RM `data_structures` §ELEMENT
/// `Inv_null_flavour_indicated` (`is_null() xor null_flavour = Void`) makes the
/// two mutually exclusive, and requires the null flavour on a value-less
/// ELEMENT.
fn walk(
    node: &WebTemplateNode,
    prefix: &str,
    opt_depth: usize,
    level: DetailLevel,
    force: bool,
    out: &mut Map<String, Value>,
) -> bool {
    if node.has_input() {
        return emit_leaf(node, prefix, out);
    }

    let (groups, null_branch) = split_null_branch(node);
    let cx = WalkCtx {
        prefix,
        opt_depth,
        level,
    };
    let (mut emitted, mut included) = walk_children(node, &groups, &cx, out);
    emitted |= satisfy_cardinalities(node, &groups, &mut included, &cx, out);
    emitted |= satisfy_existence(node, &groups, &mut included, &cx, out);

    // A forced (mandatory) container with nothing yet: drill its first child to a
    // leaf so the node is not emitted empty.
    if force
        && !emitted
        && let Some(child) = groups.first()
    {
        let child_prefix = format!("{prefix}/{}", seg_for(child));
        emitted |= walk(child, &child_prefix, opt_depth, level, true, out);
    }

    if !null_branch.is_empty() && (emitted || force) && !value_emitted(&groups, prefix, out) {
        emitted |= walk_null_flavour(&null_branch, &cx, out);
    }
    emitted
}

/// The invariant context of one walk level: the flat-path prefix, the optional
/// depth reached, and the requested detail level.
struct WalkCtx<'a> {
    prefix: &'a str,
    opt_depth: usize,
    level: DetailLevel,
}

/// Walks every child group of a container, returning whether anything was
/// emitted and which child paths were included.
fn walk_children<'a>(
    node: &'a WebTemplateNode,
    groups: &[&'a WebTemplateNode],
    cx: &WalkCtx<'_>,
    out: &mut Map<String, Value>,
) -> (bool, Vec<&'a str>) {
    let mut emitted = false;
    let mut included: Vec<&str> = Vec::new();
    // Materialised instances per container cardinality (`max != -1`), so the
    // populated levels never overrun a container's upper bound — an *optional*
    // child is skipped once its cardinality is full (a mandatory one still
    // materialises; a template whose mandatory children alone exceed the bound
    // is contradictory and the validator's job to report).
    let mut card_counts = vec![0usize; node.cardinalities.len()];
    for child in groups {
        // A template may constrain an attribute the RM does not declare — the
        // deployed OPT 1.4 corpus carries `ELEMENT.null_flavor` (the US
        // archetype-tooling spelling of RM `null_flavour`,
        // `docs/specs/openehr/RM/docs/UML/classes/org.openehr.rm.data_structures.element.adoc`
        // §Attributes) and other RM-1.0.x leftovers. Such a constraint is
        // tolerated when VALIDATING a template, but materializing it here would
        // author an example that is not a conformant RM instance, so the
        // example generator skips it. The generated RM model is the oracle.
        if !rm_declares(&child.aql_path) {
            continue;
        }
        let child_opt = cx.opt_depth + usize::from(is_optional(child));
        let include = match cx.level {
            DetailLevel::Required => child_opt == 0,
            DetailLevel::Medium | DetailLevel::Complete => true,
        };
        if !include || skips_optional(child) {
            continue;
        }
        let ci = cardinality_index(node, child);
        if is_optional(child) && cardinality_full(node, ci, &card_counts) {
            continue;
        }
        included.push(child.aql_path.as_str());
        emitted |= walk_child(node, child, cx, &mut card_counts, out);
    }
    (emitted, included)
}

/// Whether an OPTIONAL child is omitted from the example.
///
/// A node whose coded-name constraint is display/rubric-incoherent (see
/// `CodedName::incoherent`) or whose leaf is unsatisfiable has no instance
/// form every conforming consumer accepts, and an example exists to be
/// committable everywhere. A MANDATORY one is still emitted in our
/// spec-faithful form.
fn skips_optional(child: &WebTemplateNode) -> bool {
    is_optional(child)
        && (child.name_coded.as_ref().is_some_and(|cn| cn.incoherent)
            || is_unsatisfiable_leaf(child))
}

/// The index of the bounded container cardinality a child sits under, if any.
fn cardinality_index(node: &WebTemplateNode, child: &WebTemplateNode) -> Option<usize> {
    node.cardinalities
        .iter()
        .position(|c| c.max != -1 && child.aql_path.starts_with(c.path.as_str()))
}

/// Whether the container cardinality at `index` has reached its upper bound.
fn cardinality_full(node: &WebTemplateNode, index: Option<usize>, counts: &[usize]) -> bool {
    index.is_some_and(|i| {
        let max = node
            .cardinalities
            .get(i)
            .map_or(usize::MAX, |c| usize::try_from(c.max).unwrap_or(usize::MAX));
        counts.get(i).is_some_and(|&n| n >= max)
    })
}

/// Walks one included child, materialising a second occurrence at the
/// `Complete` level to demonstrate repetition (cardinality permitting).
fn walk_child(
    node: &WebTemplateNode,
    child: &WebTemplateNode,
    cx: &WalkCtx<'_>,
    card_counts: &mut [usize],
    out: &mut Map<String, Value>,
) -> bool {
    let ci = cardinality_index(node, child);
    let child_opt = cx.opt_depth + usize::from(is_optional(child));
    let child_prefix = format!("{}/{}", cx.prefix, seg_for(child));
    // A mandatory child must materialise even when all of *its* children are
    // optional (else the mandatory node would go missing).
    let child_force = !is_optional(child);
    let source = interval_part_source(node, child);
    let mut emitted = walk(source, &child_prefix, child_opt, cx.level, child_force, out);
    if emitted && let Some(slot) = ci.and_then(|i| card_counts.get_mut(i)) {
        *slot += 1;
    }
    if cx.level == DetailLevel::Complete
        && emitted
        && is_repeating(child)
        && !cardinality_full(node, ci, card_counts)
    {
        let second_prefix = format!("{}/{}:1", cx.prefix, child.id);
        let second_emitted = walk(child, &second_prefix, child_opt, cx.level, false, out);
        emitted |= second_emitted;
        if second_emitted && let Some(slot) = ci.and_then(|i| card_counts.get_mut(i)) {
            *slot += 1;
        }
    }
    emitted
}

/// The node whose example fills `child`: a `DV_INTERVAL` part the template
/// leaves open takes its constrained sibling's example, so the limits agree
/// (RM `data_types` §DV_INTERVAL `Limits_consistent`).
fn interval_part_source<'a>(
    node: &'a WebTemplateNode,
    child: &'a WebTemplateNode,
) -> &'a WebTemplateNode {
    let open = child.implicit && node.rm_type.starts_with("DV_INTERVAL<");
    let sibling = || {
        node.children
            .iter()
            .find(|s| !s.implicit && s.rm_type == child.rm_type)
    };
    open.then(sibling).flatten().unwrap_or(child)
}

/// Cardinality satisfaction: for every container attribute constrained to
/// `min >= 1`, ensures that many distinct children under it are materialised (a
/// committable skeleton), even where the level would otherwise skip them.
///
/// A child walked here joins `included`.
fn satisfy_cardinalities<'a>(
    node: &WebTemplateNode,
    groups: &[&'a WebTemplateNode],
    included: &mut Vec<&'a str>,
    cx: &WalkCtx<'_>,
    out: &mut Map<String, Value>,
) -> bool {
    let mut emitted = false;
    for card in &node.cardinalities {
        let min = card.min.and_then(|m| usize::try_from(m).ok()).unwrap_or(0);
        let mut count = included
            .iter()
            .filter(|p| p.starts_with(card.path.as_str()))
            .count();
        for child in groups.iter().filter(|c| c.aql_path.starts_with(&card.path)) {
            if count >= min {
                break;
            }
            if included.contains(&child.aql_path.as_str()) {
                continue;
            }
            let child_prefix = format!("{}/{}", cx.prefix, seg_for(child));
            included.push(child.aql_path.as_str());
            emitted |= walk(child, &child_prefix, cx.opt_depth, cx.level, true, out);
            count += 1;
        }
    }
    emitted
}

/// Existence satisfaction: for every attribute the template makes mandatory
/// (AOM 1.4 `master04-constraint_model_package.adoc` §existence, `min >= 1`),
/// ensures a child under it is materialised when one is reachable.
///
/// A mandatory attribute with no reachable child (a structural node carrying no
/// leaf content) is filled from its structural stub by
/// [`fill_mandatory_structures`] instead. A child walked here joins `included`.
fn satisfy_existence<'a>(
    node: &WebTemplateNode,
    groups: &[&'a WebTemplateNode],
    included: &mut Vec<&'a str>,
    cx: &WalkCtx<'_>,
    out: &mut Map<String, Value>,
) -> bool {
    let mut emitted = false;
    for ex in &node.existence {
        if ex.min < 1 || included.iter().any(|p| under_attribute(p, &ex.path)) {
            continue;
        }
        if let Some(child) = groups.iter().find(|c| {
            under_attribute(&c.aql_path, &ex.path) && rm_declares(&c.aql_path) && !skips_optional(c)
        }) {
            let child_prefix = format!("{}/{}", cx.prefix, seg_for(child));
            included.push(child.aql_path.as_str());
            emitted |= walk(child, &child_prefix, cx.opt_depth, cx.level, true, out);
        }
    }
    emitted
}

/// Whether `path` lies under the attribute at `attribute_path`: the attribute
/// itself, or a node or attribute beneath it.
fn under_attribute(path: &str, attribute_path: &str) -> bool {
    path.strip_prefix(attribute_path)
        .is_some_and(|rest| rest.is_empty() || rest.starts_with(['[', '/']))
}

/// The RM attribute an `aql_path` ends in, its predicate stripped.
fn tail_attribute(aql_path: &str) -> &str {
    let tail = aql_path.rsplit('/').next().unwrap_or(aql_path);
    tail.split('[').next().unwrap_or(tail)
}

/// The ELEMENT attributes that describe a value-less ELEMENT: RM
/// `data_structures` §ELEMENT `null_flavour`, and `null_reason`, which
/// `Inv_null_reason_valid` admits only on a null ELEMENT.
const NULL_BRANCH: [&str; 2] = ["null_flavour", "null_reason"];

/// Splits a node's child groups into the ones walked as data and, for an
/// ELEMENT, its null branch ([`NULL_BRANCH`]), which [`walk_null_flavour`]
/// emits only for a value-less ELEMENT.
fn split_null_branch(node: &WebTemplateNode) -> (Vec<&WebTemplateNode>, Vec<&WebTemplateNode>) {
    let groups = child_groups(node);
    if node.rm_type != "ELEMENT" {
        return (groups, Vec::new());
    }
    groups
        .into_iter()
        .partition(|c| !NULL_BRANCH.contains(&tail_attribute(&c.aql_path)))
}

/// Whether a `value` child of `groups` emitted a flat entry under `prefix`.
fn value_emitted(groups: &[&WebTemplateNode], prefix: &str, out: &Map<String, Value>) -> bool {
    groups.iter().any(|c| {
        if tail_attribute(&c.aql_path) != "value" {
            return false;
        }
        let base = format!("{prefix}/{}", seg_for(c));
        out.keys().any(|k| {
            k.strip_prefix(base.as_str())
                .is_some_and(|rest| rest.is_empty() || rest.starts_with(['|', '/', ':']))
        })
    })
}

/// Emits the `null_flavour` of a value-less ELEMENT, the one shape in which RM
/// `data_structures` §ELEMENT `Inv_null_flavour_indicated` requires it.
fn walk_null_flavour(
    null_branch: &[&WebTemplateNode],
    cx: &WalkCtx<'_>,
    out: &mut Map<String, Value>,
) -> bool {
    null_branch
        .iter()
        .find(|c| tail_attribute(&c.aql_path) == "null_flavour")
        .is_some_and(|child| {
            let child_prefix = format!("{}/{}", cx.prefix, seg_for(child));
            walk(child, &child_prefix, cx.opt_depth, cx.level, true, out)
        })
}

/// Fills every mandatory structural attribute the FLAT build left absent with
/// the empty node its structural stub constrains.
///
/// An attribute the template makes mandatory (AOM 1.4
/// `master04-constraint_model_package.adoc` §existence) whose structural child
/// carries no leaf content has no web-template node to walk, so the FLAT map
/// cannot express it. The stub records the constrained identity (RM type,
/// archetype node id, rubric), the value the closed-archetype walk admits
/// (§`Valid_value`); stubs and existence constraints meet on the attribute's
/// absolute archetype path.
fn fill_mandatory_structures(composition: &mut Value, tree: &WebTemplateNode) {
    let mut mandatory: BTreeSet<&str> = BTreeSet::new();
    let mut stubs: BTreeMap<&str, &WebTemplateStructuralStub> = BTreeMap::new();
    collect_mandatory_structures(tree, &mut mandatory, &mut stubs);
    for path in mandatory {
        let Some(stub) = stubs.get(path) else {
            continue;
        };
        let Some(owner) = path
            .strip_suffix(stub.attr.as_str())
            .and_then(|p| p.strip_suffix('/'))
        else {
            continue;
        };
        let segments = if owner.is_empty() {
            Vec::new()
        } else {
            match owner.parse::<RmPath>() {
                Ok(p) => p.segments,
                // NOTE: no openEHR spec governs example generation — an owner
                // path that does not parse locates nothing, so nothing is filled.
                Err(_) => continue,
            }
        };
        let default_name = if stub.rm_type == "HISTORY" {
            "History"
        } else {
            "Tree"
        };
        for_each_at_mut(composition, &segments, &mut |obj| {
            if let Value::Object(m) = obj
                && !m.contains_key(&stub.attr)
            {
                m.insert(stub.attr.clone(), structural_from(stub, default_name));
            }
        });
    }
}

/// Adds the occurrences a content-less mandatory SECTION is short of.
///
/// A SECTION the template constrains by its name alone has no leaf, so the FLAT
/// map cannot express it. `SECTION.items` is optional
/// (`RM/docs/UML/classes/org.openehr.rm.composition.section.adoc` §Attributes),
/// so the empty node is a conforming instance, inserted up to its occurrences
/// lower bound (AOM 1.4 `master04-constraint_model_package.adoc`
/// §occurrences).
fn fill_content_less_sections(composition: &mut Value, node: &WebTemplateNode, rm_version: &str) {
    for child in &node.children {
        if child.rm_type == "SECTION" && child.children.is_empty() {
            insert_missing_occurrences(composition, child, rm_version);
        }
        fill_content_less_sections(composition, child, rm_version);
    }
}

/// Inserts empty instances of `node` under every owner its `aql_path` reaches
/// until each holds the node's occurrences lower bound.
fn insert_missing_occurrences(composition: &mut Value, node: &WebTemplateNode, rm_version: &str) {
    let Some(min) = node
        .min
        .and_then(|m| usize::try_from(m).ok())
        .filter(|m| *m >= 1)
    else {
        return;
    };
    // NOTE: no openEHR spec governs example generation — a path that does not
    // parse locates nothing, so nothing is inserted.
    let Ok(path) = node.aql_path.parse::<RmPath>() else {
        return;
    };
    let Some((last, owner)) = path.segments.split_last() else {
        return;
    };
    let name = last
        .predicate
        .name_value
        .clone()
        .or_else(|| node.localized_name.clone())
        .or_else(|| node.name.clone())
        .unwrap_or_else(|| node.id.clone());
    let mut instance = Map::new();
    instance.insert("_type".into(), json!(node.rm_type));
    instance.insert("name".into(), json!({"_type": "DV_TEXT", "value": name}));
    if let Some(id) = recorded_archetype_id(node) {
        instance.insert("archetype_node_id".into(), json!(id));
    }
    stamp_archetype_details(&mut instance, node, false, "", rm_version);
    let instance = Value::Object(instance);
    for_each_at_mut(composition, owner, &mut |obj| {
        let Value::Object(m) = obj else {
            return;
        };
        let Value::Array(items) = m
            .entry(last.attribute.clone())
            .or_insert_with(|| Value::Array(Vec::new()))
        else {
            return;
        };
        let present = items
            .iter()
            .filter(|item| last.predicate.matches(item))
            .count();
        for _ in present..min {
            items.push(instance.clone());
        }
    });
}

/// Collects the mandatory attribute paths and the structural stubs of the
/// whole web-template tree.
fn collect_mandatory_structures<'a>(
    node: &'a WebTemplateNode,
    mandatory: &mut BTreeSet<&'a str>,
    stubs: &mut BTreeMap<&'a str, &'a WebTemplateStructuralStub>,
) {
    for ex in node.existence.iter().filter(|ex| ex.min >= 1) {
        mandatory.insert(ex.path.as_str());
    }
    for stub in &node.structural_stubs {
        stubs.entry(stub.path.as_str()).or_insert(stub);
    }
    for child in &node.children {
        collect_mandatory_structures(child, mandatory, stubs);
    }
}

/// Applies `f` to every canonical-JSON node `segments` reach from `node`.
///
/// Each step selects the values under the segment's attribute whose
/// archetype-node-id and name conjuncts the segment predicate matches (BASE
/// `master11-paths` §"Predicate Expressions"), descending into every element
/// of a container attribute.
fn for_each_at_mut(node: &mut Value, segments: &[PathSegment], f: &mut dyn FnMut(&mut Value)) {
    let Some((segment, rest)) = segments.split_first() else {
        f(node);
        return;
    };
    let Some(child) = node.get_mut(&segment.attribute) else {
        return;
    };
    match child {
        Value::Array(items) => {
            for item in items {
                if segment.predicate.matches(item) {
                    for_each_at_mut(item, rest, f);
                }
            }
        }
        single => {
            if segment.predicate.matches(single) {
                for_each_at_mut(single, rest, f);
            }
        }
    }
}

/// The children to consider under a container: one per distinct `aql_path` (the
/// first alternative of any polymorphic choice). Under an `EVENT_CONTEXT` only
/// the archetyped `other_context` content is walked; its standard fields are
/// rebuilt from the `ctx/…` context keys by `from_flat` (Simplified Formats
/// master06).
fn child_groups(node: &WebTemplateNode) -> Vec<&WebTemplateNode> {
    let mut seen: HashSet<&str> = HashSet::new();
    let context = node.rm_type == "EVENT_CONTEXT";
    node.children
        .iter()
        .filter(|c| !context || c.aql_path.contains("/other_context"))
        .filter(|c| seen.insert(c.aql_path.as_str()))
        .collect()
}

/// Whether a node is optional (occurrences lower bound `< 1`).
fn is_optional(node: &WebTemplateNode) -> bool {
    node.min.unwrap_or(0) < 1
}

/// Whether a node may occur more than once (Better's `isRepeating`).
fn is_repeating(node: &WebTemplateNode) -> bool {
    node.max == -1 || node.max > 1
}

/// Does the generated RM model declare the attribute `aql_path` ends in?
///
/// The tail of an AQL path is the RM attribute the node sits under (predicates
/// stripped). An attribute name no RM class declares cannot be materialized
/// into a conformant instance — see the call site for the `null_flavor` case.
/// The check is name-only, deliberately: FLAT level removal means a Web
/// Template child may sit several RM levels below its Web Template parent, so
/// the parent's class is not the right scope to resolve against.
fn rm_declares(aql_path: &str) -> bool {
    static DECLARED: std::sync::LazyLock<BTreeSet<&str>> = std::sync::LazyLock::new(|| {
        openehr_rm::v1_2::model::classes()
            .flat_map(|c| c.attributes.iter().map(|a| a.name))
            .collect()
    });
    let attr = tail_attribute(aql_path);
    attr.is_empty() || DECLARED.contains(attr)
}

/// The flat path segment for a node: `id:0` for a repeating node (`max == -1 ||
/// max > 1`), else the bare `id` — matching
/// [`composition_to_flat`](crate::flat::convert::composition_to_flat) so the example
/// round-trips.
fn seg_for(node: &WebTemplateNode) -> String {
    if is_repeating(node) {
        format!("{}:0", node.id)
    } else {
        node.id.clone()
    }
}

// ── leaf value emission ─────────────────────────────────────────────────────────

/// Emit the flat `path|suffix` entries for one leaf value at `base`. Returns
/// whether anything was emitted.
fn emit_leaf(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>) -> bool {
    let rm = node.rm_type.split('<').next().unwrap_or(&node.rm_type);
    match rm {
        "DV_TEXT" | "DV_PARAGRAPH" => {
            put(out, base, "", json!(example_text(node)));
        }
        "DV_URI" => {
            // Honour a C_STRING value pattern (master05 §DV_URI: bare value) and
            // any closed value list before the type default, so the example
            // satisfies the leaf's AOM 1.4 `C_STRING.valid_value`.
            let value = first_input(node)
                .and_then(|i| i.validation.as_ref())
                .and_then(|v| v.pattern.as_deref())
                .and_then(example_for_pattern)
                .or_else(|| list_value(first_input(node)))
                .unwrap_or_else(|| "http://example.org/resource".to_owned());
            put(out, base, "", json!(value));
        }
        "DV_EHR_URI" => {
            // A DV_EHR_URI value MUST have scheme `ehr` (RM data_types
            // `UML/classes/org.openehr.rm.data_types.dv_ehr_uri.adoc`
            // §`Scheme_valid`: `scheme.is_equal(Ehr_scheme)`); this is
            // non-negotiable, so the value is always a valid `ehr:` URI even when a
            // C_STRING pattern also constrains it — an ehr URI that also matches the
            // pattern when one exists ([`ehr_uri_example`]), else the default. (A
            // pattern no ehr URI can match is a defective OPT constraint; the
            // OPTIONAL leaf carrying it is omitted upstream in [`walk`].)
            put(out, base, "", json!(ehr_uri_example(node)));
        }
        "DV_CODED_TEXT" => emit_coded_text(node, base, out),
        "CODE_PHRASE" => emit_code_phrase(node, base, out),
        "DV_QUANTITY" => emit_quantity(node, base, out),
        "DV_COUNT" => {
            let range = first_input(node).and_then(input_range);
            put(out, base, "", json!(pick_count(range)));
        }
        "DV_PROPORTION" => emit_proportion(node, base, out),
        "DV_ORDINAL" => emit_ordinal(node, base, out, false),
        "DV_SCALE" => emit_ordinal(node, base, out, true),
        "DV_BOOLEAN" => put(out, base, "", json!(example_boolean(node))),
        "DV_DATE_TIME" | "DV_DATE" | "DV_TIME" => {
            put(out, base, "", json!(example_temporal(node, rm)));
        }
        "DV_DURATION" => put(out, base, "", json!(example_duration(node))),
        "DV_IDENTIFIER" => {
            // `id` is RM-mandatory (RM `data_types` §`DV_IDENTIFIER`); honour a
            // C_STRING constraint on it, else a placeholder.
            let id = input_with_suffix(node, "id")
                .and_then(constrained_string_example)
                .unwrap_or_else(|| "example-id".to_owned());
            put(out, base, "id", json!(id));
            // Fill any OPT-constrained (hence, per the builder, mandated)
            // sub-attribute with a conforming value so the example validates
            // (AOM 1.4 `C_STRING.valid_value`; the validator enforces a
            // constrained-and-mandatory DV_IDENTIFIER sub-attribute's presence).
            for part in ["issuer", "assigner", "type"] {
                if let Some(value) =
                    input_with_suffix(node, part).and_then(constrained_string_example)
                {
                    put(out, base, part, json!(value));
                }
            }
        }
        "DV_MULTIMEDIA" => {
            put(out, base, "", json!("http://example.org/media"));
            // Honour a `C_CODE_PHRASE` list on `media_type` (captured in
            // `code_lists` — the constraint the validator enforces).
            let media = node
                .code_lists
                .iter()
                .find(|cl| cl.attr == "media_type")
                .and_then(|cl| cl.codes.first())
                .map_or("text/plain", String::as_str);
            put(out, base, "mediatype", json!(media));
            // A plausible non-zero size. `Size_valid` is `size >= 0`
            // (`RM docs/UML/classes/org.openehr.rm.data_types.dv_multimedia.adoc`
            // §Invariants), so 0 is spec-valid — but a referenced resource of
            // zero bytes is unreal, and these are illustrative examples.
            put(out, base, "size", json!(1024));
        }
        "DV_PARSABLE" => {
            // master05 §DV_PARSABLE: bare `value` + `|formalism`. The formalism is
            // an RM-mandatory String the archetype usually constrains to a closed
            // C_STRING list (e.g. `text/html`); pick its first member so the
            // example is valid — never the bare `"text"` default when a list
            // constrains it (AOM 1.4 `C_STRING.valid_value`).
            let value = input_with_suffix(node, "value")
                .or_else(|| first_input(node))
                .and_then(|i| i.validation.as_ref())
                .and_then(|v| v.pattern.as_deref())
                .and_then(example_for_pattern)
                .unwrap_or_else(|| "example".to_owned());
            let formalism = input_with_suffix(node, "formalism")
                .filter(|i| i.list_open != Some(true))
                .and_then(|i| i.list.first())
                .map_or_else(|| "text".to_owned(), |cv| cv.value.clone());
            put(out, base, "", json!(value));
            put(out, base, "formalism", json!(formalism));
        }
        // A slot NARROWED to a concrete non-default party subtype must
        // materialize: the builder's unset-subject default is PARTY_SELF
        // (master05 §OBSERVATION `/subject` row Note), which the template's own
        // constraint then refuses — so the example emits the minimal members
        // the narrowed subtype mandates. PARTY_RELATED additionally carries
        // `relationship` 1..1 (RM common `party_related.adoc`), whose example
        // code comes from the node's own relationship child.
        "PARTY_IDENTIFIED" => put(out, base, "name", json!("Example party")),
        "PARTY_RELATED" => {
            put(out, base, "name", json!("Example party"));
            let rel_base = format!("{base}/relationship");
            if let Some(rel) = node
                .children
                .iter()
                .find(|c| c.id == "relationship" || c.aql_path.ends_with("/relationship"))
            {
                emit_coded_text(rel, &rel_base, out);
            } else {
                // Unconstrained: the openEHR `related party relationship`
                // group's canonical unknown (TERM 3.1.0).
                put(out, &rel_base, "code", json!("253"));
                put(out, &rel_base, "value", json!("unknown"));
                put(out, &rel_base, "terminology", json!("openehr"));
            }
        }
        // Every OTHER party leaf (an unnarrowed PARTY_PROXY, PARTY_SELF) is
        // skipped rather than fabricated: an unset `ENTRY.subject` defaults
        // to PARTY_SELF and a `COMPOSITION.composer` comes from
        // `ctx/composer_*`, so inventing a named party here would put a
        // fictitious person in the example. See the module NOTE. A DV_STATE
        // is left out too: master05 has no §DV_STATE table to spell it (#3936).
        _ => return false,
    }
    true
}

/// Insert a flat entry at `base` (bare) or `base|suffix`.
fn put(out: &mut Map<String, Value>, base: &str, suffix: &str, value: Value) {
    let key = if suffix.is_empty() {
        base.to_owned()
    } else {
        format!("{base}|{suffix}")
    };
    out.insert(key, value);
}

/// A deterministic text value: the first enumerated value (a non-open string
/// list), else the node's rubric name, else a generic placeholder.
fn example_text(node: &WebTemplateNode) -> String {
    if let Some(input) = first_input(node)
        && input.input_type == WebTemplateInputType::Text
        && input.list_open != Some(true)
        && let Some(cv) = input.list.first()
    {
        return cv.value.clone();
    }
    // Honour a C_STRING value pattern when one constrains the free text
    // (AOM 1.4 `C_STRING.valid_value`).
    if let Some(value) = first_input(node)
        .and_then(|i| i.validation.as_ref())
        .and_then(|v| v.pattern.as_deref())
        .and_then(example_for_pattern)
    {
        return value;
    }
    node.name
        .clone()
        .unwrap_or_else(|| "Example text".to_owned())
}

/// A deterministic string satisfying a leaf's `C_STRING` value pattern, for the
/// literal-ish patterns the corpus carries (`/abcdef/`, `/xyz/`). Returns `None`
/// when the pattern uses regex metacharacters (no single canonical instance) —
/// the caller then falls back to its type default. AOM 1.4 `C_STRING.valid_value`
/// (`AM/docs/AOM1.4/master04-constraint_model_package.adoc` §`C_STRING`): a value
/// is valid iff it matches the pattern; the ADL regex is `/`-delimited
/// (`ADL1.4/master05-cadl.adoc` §Regular Expression).
fn example_for_pattern(pattern: &str) -> Option<String> {
    const META: &[char] = &[
        '.', '^', '$', '*', '+', '?', '(', ')', '[', ']', '{', '}', '|', '\\',
    ];
    let body = pattern
        .strip_prefix('/')
        .and_then(|p| p.strip_suffix('/'))
        .unwrap_or(pattern);
    if body.is_empty() || body.chars().any(|c| META.contains(&c)) {
        return None;
    }
    // A literal pattern matches its own text; confirm before committing to it.
    if pattern_matches(body, body) {
        Some(body.to_owned())
    } else {
        None
    }
}

/// A deterministic value satisfying a leaf sub-attribute's `C_STRING` constraint
/// (a closed value list or a value pattern), or `None` when the input carries no
/// enforceable string constraint. Used to fill an OPT-constrained (hence
/// mandated) `DV_IDENTIFIER` sub-attribute (AOM 1.4
/// `master04-constraint_model_package.adoc` §`C_STRING`). For a pattern, the
/// literal pattern body is offered when it satisfies its own regex (e.g. `gov.si`,
/// where `.` matches the literal dot) — a conforming instance even when the
/// pattern carries regex metacharacters that [`example_for_pattern`] declines.
fn constrained_string_example(input: &WebTemplateInput) -> Option<String> {
    if input.list_open != Some(true)
        && let Some(cv) = input.list.first()
    {
        return Some(cv.value.clone());
    }
    let pattern = input.validation.as_ref()?.pattern.as_deref()?;
    example_for_pattern(pattern).or_else(|| {
        let body = pattern
            .strip_prefix('/')
            .and_then(|p| p.strip_suffix('/'))
            .unwrap_or(pattern);
        (!body.is_empty() && pattern_matches(pattern, body)).then(|| body.to_owned())
    })
}

/// Whether `value` satisfies an ADL `C_STRING` regex `pattern` (`/`-delimited,
/// anchored full-match — mirroring the leaf validator's `matches_pattern`). An
/// uninterpretable pattern is treated as matching (it cannot be evaluated, so it
/// does not over-constrain the example).
fn pattern_matches(pattern: &str, value: &str) -> bool {
    let body = pattern
        .strip_prefix('/')
        .and_then(|p| p.strip_suffix('/'))
        .unwrap_or(pattern);
    match regex::Regex::new(&format!("^(?:{body})$")) {
        Ok(re) => re.is_match(value),
        Err(_) => true,
    }
}

/// The C_STRING value pattern constraining a leaf, if any.
fn value_pattern(node: &WebTemplateNode) -> Option<&str> {
    node.inputs
        .first()
        .and_then(|i| i.validation.as_ref())
        .and_then(|v| v.pattern.as_deref())
}

/// The default DV_EHR_URI value — scheme `ehr` (RM `DV_EHR_URI.Scheme_valid`).
const EHR_URI_DEFAULT: &str = "ehr://example.org/composition";

/// A deterministic DV_EHR_URI value: always an `ehr:`-scheme URI (RM data_types
/// `UML/classes/org.openehr.rm.data_types.dv_ehr_uri.adoc` §`Scheme_valid`), and
/// matching the leaf's C_STRING pattern when the default (or a literal instance
/// that is itself an ehr URI) satisfies it. When no ehr URI can satisfy the
/// pattern the default is returned — a valid RM value; the un-committable OPTIONAL
/// leaf carrying such a defective OPT constraint is omitted in [`walk`].
fn ehr_uri_example(node: &WebTemplateNode) -> String {
    let Some(pattern) = value_pattern(node) else {
        return EHR_URI_DEFAULT.to_owned();
    };
    if pattern_matches(pattern, EHR_URI_DEFAULT) {
        return EHR_URI_DEFAULT.to_owned();
    }
    // A literal pattern instance that is itself an `ehr:` URI satisfies both.
    match example_for_pattern(pattern) {
        Some(lit) if lit.starts_with("ehr:") => lit,
        _ => EHR_URI_DEFAULT.to_owned(),
    }
}

/// Whether an OPTIONAL leaf has no committable value because its archetype
/// C_STRING constraint contradicts an RM invariant of the leaf type — currently a
/// DV_EHR_URI whose value pattern no `ehr:`-scheme URI can match (the OPT's
/// C_STRING contradicts RM `DV_EHR_URI.Scheme_valid`). Such a leaf is omitted from
/// the example when optional (the example must be committable — the same posture
/// as an incoherent coded-name node), never fabricated into an invalid value.
fn is_unsatisfiable_leaf(node: &WebTemplateNode) -> bool {
    let rm = node.rm_type.split('<').next().unwrap_or(&node.rm_type);
    if rm != "DV_EHR_URI" {
        return false;
    }
    value_pattern(node).is_some_and(|p| !pattern_matches(p, &ehr_uri_example(node)))
}

fn emit_coded_text(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>) {
    let input = input_with_suffix(node, "code").or_else(|| first_input(node));
    let (code, value, terminology) = coded_example(input);
    put(out, base, "code", json!(code));
    put(out, base, "value", json!(value));
    put(out, base, "terminology", json!(terminology));
}

fn emit_code_phrase(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>) {
    let input = input_with_suffix(node, "code").or_else(|| first_input(node));
    let (code, _value, terminology) = coded_example(input);
    put(out, base, "code", json!(code));
    put(out, base, "terminology", json!(terminology));
}

/// The `(code, value, terminology)` for an example coded value: the first entry
/// of the input's coded list, else a placeholder local code. The list labels
/// already carry the display text — term definitions, then the TERM 3.1.0
/// rubric for `openehr` codes (`webtemplate::inputs::coded_value`).
fn coded_example(input: Option<&WebTemplateInput>) -> (String, String, String) {
    match input {
        Some(i) if !i.list.is_empty() => {
            let Some(cv) = i.list.first() else {
                return (String::new(), String::new(), "local".to_owned());
            };
            let terminology = i.terminology.clone().unwrap_or_else(|| "local".to_owned());
            let value = cv.label.clone().unwrap_or_else(|| cv.value.clone());
            (cv.value.clone(), value, terminology)
        }
        Some(i) => (
            "at0000".to_owned(),
            "Example".to_owned(),
            i.terminology.clone().unwrap_or_else(|| "local".to_owned()),
        ),
        None => (
            "at0000".to_owned(),
            "Example".to_owned(),
            "local".to_owned(),
        ),
    }
}

fn emit_quantity(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>) {
    let unit_input = input_with_suffix(node, "unit");
    let unit = unit_input
        .and_then(|i| i.list.first())
        .map(|cv| cv.value.clone())
        .or_else(|| {
            // No enumerated C_QUANTITY_ITEM unit list: if the constraint fixes a
            // measurement `property`, emit a valid unit for it (the primary/base
            // unit, else the first) so the generated example satisfies the
            // property→units check (openEHR `PropertyUnitData.xml` table). A
            // property with no table entry falls through to the "1" default.
            node.quantity_property.as_deref().and_then(|p| {
                let units = openehr_term::bundle::openehr().units_for_property(p);
                units
                    .iter()
                    .find(|u| u.primary)
                    .or_else(|| units.first())
                    .map(|u| u.text.clone())
            })
        })
        .unwrap_or_else(|| "1".to_owned());
    // Prefer the magnitude input's own range, else the range scoped to the unit.
    let range = input_with_suffix(node, "magnitude")
        .and_then(input_range)
        .or_else(|| {
            unit_input
                .and_then(|i| i.list.first())
                .and_then(|cv| cv.validation.as_ref())
                .and_then(|v| v.range.as_ref())
        });
    put(out, base, "magnitude", json!(pick_decimal(range)));
    put(out, base, "unit", json!(unit));
}

fn emit_proportion(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>) {
    // Choose values satisfying the DV_PROPORTION invariants for the first
    // allowed kind AND the archetype's numerator/denominator ranges (RM
    // data_types `dv_proportion.adoc`: `Unitary_validity` denominator = 1,
    // `Percent_validity` 100, `Fraction_validity` integral, `Valid_denominator`
    // ≠ 0). `type` codes (PROPORTION_KIND): ratio 0, unitary 1, percent 2,
    // fraction 3, integer_fraction 4. The ranges ride on the
    // `numerator`/`denominator` inputs (master05 §DV_PROPORTION), which the leaf
    // validator range-checks, so the picked values must land inside them.
    let type_code = match node.proportion_types.first().map(String::as_str) {
        Some("unitary") => 1,
        Some("percent") => 2,
        Some("fraction") => 3,
        Some("integer_fraction") => 4,
        _ => 0,
    };
    let num_input = input_with_suffix(node, "numerator");
    let den_input = input_with_suffix(node, "denominator");
    // Fraction kinds force integral numerator+denominator; the builder also types
    // the numerator/denominator inputs as `Integer` when the archetype constrains
    // `is_integral` (RM `Is_integral_validity`).
    let integral = matches!(type_code, 3 | 4)
        || num_input.is_some_and(|i| i.input_type == WebTemplateInputType::Integer)
        || den_input.is_some_and(|i| i.input_type == WebTemplateInputType::Integer);
    let numerator = pick_proportion_part(num_input.and_then(input_range), integral, false);
    let denominator = match type_code {
        1 => 1.0,   // Unitary_validity: denominator = 1
        2 => 100.0, // Percent_validity: denominator = 100
        _ => pick_proportion_part(den_input.and_then(input_range), integral, true),
    };
    put(out, base, "numerator", json!(numerator));
    put(out, base, "denominator", json!(denominator));
    put(out, base, "type", json!(type_code));
}

/// Pick a DV_PROPORTION numerator/denominator inside `range` (deterministic).
/// `integral` forces a whole number (fraction kinds / `is_integral`), `avoid_zero`
/// forbids `0` (a denominator must be non-zero — `Valid_denominator`). Falls back
/// to the nearest in-range decimal when no in-range integer exists (a contradictory
/// integral range — none in the corpus).
fn pick_proportion_part(range: Option<&WebTemplateRange>, integral: bool, avoid_zero: bool) -> f64 {
    let v = pick_decimal(range);
    if !integral {
        return v;
    }
    for cand in [v.round(), v.floor(), v.ceil()] {
        if in_decimal_range(cand, range) && !(avoid_zero && cand == 0.0) {
            return cand;
        }
    }
    v
}

/// Whether `v` satisfies a `WebTemplateRange` (honouring `minOp`/`maxOp`; missing
/// bounds are unbounded) — mirrors the leaf validator's `in_range`.
fn in_decimal_range(v: f64, range: Option<&WebTemplateRange>) -> bool {
    let Some(r) = range else { return true };
    if let Some(min) = r.min.as_ref().and_then(Value::as_f64) {
        let ok = if r.min_op.as_deref() == Some(">") {
            v > min
        } else {
            v >= min
        };
        if !ok {
            return false;
        }
    }
    if let Some(max) = r.max.as_ref().and_then(Value::as_f64) {
        let ok = if r.max_op.as_deref() == Some("<") {
            v < max
        } else {
            v <= max
        };
        if !ok {
            return false;
        }
    }
    true
}

fn emit_ordinal(node: &WebTemplateNode, base: &str, out: &mut Map<String, Value>, scale: bool) {
    let numeric_suffix = if scale { "scale" } else { "ordinal" };
    if let Some(cv) = first_input(node).and_then(|i| i.list.first()) {
        let numeric = if scale {
            json!(cv.scale.unwrap_or(0.0))
        } else {
            json!(cv.ordinal.unwrap_or(0))
        };
        put(out, base, numeric_suffix, numeric);
        put(out, base, "code", json!(cv.value));
        put(
            out,
            base,
            "value",
            json!(cv.label.clone().unwrap_or_else(|| cv.value.clone())),
        );
    } else {
        put(
            out,
            base,
            numeric_suffix,
            if scale { json!(0.0) } else { json!(0) },
        );
        put(out, base, "code", json!("at0000"));
        put(out, base, "value", json!("Example"));
    }
}

/// A deterministic temporal example honouring the leaf's AOM 1.4 temporal
/// pattern (`yyyy-??-XX` etc.: literal = mandatory, `??` = optional/kept,
/// `XX` = prohibited/omitted — mirroring the validator's presence-only
/// judgement) and the `timezone_validity` constraint (`1003` = the designator
/// must be absent; the fixed example instants already carry `Z` for the rest).
fn example_temporal(node: &WebTemplateNode, rm: &str) -> String {
    let pattern = node
        .inputs
        .first()
        .and_then(|i| i.validation.as_ref())
        .and_then(|v| v.pattern.as_deref());
    let (pat_date, pat_time) = match pattern {
        Some(p) if p.contains('T') => {
            let (d, t) = p.split_once('T').unwrap_or((p, ""));
            (d, t)
        }
        Some(p) if p.contains(':') => ("", p),
        Some(p) => (p, ""),
        None => ("", ""),
    };
    let tz = if node.tz_validity == Some(1003) {
        ""
    } else {
        "Z"
    };
    let date = temporal_segments(pat_date, DATE_SEGMENTS, '-');
    match rm {
        "DV_DATE" => date,
        "DV_TIME" => format!("{}{tz}", temporal_segments(pat_time, TIME_SEGMENTS, ':')),
        // DV_DATE_TIME: a time part prohibited outright (pattern `…TXX:…`)
        // truncates to the date.
        _ if pat_time.starts_with("XX") => date,
        _ => format!(
            "{date}T{}{tz}",
            temporal_segments(pat_time, TIME_SEGMENTS, ':')
        ),
    }
}

/// The example date's segments, coarsest first.
const DATE_SEGMENTS: [&str; 3] = ["2022", "02", "03"];

/// The example time's segments, coarsest first.
const TIME_SEGMENTS: [&str; 3] = ["04", "05", "06"];

/// Renders one temporal half, dropping every segment the pattern prohibits.
///
/// The leading segment is always present; the rest are kept until the pattern
/// marks one `XX`, since ISO 8601 partial precision truncates right-to-left —
/// an omitted month forces the day off with it.
fn temporal_segments(pattern: &str, full: [&str; 3], separator: char) -> String {
    let segments: Vec<&str> = if pattern.is_empty() {
        Vec::new()
    } else {
        pattern.splitn(3, separator).collect()
    };
    let mut out = String::from(full[0]);
    for (i, part) in full.iter().enumerate().skip(1) {
        if segments.get(i).is_some_and(|s| *s == "XX") {
            break;
        }
        out.push(separator);
        out.push_str(part);
    }
    out
}

/// A deterministic duration example honouring the `C_DURATION` allowed-fields
/// pattern (encoded by the builder as which per-field inputs exist — mirroring
/// the validator) and the ISO duration range: the range minimum when one is
/// declared, else one unit of the first allowed field, else `PT1H`.
fn example_duration(node: &WebTemplateNode) -> String {
    // ISO-8601 duration fields, coarsest → finest, with the RM's nominal field
    // lengths in seconds (matching the leaf validator's `duration_seconds`, so a
    // picked value agrees with the range check byte-for-byte): year = 365.25 d,
    // month = 30.4375 d (RM data_types §DV_DURATION magnitude semantics).
    const ISO: &[(&str, bool, char, f64)] = &[
        ("year", false, 'Y', 31_557_600.0),
        ("month", false, 'M', 2_629_800.0),
        ("week", false, 'W', 604_800.0),
        ("day", false, 'D', 86_400.0),
        ("hour", true, 'H', 3_600.0),
        ("minute", true, 'M', 60.0),
        ("second", true, 'S', 1.0),
    ];
    let allowed: Vec<&str> = node
        .inputs
        .iter()
        .filter_map(|i| i.suffix.as_deref())
        .collect();
    // The fields the C_DURATION pattern permits (all when the node lists none or
    // the full seven), coarsest → finest.
    let usable: Vec<&(&str, bool, char, f64)> = ISO
        .iter()
        .filter(|f| allowed.is_empty() || allowed.len() >= 7 || allowed.contains(&f.0))
        .collect();
    // A whole count `n` of `field` (kept as f64 to avoid a lossy float→int cast;
    // printed with no fractional digits).
    let fmt = |field: &(&str, bool, char, f64), n: f64| -> String {
        let (_, is_time, letter, _) = *field;
        if is_time {
            format!("PT{n:.0}{letter}")
        } else {
            format!("P{n:.0}{letter}")
        }
    };
    // Unconstrained: one unit of the coarsest usable field (the historic default).
    let Some(range) = node.duration_range.as_ref() else {
        return usable
            .first()
            .map_or_else(|| EXAMPLE_DURATION.to_owned(), |field| fmt(field, 1.0));
    };
    // Ranged: express a whole count of the FINEST usable field (maximal
    // granularity) inside [min, max] honouring the AOM interval inclusivity
    // (`minOp`/`maxOp` `>`/`<` = excluded bound; BASE foundation_types Interval).
    let field = usable
        .last()
        .copied()
        .unwrap_or(&("hour", true, 'H', 3_600.0));
    let unit = field.3;
    let min_secs = range.min.as_ref().and_then(Value::as_str).map(iso_seconds);
    let max_secs = range.max.as_ref().and_then(Value::as_str).map(iso_seconds);
    let min_excl = range.min_op.as_deref() == Some(">");
    let max_excl = range.max_op.as_deref() == Some("<");
    // The whole-count bounds (in field units) satisfying the second bounds,
    // kept in f64 to avoid a lossy float→int cast.
    let n_lo = match min_secs {
        Some(m) if min_excl => (m / unit).floor() + 1.0,
        Some(m) => (m / unit).ceil(),
        None => 0.0,
    }
    .max(0.0);
    let n_hi = match max_secs {
        Some(m) if max_excl => (m / unit).ceil() - 1.0,
        Some(m) => (m / unit).floor(),
        None => f64::INFINITY,
    };
    if n_lo > n_hi {
        // Contradictory bounds for this field — no in-range whole count exists.
        // Best effort: the literal minimum bound (or one unit).
        return range
            .min
            .as_ref()
            .and_then(Value::as_str)
            .map_or_else(|| fmt(field, 1.0), str::to_owned);
    }
    // Target: the midpoint when bounded above, else just above the minimum.
    let target = match max_secs {
        Some(mx) => f64::midpoint(min_secs.unwrap_or(0.0), mx),
        None => min_secs.unwrap_or(0.0) + unit,
    };
    let n = (target / unit).round().max(n_lo).min(n_hi);
    fmt(field, n)
}

/// Total seconds of an ISO-8601 duration string, using the RM's nominal field
/// lengths (the same constants the leaf validator's `duration_seconds` uses, so a
/// picked example duration and the range check agree). A part that does not parse
/// contributes nothing (the RM-invariant pass owns well-formedness).
fn iso_seconds(value: &str) -> f64 {
    let rest = value.strip_prefix('-').unwrap_or(value);
    let Some(rest) = rest.strip_prefix('P') else {
        return 0.0;
    };
    let (date_part, time_part) = rest.split_once('T').unwrap_or((rest, ""));
    iso_part_seconds(date_part, false) + iso_part_seconds(time_part, true)
}

/// Total seconds of one half of an ISO-8601 duration string.
///
/// `in_time` selects the time-half reading of the ambiguous `M` designator
/// (minutes rather than months).
fn iso_part_seconds(part: &str, in_time: bool) -> f64 {
    let mut total = 0.0;
    let mut num = String::new();
    for ch in part.chars() {
        if ch.is_ascii_digit() || ch == '.' || ch == ',' {
            num.push(if ch == ',' { '.' } else { ch });
            continue;
        }
        let n: f64 = num.parse().unwrap_or(0.0);
        num.clear();
        total += n * iso_designator_seconds(ch, in_time);
    }
    total
}

/// The RM's nominal length in seconds of one ISO-8601 duration designator.
fn iso_designator_seconds(designator: char, in_time: bool) -> f64 {
    match (designator, in_time) {
        ('Y', false) => 31_557_600.0,
        ('M', false) => 2_629_800.0,
        ('W', false) => 604_800.0,
        ('D', false) => 86_400.0,
        ('H', true) => 3_600.0,
        ('M', true) => 60.0,
        ('S', true) => 1.0,
        _ => 0.0,
    }
}

/// A deterministic boolean example: `false` when the archetype allows only
/// `false`, else `true`.
fn example_boolean(node: &WebTemplateNode) -> bool {
    let only_false = first_input(node).is_some_and(|i| {
        i.list.iter().any(|c| c.value == "false") && !i.list.iter().any(|c| c.value == "true")
    });
    !only_false
}

// ── input helpers ───────────────────────────────────────────────────────────────

fn first_input(node: &WebTemplateNode) -> Option<&WebTemplateInput> {
    node.inputs.first()
}

fn input_with_suffix<'a>(node: &'a WebTemplateNode, suffix: &str) -> Option<&'a WebTemplateInput> {
    node.inputs
        .iter()
        .find(|i| i.suffix.as_deref() == Some(suffix))
}

/// The first enumerated value of a (non-open) text input, if any.
fn list_value(input: Option<&WebTemplateInput>) -> Option<String> {
    let input = input?;
    if input.list_open == Some(true) {
        return None;
    }
    input.list.first().map(|cv| cv.value.clone())
}

fn input_range(input: &WebTemplateInput) -> Option<&WebTemplateRange> {
    input.validation.as_ref().and_then(|v| v.range.as_ref())
}

// ── numeric picking (deterministic, range-clamped) ──────────────────────────────

/// A plausible, non-zero decimal example value within `range`.
///
/// An unconstrained magnitude gets a deterministic non-zero default
/// (`DEFAULT_DECIMAL`); a range-constrained one is placed at the range
/// **midpoint** when both bounds exist (honouring the open-bound `>`/`<`
/// operators), and clamped toward the single stated bound otherwise. The result
/// never lands on `0.0` when the range admits a non-zero value: a zero example
/// magnitude is clinically unreal and defeats the multiplicative payload jitter
/// the example skeletons feed. Deterministic (no randomness): the same range
/// always yields the same value. The FLAT/STRUCTURED formats have no versioned
/// openEHR spec of their own — this pick policy is our own design.
fn pick_decimal(range: Option<&WebTemplateRange>) -> f64 {
    /// The default when no numeric bound is stated (a plausible non-zero value).
    const DEFAULT_DECIMAL: f64 = 10.0;
    /// The step taken across an open (`>` / `<`) bound.
    const STEP: f64 = 1.0;

    let Some(r) = range else {
        return DEFAULT_DECIMAL;
    };
    // Effective bounds, moved just inside an open (`>` / `<`) constraint.
    let lo = r.min.as_ref().and_then(Value::as_f64).map(|min| {
        if r.min_op.as_deref() == Some(">") {
            min + STEP
        } else {
            min
        }
    });
    let hi = r.max.as_ref().and_then(Value::as_f64).map(|max| {
        if r.max_op.as_deref() == Some("<") {
            max - STEP
        } else {
            max
        }
    });
    match (lo, hi) {
        (Some(lo), Some(hi)) => {
            let mid = f64::midpoint(lo, hi);
            // A midpoint of 0.0 on a range symmetric about zero (e.g. [-5, 5])
            // would land on the forbidden zero even though a non-zero value is
            // in range — bias to the positive half instead.
            if mid == 0.0 && hi > 0.0 {
                hi / 2.0
            } else {
                mid
            }
        }
        // Only a lower bound: sit at the floor, or the default when that is not
        // above zero (so the pick stays non-zero and in range).
        (Some(lo), None) => lo.max(DEFAULT_DECIMAL),
        // Only an upper bound: sit at the ceiling, or the default when that is
        // not below zero; a non-positive ceiling admits only a value below it.
        (None, Some(hi)) => {
            let v = hi.min(DEFAULT_DECIMAL);
            if v == 0.0 { hi - STEP } else { v }
        }
        (None, None) => DEFAULT_DECIMAL,
    }
}

/// An integer example value clamped into `range` (defaulting to `0`).
fn pick_count(range: Option<&WebTemplateRange>) -> i64 {
    let Some(r) = range else { return 0 };
    let mut v: i64 = 0;
    if let Some(min) = r.min.as_ref().and_then(Value::as_i64) {
        let lo = if r.min_op.as_deref() == Some(">") {
            min + 1
        } else {
            min
        };
        if v < lo {
            v = lo;
        }
    }
    if let Some(max) = r.max.as_ref().and_then(Value::as_i64) {
        let hi = if r.max_op.as_deref() == Some("<") {
            max - 1
        } else {
            max
        };
        if v > hi {
            v = hi;
        }
    }
    v
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::flat::webtemplate::builder::build_web_template;

    fn web_template(opt_rel: &str) -> WebTemplate {
        let path = format!("{}/{opt_rel}", env!("CARGO_MANIFEST_DIR"));
        let xml = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
        let opt = openehr_its::opt14::from_xml(&xml).expect("parse OPT");
        build_web_template(&opt).expect("build web template")
    }

    /// The Demo Vitals template (OBSERVATION with a history of events) vendored
    /// for the FLAT tests.
    fn demo_vitals() -> WebTemplate {
        web_template("tests/fixtures/better/Demo Vitals.opt")
    }

    fn leaf_count(comp: &Value) -> usize {
        // Count populated DATA_VALUE leaves as a coarse coverage metric.
        fn rec(v: &Value, n: &mut usize) {
            match v {
                Value::Object(m) => {
                    if m.get("_type")
                        .and_then(Value::as_str)
                        .is_some_and(|t| t.starts_with("DV_"))
                    {
                        *n += 1;
                    }
                    for val in m.values() {
                        rec(val, n);
                    }
                }
                Value::Array(a) => {
                    for e in a {
                        rec(e, n);
                    }
                }
                _ => {}
            }
        }
        let mut n = 0;
        rec(comp, &mut n);
        n
    }

    #[test]
    fn parses_detail_level() {
        assert_eq!(DetailLevel::from_query(None), Ok(DetailLevel::Required));
        assert_eq!(
            DetailLevel::from_query(Some("required")),
            Ok(DetailLevel::Required)
        );
        assert_eq!(
            DetailLevel::from_query(Some("medium")),
            Ok(DetailLevel::Medium)
        );
        assert_eq!(
            DetailLevel::from_query(Some("complete")),
            Ok(DetailLevel::Complete)
        );
        assert!(DetailLevel::from_query(Some("full")).is_err());
    }

    #[test]
    fn parses_example_type() {
        assert_eq!(ExampleType::from_query(None), Ok(ExampleType::Input));
        assert_eq!(
            ExampleType::from_query(Some("input")),
            Ok(ExampleType::Input)
        );
        assert_eq!(
            ExampleType::from_query(Some("output")),
            Ok(ExampleType::Output)
        );
        assert!(ExampleType::from_query(Some("bogus")).is_err());
    }

    // A present out-of-enum value is refused even when it is empty or a
    // whitespace-padded spelling of a token: the declared default applies
    // only to an ABSENT parameter (ITS-REST
    // parameters/query/example_detail_level.yaml, example_type.yaml — closed
    // enums), so no present value may silently become one.
    #[test]
    fn refuses_present_out_of_enum_values() {
        for bad in ["", " ", " required ", "REQUIRED", "required\n"] {
            assert!(
                DetailLevel::from_query(Some(bad)).is_err(),
                "detail_level {bad:?} must refuse"
            );
        }
        for bad in ["", " ", " input ", "INPUT", "output "] {
            assert!(
                ExampleType::from_query(Some(bad)).is_err(),
                "type {bad:?} must refuse"
            );
        }
    }

    #[test]
    fn is_deterministic() {
        let wt = demo_vitals();
        let a = example_composition(&wt, DetailLevel::Medium).expect("the example builds");
        let b = example_composition(&wt, DetailLevel::Medium).expect("the example builds");
        assert_eq!(a, b, "two calls produce identical JSON");
    }

    #[test]
    fn is_a_composition_with_housekeeping() {
        let wt = demo_vitals();
        let comp = example_composition(&wt, DetailLevel::Required).expect("the example builds");
        assert_eq!(
            comp.get("_type").and_then(Value::as_str),
            Some("COMPOSITION")
        );
        assert!(comp.get("language").is_some(), "mandatory language present");
        assert!(
            comp.get("territory").is_some(),
            "mandatory territory present"
        );
        assert!(comp.get("composer").is_some(), "mandatory composer present");
        assert!(comp.get("category").is_some(), "mandatory category present");
        assert_eq!(
            comp.pointer("/composer/name").and_then(Value::as_str),
            Some("Example composer")
        );
        assert_eq!(
            comp.pointer("/archetype_details/template_id/value")
                .and_then(Value::as_str),
            Some(wt.template_id.as_str()),
            "self-describing template id"
        );
    }

    #[test]
    fn medium_populates_optional_content() {
        // The level's whole point: a template whose content chain is entirely
        // optional still yields a populated document at `medium` (the empty
        // `required` skeleton is the committable *minimum*, not the example).
        let wt = demo_vitals();
        let comp = example_composition(&wt, DetailLevel::Medium).expect("the example builds");
        let content = comp.get("content").and_then(Value::as_array);
        assert!(
            content.is_some_and(|c| !c.is_empty()),
            "medium example carries content entries"
        );
        assert!(
            leaf_count(&comp)
                > leaf_count(
                    &example_composition(&wt, DetailLevel::Required).expect("the example builds")
                ),
            "medium populates strictly more leaves than required"
        );
    }

    #[test]
    fn complete_demonstrates_repetition() {
        let wt = demo_vitals();
        let medium = example_composition(&wt, DetailLevel::Medium).expect("the example builds");
        let complete = example_composition(&wt, DetailLevel::Complete).expect("the example builds");
        assert!(
            leaf_count(&complete) > leaf_count(&medium),
            "complete adds second occurrences of repeating nodes"
        );
    }

    #[test]
    fn levels_are_monotonic() {
        let wt = demo_vitals();
        let required = leaf_count(
            &example_composition(&wt, DetailLevel::Required).expect("the example builds"),
        );
        let medium =
            leaf_count(&example_composition(&wt, DetailLevel::Medium).expect("the example builds"));
        let complete = leaf_count(
            &example_composition(&wt, DetailLevel::Complete).expect("the example builds"),
        );
        assert!(
            required <= medium && medium <= complete,
            "coverage grows with detail: required={required}, medium={medium}, complete={complete}"
        );
        assert!(
            complete > required,
            "a rich template exposes more leaves at complete than required \
             (required={required}, complete={complete})"
        );
    }

    #[test]
    fn output_populates_a_deterministic_uid() {
        let wt = demo_vitals();
        let mut input =
            example_composition(&wt, DetailLevel::Required).expect("the example builds");
        assert!(input.get("uid").is_none(), "input form has no uid");

        let mut output = input.clone();
        apply_output_uid(&mut output, &wt.template_id);
        let uid = output
            .pointer("/uid/value")
            .and_then(Value::as_str)
            .expect("output uid");
        assert!(
            uid.ends_with("::example.server::1"),
            "OBJECT_VERSION_ID form: {uid}"
        );
        assert_eq!(
            output.pointer("/uid/_type").and_then(Value::as_str),
            Some("OBJECT_VERSION_ID")
        );

        // Deterministic across calls.
        apply_output_uid(&mut input, &wt.template_id);
        assert_eq!(input.get("uid"), output.get("uid"));
    }

    fn range(
        min: Option<f64>,
        min_op: Option<&str>,
        max: Option<f64>,
        max_op: Option<&str>,
    ) -> WebTemplateRange {
        WebTemplateRange {
            min_op: min_op.map(str::to_owned),
            min: min.map(|m| json!(m)),
            max_op: max_op.map(str::to_owned),
            max: max.map(|m| json!(m)),
        }
    }

    #[test]
    fn pick_decimal_is_non_zero_and_in_range() {
        // Unconstrained: a plausible non-zero default, not 0.0.
        assert_eq!(pick_decimal(None), 10.0);
        // Both bounds present: the midpoint (never the min, never 0.0).
        assert_eq!(
            pick_decimal(Some(&range(Some(0.0), None, Some(10.0), None))),
            5.0
        );
        assert_eq!(
            pick_decimal(Some(&range(Some(60.0), None, Some(80.0), None))),
            70.0
        );
        // A range symmetric about zero must not yield the forbidden 0.0.
        let v = pick_decimal(Some(&range(Some(-5.0), None, Some(5.0), None)));
        assert!(
            v != 0.0 && (-5.0..=5.0).contains(&v),
            "in range, non-zero: {v}"
        );
        // Only a lower bound: at the floor when it is above zero, else the default.
        assert_eq!(
            pick_decimal(Some(&range(Some(50.0), None, None, None))),
            50.0
        );
        assert_eq!(
            pick_decimal(Some(&range(Some(0.0), None, None, None))),
            10.0
        );
        // Only an upper bound: below the ceiling, non-zero.
        assert_eq!(
            pick_decimal(Some(&range(None, None, Some(100.0), None))),
            10.0
        );
        assert_eq!(pick_decimal(Some(&range(None, None, Some(4.0), None))), 4.0);
        // Open bounds are honoured (`>` / `<` exclude the stated value).
        assert_eq!(
            pick_decimal(Some(&range(Some(0.0), Some(">"), None, None))),
            10.0
        );
        let hi = pick_decimal(Some(&range(None, None, Some(1.0), Some("<"))));
        assert!(hi < 1.0, "strictly below an open upper bound: {hi}");
    }

    #[test]
    fn pick_decimal_populated_magnitudes_are_non_zero() {
        fn collect(v: &Value, out: &mut Vec<f64>) {
            match v {
                Value::Object(m) => {
                    if m.get("_type").and_then(Value::as_str) == Some("DV_QUANTITY")
                        && let Some(x) = m.get("magnitude").and_then(Value::as_f64)
                    {
                        out.push(x);
                    }
                    m.values().for_each(|c| collect(c, out));
                }
                Value::Array(a) => a.iter().for_each(|e| collect(e, out)),
                _ => {}
            }
        }
        // A populated example must not seed a zero-valued quantity magnitude
        // (clinically unreal; defeats multiplicative jitter).
        let wt = demo_vitals();
        let comp = example_composition(&wt, DetailLevel::Medium).expect("the example builds");
        let mut mags = Vec::new();
        collect(&comp, &mut mags);
        assert!(!mags.is_empty(), "Demo Vitals exposes DV_QUANTITY leaves");
        assert!(
            mags.iter().all(|m| *m != 0.0),
            "no example magnitude is zero: {mags:?}"
        );
    }
}