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
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! Simplified tree → RM (canonical JSON) — the composition builder.
//!
//! The reverse of [`crate::flat::flatten`]: the [`WebTemplate`] tree is walked
//! against the parsed [`SimDocument`], each leaf's datum parts rebuild its
//! DATA_VALUE per the `master05-rm_mapping.adoc` tables (`crate::flat::map`),
//! and the RM structural nodes the simplified form omits (ITS-REST
//! `simplified_formats/master04` §Level Removal: `HISTORY`, a collapsed
//! `EVENT`, the `ITEM_STRUCTURE` family, the `ELEMENT` wrapper) are
//! re-materialised from the relative RM path between a node and its
//! parent. The `ctx/` vocabulary (`crate::flat::ctx`,
//! `master06-context_information.adoc`) supplies the composition context
//! and per-entry defaults. A final structural pass fills the RM-mandatory
//! fields the simplified form never surfaces, so the result deserialises
//! as an `openehr-rm` Composition.
//!
//! Unknown field identifiers are rejected, not ignored
//! (`master04 §Validation`: "Field identifiers match WT metadata
//! structure").

#![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::HashSet;
use std::sync::LazyLock;

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

use crate::flat::ctx;
use crate::flat::error::FlatError;
use crate::flat::identity::{
    default_name, name_value, recorded_archetype_id, stamp_archetype_details,
    stamp_locatable_identity,
};
use crate::flat::map;
use crate::flat::rmpath;
use crate::flat::sim::{SimDocument, SimNode};
use crate::flat::webtemplate::model::{
    CodedName, WebTemplate, WebTemplateNode, WebTemplateStructuralStub,
};

/// The RM release stamped into `ARCHETYPED.rm_version` when the caller names none.
///
/// RM common `master03-archetyped_package.adoc` §ARCHETYPED: the "version of the
/// openEHR reference model used to create this object"; this crate builds
/// against the pinned RM 1.2.0.
pub const RM_VERSION: &str = "1.2.0";

/// Deterministic fill for RM-mandatory temporal fields the simplified form
/// never surfaces as data (`HISTORY.origin` of a synthesised history,
/// `EVENT.time` with no derivable origin). Never present on the simplified
/// wire, so a fixed value keeps the round-trip stable — a fresh `now()`
/// here would make two successive flattenings disagree. (The `ctx/time`
/// `now()` default of `master04 §Context` applies to the EVENT_CONTEXT via
/// [`crate::flat::ctx`], not to these structural fills.)
pub(crate) const DEFAULT_TIME: &str = "1970-01-01T00:00:00Z";

/// What a caller chooses about a build beyond the document and the template.
///
/// [`BuildOptions::default`] is what [`build_composition`] uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BuildOptions<'a> {
    /// The value written verbatim into every `archetype_details.rm_version` the
    /// build stamps. Choosing the release the object conforms to is the
    /// caller's decision.
    pub rm_version: &'a str,
}

impl Default for BuildOptions<'_> {
    fn default() -> Self {
        Self {
            rm_version: RM_VERSION,
        }
    }
}

impl<'a> BuildOptions<'a> {
    /// The options with `rm_version` stamped into every `ARCHETYPED` the build
    /// writes.
    #[must_use]
    pub fn with_rm_version(mut self, rm_version: &'a str) -> Self {
        self.rm_version = rm_version;
        self
    }

    /// The options a build against `wt` uses when its caller names none: the
    /// RM release of an OPT2 (its `rm_release`, AOM2
    /// `master03-archetype_package.adoc`), else [`RM_VERSION`].
    #[must_use]
    pub fn for_template(wt: &'a WebTemplate) -> Self {
        Self::default().with_rm_version(wt.tree.rm_release.as_deref().unwrap_or(RM_VERSION))
    }
}

/// Converts a parsed simplified document to a canonical-JSON composition,
/// driven by `wt`, with [`BuildOptions::for_template`].
///
/// `now` is the caller's current timestamp, used only for the `ctx/time`
/// default (`master04 §Context`). A document that names no `category` takes
/// the template's default for it (`template_category`).
///
/// # Errors
///
/// As [`build_composition_with`].
pub fn build_composition(
    doc: &SimDocument,
    wt: &WebTemplate,
    now: &str,
) -> Result<Value, FlatError> {
    build_composition_with(doc, wt, now, &BuildOptions::for_template(wt))
}

/// Converts a parsed simplified document to a canonical-JSON composition,
/// driven by `wt`, with the caller's [`BuildOptions`].
///
/// `now` is the caller's current timestamp, used only for the `ctx/time`
/// default (`master04 §Context`). A document that names no `category` takes
/// the template's default for it (`template_category`).
///
/// # Errors
///
/// [`FlatError::UnknownPath`] for a field identifier matching no
/// web-template node; the `crate::flat::map`/`crate::flat::ctx` errors for datum
/// and context violations; [`FlatError::MissingRequiredSuffix`] naming
/// `<root>/category|code` when the document names no category and the
/// template admits several with no default; [`FlatError::Conversion`] when the
/// document carries nothing buildable.
pub fn build_composition_with(
    doc: &SimDocument,
    wt: &WebTemplate,
    now: &str,
    options: &BuildOptions<'_>,
) -> Result<Value, FlatError> {
    let root_id = &wt.tree.id;
    let mut data_root = None;
    let mut ctx_node = None;
    for (name, child) in &doc.children {
        match name.as_str() {
            "ctx" => ctx_node = child.occurrences.first(),
            n if n == root_id => data_root = child.occurrences.first(),
            other => return Err(FlatError::UnknownPath(other.to_owned())),
        }
    }
    if data_root.is_none() && ctx_node.is_none() {
        return Err(FlatError::Conversion(
            "empty simplified document: no data root and no ctx".to_owned(),
        ));
    }

    let empty = SimNode::default();
    let data_root = data_root.unwrap_or(&empty);
    // Root-level path spellings of the in-context composition attributes
    // (`<root>/language|code`, `<root>/composer|name`, …) are the path form
    // of the `ctx/` shortcuts (`master05 §COMPOSITION` rows); an explicit
    // `ctx/…` key wins.
    let merged_ctx = merge_root_ctx_spellings(ctx_node, data_root);
    let explicit_event_context = has_explicit_event_context(merged_ctx.as_ref());
    let mut defaults = ctx::resolve(merged_ctx.as_ref(), now)?;
    apply_root_raw(&mut defaults, data_root, root_id)?;

    // The template's hoisted-wrapper type narrowings (`ITEM_STRUCTURE`/`EVENT`
    // families the compactor folded away), keyed by absolute archetype path, so
    // the structural re-materialisation below stamps the *constrained* concrete
    // type (`ITEM_LIST`/`ITEM_SINGLE`/`INTERVAL_EVENT`) rather than the abstract
    // family default (AOM 1.4 type conformance; master04 §Level Removal — the
    // collapsed wrapper's type is not carried on the FLAT wire, so it is resolved
    // from the template here).
    let build_ctx = BuildCtx::new(wt, options);

    let mut comp = match build(&wt.tree, data_root, root_id, &build_ctx)? {
        Some(Value::Object(m)) => m,
        _ => Map::new(),
    };
    finish_identity(
        &mut comp,
        &wt.tree,
        true,
        &wt.template_id,
        options.rm_version,
    );
    ensure_template_id(&mut comp, &wt.tree, &wt.template_id, options.rm_version);
    // Resolve `category` BEFORE the context is applied: persistent
    // compositions may optionally omit the Event context (RM ehr master05
    // §"Persistent Compositions may optionally have an Event context").
    ensure_category(&mut comp, &wt.tree)?;
    apply_composition_ctx(&mut comp, &defaults, explicit_event_context);
    let mut value = Value::Object(comp);
    apply_entry_defaults(&mut value, &defaults);
    complete_tree(&mut value);
    Ok(value)
}

/// The concrete party classes a party build produces (RM demographic
/// `master02-demographic_package.adoc` §Class Descriptions: `PARTY` and its
/// descendants are the versioned demographic objects).
pub(crate) const PARTY_CLASSES: [&str; 5] = ["PERSON", "ORGANISATION", "GROUP", "AGENT", "ROLE"];

/// Converts a parsed simplified document of a party template (a `PERSON`,
/// `ORGANISATION`, `GROUP`, `AGENT` or `ROLE` root) to a canonical-JSON party.
///
/// The same template walk and level re-materialisation as
/// [`build_composition_with`], without the composition steps: no `category`, no
/// `ctx/` vocabulary and no entry defaults. Every list attribute of the
/// demographic package (`identities`, `contacts`, `addresses`, `capabilities`,
/// `roles`, `languages`, `relationships`) is built as an array, and the result
/// is checked to decode as the root's class before it is returned.
///
/// `ROLE.performer` (RM demographic §ROLE, `PARTY_REF`, 1..1) needs no template
/// node: `<root>/performer|id`, `|namespace`, `|type` and the optional
/// `|id_scheme` build it, or `<root>/performer|raw` takes a canonical-JSON
/// `PARTY_REF` whole (master04 §Raw canonical JSON).
///
/// NOTE: ITS-REST `simplified_formats/master04` defines FLAT for compositions only; a party build is our own extension over the same walk.
///
/// # Errors
///
/// [`FlatError::NotAPartyTemplate`] when the template root is not a party
/// class; [`FlatError::ContextOnParty`] for a `ctx/` key;
/// [`FlatError::UnknownPath`] for a field identifier matching no web-template
/// node; the datum errors of [`build_composition_with`];
/// [`FlatError::Conversion`] when the document carries no data root; and
/// [`FlatError::PartyDecode`] when the built object does not decode as the root
/// class (a mandatory attribute the document left empty, for example
/// `identities`).
pub fn build_party(
    doc: &SimDocument,
    wt: &WebTemplate,
    options: &BuildOptions<'_>,
) -> Result<Value, FlatError> {
    let class = concrete_type(&wt.tree.rm_type);
    if !PARTY_CLASSES.contains(&class) {
        return Err(FlatError::NotAPartyTemplate {
            root: wt.tree.rm_type.clone(),
        });
    }
    let value = build_root(doc, wt, options)?;
    check_party_decodes(&value, class)?;
    Ok(value)
}

/// Converts a parsed simplified document to an instance of the template's root class.
///
/// The root may be any class (an ENTRY, a SECTION, a CLUSTER, a party), and
/// the build skips the composition steps: no `category`, no `ctx/` vocabulary
/// and no entry defaults; a `ctx/` key is refused.
///
/// The composition builder is [`build_composition_with`] and the checked party
/// builder [`build_party`]; this is the walk both share for a root that is not
/// a COMPOSITION. The result is not decoded, so the caller owns the check that
/// it is an instance of its class.
///
/// NOTE: ITS-REST `simplified_formats/master04` defines FLAT for compositions only; a non-COMPOSITION root is our own extension over the same walk.
///
/// # Errors
///
/// [`FlatError::ContextOnParty`] for a `ctx/` key; [`FlatError::UnknownPath`]
/// for a field identifier matching no web-template node; the datum errors of
/// [`build_composition_with`]; and [`FlatError::Conversion`] when the document
/// carries no data root.
pub fn build_root(
    doc: &SimDocument,
    wt: &WebTemplate,
    options: &BuildOptions<'_>,
) -> Result<Value, FlatError> {
    let root_id = &wt.tree.id;
    let mut data_root = None;
    for (name, child) in &doc.children {
        match name.as_str() {
            "ctx" => return Err(FlatError::ContextOnParty),
            n if n == root_id => data_root = child.occurrences.first(),
            other => return Err(FlatError::UnknownPath(other.to_owned())),
        }
    }
    let Some(data_root) = data_root else {
        return Err(FlatError::Conversion(
            "empty simplified document: no data root".to_owned(),
        ));
    };
    let build_ctx = BuildCtx::new(wt, options);
    let mut root = match build(&wt.tree, data_root, root_id, &build_ctx)? {
        Some(Value::Object(m)) => m,
        _ => Map::new(),
    };
    finish_identity(
        &mut root,
        &wt.tree,
        true,
        &wt.template_id,
        options.rm_version,
    );
    ensure_template_id(&mut root, &wt.tree, &wt.template_id, options.rm_version);
    let mut value = Value::Object(root);
    complete_tree(&mut value);
    Ok(value)
}

/// Decodes `value` as the party class `class`, so a built party that the
/// generated RM types refuse is reported here and never handed on.
///
/// # Errors
///
/// [`FlatError::PartyDecode`] carrying the strict reader's refusal.
pub(crate) fn check_party_decodes(value: &Value, class: &str) -> Result<(), FlatError> {
    use openehr_its::json::from_canonical_value;
    use openehr_rm::v1_2::demographic;
    let decoded = match class {
        "PERSON" => from_canonical_value::<demographic::person::Person>(value).map(drop),
        "ORGANISATION" => {
            from_canonical_value::<demographic::organisation::Organisation>(value).map(drop)
        }
        "GROUP" => from_canonical_value::<demographic::group::Group>(value).map(drop),
        "AGENT" => from_canonical_value::<demographic::agent::Agent>(value).map(drop),
        _ => from_canonical_value::<demographic::role::Role>(value).map(drop),
    };
    decoded.map_err(|source| FlatError::PartyDecode {
        class: class.to_owned(),
        source,
    })
}

/// Merge the root-level path spellings of the in-context composition
/// attributes into the `ctx` tree (`master05 §COMPOSITION` rows spell the
/// same data as paths; `master06` gives the `ctx/` shortcut). An explicit
/// `ctx/…` key always wins; the path spellings only fill gaps.
///
/// The event-context spellings of `master05 §EVENT_CONTEXT` merge the same
/// way: `/context/start_time` feeds `ctx/time`, `/context/_end_time` feeds
/// `ctx/end_time`, `/context/_location` feeds `ctx/location` and
/// `/context/setting|code` (else `|value`) feeds `ctx/setting` (master06
/// §§time, end_time, location, setting), so the defaults hung off the context
/// time (`OBSERVATION.history.origin`, `EVENT.time`, `ACTION.time`) do not
/// depend on which spelling the client chose.
fn merge_root_ctx_spellings(ctx_node: Option<&SimNode>, data_root: &SimNode) -> Option<SimNode> {
    let mut merged = ctx_node.cloned().unwrap_or_default();
    let mut fill = |key: &str, value: Option<&Value>| {
        if let Some(v) = value
            && !merged.children.contains_key(key)
        {
            merged
                .occurrence_mut(key, None)
                .attrs
                .insert(String::new(), v.clone());
        }
    };
    let attr = |name: &str, suffix: &str| data_root.child(name).and_then(|n| n.attrs.get(suffix));
    fill("language", attr("language", "code"));
    fill("territory", attr("territory", "code"));
    fill("composer_name", attr("composer", "name"));
    fill("composer_id", attr("composer", "id"));
    fill("id_namespace", attr("composer", "id_namespace"));
    fill("id_scheme", attr("composer", "id_scheme"));
    let context = data_root.child("context");
    let context_attr = |name: &str, suffix: &str| {
        context
            .and_then(|c| c.child(name))
            .and_then(|n| n.attrs.get(suffix))
    };
    fill("time", context_attr("start_time", ""));
    fill("end_time", context_attr("_end_time", ""));
    fill("location", context_attr("_location", ""));
    fill(
        "setting",
        context_attr("setting", "code").or_else(|| context_attr("setting", "value")),
    );
    if merged.is_empty() {
        None
    } else {
        Some(merged)
    }
}

/// Takes the COMPOSITION `language`, `territory` and `composer` a client
/// sends whole as canonical JSON (`<root>/language|raw`, …; master04 §Raw
/// canonical JSON) into the resolved context, where a `ctx/` key or a
/// suffix spelling of the same attribute has not already set it.
///
/// # Errors
/// [`FlatError::RawWithoutType`] for a `|raw` value without `_type`;
/// [`FlatError::InvalidRaw`] for one whose `_type` is not the attribute's RM type (`CODE_PHRASE`, or a `PARTY_PROXY`
/// subtype for `composer`; RM ehr §COMPOSITION), or one beside other content.
fn apply_root_raw(
    defaults: &mut ctx::CtxDefaults,
    data_root: &SimNode,
    root_id: &str,
) -> Result<(), FlatError> {
    let raw = |seg: &str, types: &[&str]| {
        data_root
            .child(seg)
            .and_then(|node| map::raw_value(node, &format!("{root_id}/{seg}"), types))
            .transpose()
    };
    if let Some(phrase) = raw("language", &["CODE_PHRASE"])?
        && defaults.language.is_none()
    {
        defaults.language_phrase = Some(phrase);
    }
    if let Some(phrase) = raw("territory", &["CODE_PHRASE"])?
        && defaults.territory.is_none()
    {
        defaults.territory_phrase = Some(phrase);
    }
    if let Some(composer) = raw("composer", map::PARTY_PROXY_CLASSES)?
        && defaults.composer.is_none()
    {
        defaults.composer = Some(composer);
    }
    Ok(())
}

/// Whether the client supplied any explicit EVENT_CONTEXT content — a
/// persistent composition only carries a context when it did (RM ehr
/// master05 §"Persistent Compositions may optionally have an Event
/// context").
fn has_explicit_event_context(ctx_node: Option<&SimNode>) -> bool {
    let Some(ctx) = ctx_node else { return false };
    ctx.children.keys().any(|key| {
        matches!(
            key.as_str(),
            "time" | "end_time" | "setting" | "location" | "health_care_facility"
        ) || key.starts_with("participation_")
    })
}

/// The `|raw` bypass on a container node: the payload must be a
/// canonical-JSON RM object carrying `_type`
/// (`master04 §Raw canonical JSON`).
fn build_raw(raw: &Value, path: &str) -> Result<Value, FlatError> {
    if raw.get("_type").and_then(Value::as_str).is_none() {
        return Err(FlatError::RawWithoutType {
            path: path.to_owned(),
        });
    }
    Ok(raw.clone())
}

// ── the template walk ──────────────────────────────────────────────────────

/// Segment names of the ELEMENT-level `_` RM attribute family — attributes
/// of the wrapping ELEMENT, not of the DATA_VALUE itself
/// (`master05 §ELEMENT`).
fn is_element_level(seg: &str) -> bool {
    matches!(
        seg,
        "_uid" | "_null_flavour" | "_null_reason" | "_link" | "_feeder_audit"
    )
}

/// Whether the leaf builder ([`map::build_leaf`]) already consumed the
/// `_`-prefixed segment `seg` on a leaf of RM type `base`, so the generic
/// `_`-family routing ([`apply_rm_attr`]) must not see it a second time.
///
/// Both cases are on a PARTY_PROXY leaf, and both are consumed by
/// `map::parties::build_party` — the build-side mirror of the emit side's "one
/// family, one emission site" rule (`map::structures::emit_rm_attrs` carries no
/// PARTY arm for the same reason).
///
/// `/_relationship`: master05 §PARTY_RELATED spells the relationship sub-path
/// `/_relationship` in its mapping table and `…/relationship|code` in both of
/// the section's example blocks (and in the §"PARTY_RELATED performer" table);
/// the flat builder accepts both, and `build_party` reads whichever is present
/// as the PARTY_PROXY **subtype discriminator**. Routing it on to
/// [`map::build_rm_attr`] as well would either reject the spec's own table
/// spelling as an unknown suffix, or — with a generic `relationship` arm there
/// — attach the attribute to a party the leaf builder has already typed
/// PARTY_IDENTIFIED.
///
/// `/_identifier:i`: master05 §§PARTY_IDENTIFIED, PARTY_RELATED put the family
/// on the party itself, and `build_party` already reads it into `identifiers`.
/// `build_rm_attr`'s generic `identifier` arm would then overwrite the key with
/// its own build of the same children — idempotent for any input the parsers
/// can produce, but NOT identical at the empty edge, where the generic arm
/// inserts `identifiers: []` over the key `build_party` deliberately omits. An
/// empty list there is doubly wrong: RM `PARTY_IDENTIFIED` invariant
/// `Identifiers_valid` ("identifiers /= Void implies not identifiers.is_empty")
/// forbids the value, and ITS-REST Resources.md §JSON Format keeps an empty
/// list off the wire ("The RM attributes (even required ones) that are `Null`
/// or an empty list (array) SHOULD be absent when serialized as JSON"). One
/// family, one consumption site.
fn leaf_consumes_segment(base: &str, seg: &str) -> bool {
    matches!(
        seg,
        map::parties::RELATIONSHIP_TABLE_SEGMENT | map::parties::IDENTIFIER_SEGMENT
    ) && matches!(
        base,
        "PARTY_PROXY" | "PARTY_SELF" | "PARTY_IDENTIFIED" | "PARTY_RELATED"
    )
}

/// One hoisted wrapper of the template: its parsed absolute archetype path,
/// its constrained RM type and the name its term definition gives.
struct SlotType {
    /// The parsed absolute archetype path of the wrapper.
    path: Vec<PathSegment>,
    /// The constrained RM type.
    rm_type: String,
    /// The wrapper's name from the template, when it has one.
    name: Option<String>,
}

/// What one build carries down the template walk: the template's hoisted
/// wrappers and the `ARCHETYPED.rm_version` every archetype root is stamped
/// with.
struct BuildCtx<'a> {
    /// The hoisted wrappers, looked up by absolute path.
    slots: Vec<SlotType>,
    /// The value written into every `archetype_details.rm_version`.
    rm_version: &'a str,
}

impl<'a> BuildCtx<'a> {
    /// The context for building against `wt` with `options`.
    fn new(wt: &WebTemplate, options: &BuildOptions<'a>) -> Self {
        let mut slots = Vec::new();
        collect_slot_types(&wt.tree, &mut slots);
        Self {
            slots,
            rm_version: options.rm_version,
        }
    }
}

/// Collect the whole template's hoisted-wrapper type narrowings and names, so
/// the builder can look a re-materialised structural node's constrained type
/// and name up by its absolute path (see [`build_composition`]).
fn collect_slot_types(node: &WebTemplateNode, out: &mut Vec<SlotType>) {
    for slot in &node.slots {
        out.push(SlotType {
            path: rmpath::parse(&slot.path),
            rm_type: slot.rm_type.clone(),
            name: slot.name.clone(),
        });
    }
    for child in &node.children {
        collect_slot_types(child, out);
    }
}

/// Whether two archetype-path segment slices name the same path (attribute +
/// archetype node id per step; the runtime `name` conjunct is ignored — the
/// wrapper identity is its node id).
fn segments_match(a: &[PathSegment], b: &[PathSegment]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|(x, y)| {
            x.attribute == y.attribute
                && x.predicate.archetype_node_id == y.predicate.archetype_node_id
        })
}

/// The template's record of one structural wrapper on a placement path: its
/// constrained concrete RM type and its name.
#[derive(Clone, Default)]
struct WrapperFacts {
    /// The constrained RM type, `None` when the template records no narrowing
    /// (the caller then falls back to [`infer_type`]).
    rm_type: Option<String>,
    /// The name the template gives the wrapper, `None` when it gives none.
    name: Option<String>,
}

/// Resolve, per relative segment of `child`, what the template records about
/// the structural wrapper at that absolute path. Index-aligned with the
/// relative segment list.
fn wrapper_types(child_aql: &str, rel_len: usize, slots: &[SlotType]) -> Vec<WrapperFacts> {
    let child_abs = rmpath::parse(child_aql);
    if child_abs.len() < rel_len {
        return vec![WrapperFacts::default(); rel_len];
    }
    let base = child_abs.len() - rel_len;
    (0..rel_len)
        .map(|i| {
            child_abs
                .get(..=base + i)
                .and_then(|abs| slots.iter().find(|slot| segments_match(&slot.path, abs)))
                .map(|slot| WrapperFacts {
                    rm_type: Some(slot.rm_type.clone()),
                    name: slot.name.clone(),
                })
                .unwrap_or_default()
        })
        .collect()
}

/// Build the RM value for `node` from the simplified occurrence `sim`.
/// `path` is the printed simplified path (diagnostics); `ctx` carries the
/// template's hoisted-wrapper map and the `rm_version` to stamp.
///
/// `Ok(None)` means the occurrence builds **no value**: a leaf that carries no
/// datum part, only the `/_null_flavour` (+ `/_null_reason`) rows of master05
/// §ELEMENT. RM data_structures §ELEMENT (`Inv_null_flavour_indicated`) makes
/// `value` and `null_flavour` mutually exclusive, so the wrapping ELEMENT is
/// still materialised — carrying the null flavour and no `value`.
fn build(
    node: &WebTemplateNode,
    sim: &SimNode,
    path: &str,
    ctx: &BuildCtx<'_>,
) -> Result<Option<Value>, FlatError> {
    if node.has_input() {
        return build_leaf(node, sim, path);
    }
    let interval;
    let node = if is_interval_input(node, sim) {
        interval = WebTemplateNode {
            rm_type: "INTERVAL_EVENT".to_owned(),
            ..node.clone()
        };
        &interval
    } else {
        node
    };

    let mut obj = Map::new();
    obj.insert("_type".into(), json!(concrete_type(&node.rm_type)));
    // `OBSERVATION/history_origin` (master05 §OBSERVATION `/history_origin`) is
    // an alias for `data.origin`; captured here and applied after the mandatory
    // HISTORY is materialised (see below).
    let mut history_origin: Option<String> = None;

    walk_template_children(node, sim, path, ctx, &mut obj)?;
    apply_container_attrs(node, sim, path, &mut obj, &mut history_origin)?;
    // Datum parts on a container node are only legal via |raw
    // (master04 §Raw canonical JSON) or as one of the few datum suffixes the
    // master05 per-type tables place on a container; anything else is an
    // unknown suffix.
    if let Some(raw) = sim.attrs.get("raw") {
        return build_raw(raw, path).map(Some);
    }
    apply_container_datum_attrs(node, sim, path, &mut obj)?;

    let mut value = Value::Object(obj);
    if let Value::Object(m) = &mut value {
        finish_identity(m, node, false, "", ctx.rm_version);
        // `OBSERVATION/history_origin` sets `data.origin` (master05 §OBSERVATION
        // `/history_origin`), applied after the mandatory HISTORY is
        // materialised so the datum-supplied origin wins the structural default.
        if let Some(ts) = &history_origin
            && let Some(Value::Object(hist)) = m.get_mut("data")
        {
            hist.insert("origin".to_owned(), dv_date_time(ts));
        }
        apply_interval_flags(m, &node.rm_type);
    }
    Ok(Some(value))
}

/// Builds the DATA_VALUE of an input-carrying (leaf) node.
///
/// `Ok(None)` is the value-less ELEMENT of [`is_null_flavoured`]. Value-level
/// `_` attributes (`_normal_range`, `_mapping`, `_accuracy`, `_language`, …)
/// attach to the DV value itself; ELEMENT-level ones are routed onto the
/// wrapping ELEMENT by [`place`] (master05 per-type tables vs §ELEMENT), and
/// the few the leaf builder itself consumed are skipped
/// ([`leaf_consumes_segment`]).
///
/// # Errors
/// [`FlatError`] from the leaf build or an unusable RM attribute.
fn build_leaf(
    node: &WebTemplateNode,
    sim: &SimNode,
    path: &str,
) -> Result<Option<Value>, FlatError> {
    if is_null_flavoured(sim) {
        return Ok(None);
    }
    let base = base_type(&node.rm_type);
    let mut dv = map::build_leaf(sim, base, Some(node), path)?;
    if let Value::Object(m) = &mut dv {
        for (seg, child) in &sim.children {
            if seg.starts_with('_') && !is_element_level(seg) && !leaf_consumes_segment(base, seg) {
                apply_rm_attr(m, seg, &child.occurrences, base, path)?;
            }
        }
    }
    Ok(Some(dv))
}

/// Builds every template child the walk covers into `obj`.
///
/// # Errors
/// [`FlatError`] from a child's own build or its placement.
fn walk_template_children(
    node: &WebTemplateNode,
    sim: &SimNode,
    path: &str,
    ctx: &BuildCtx<'_>,
    obj: &mut Map<String, Value>,
) -> Result<(), FlatError> {
    for child in &node.children {
        if !child_is_walked(node, child) {
            continue;
        }
        let Some(sim_child) = sim.children.get(&child.id).or_else(|| {
            child
                .alt_json_id
                .as_deref()
                .and_then(|a| sim.children.get(a))
        }) else {
            continue;
        };
        let rel = rmpath::relative(&node.aql_path, &child.aql_path);
        for (i, occ) in sim_child.occurrences.iter().enumerate() {
            if occ.is_empty() {
                continue; // a preserved index hole
            }
            let child_path = format!("{path}/{}:{i}", child.id);
            let child_val = build(child, occ, &child_path, ctx)?;
            place(obj, &rel, child_val, child, occ, &child_path, ctx)?;
        }
    }
    Ok(())
}

/// Applies the datum segments addressed to a container node itself.
///
/// Only a template child the walk ACTUALLY processes counts as handled: a
/// child the in-context routing skipped ([`child_is_walked`]) must fall
/// through to the direct-RM-path fallback, or its datum would be neither
/// honoured nor rejected — the one outcome master04 §Validation forbids. The
/// fallback covers a direct RM-attribute path the master05 per-type mapping
/// tables declare addressable on this node even when the OPT leaves it
/// unconstrained (so the compacted web template carries no child for it) —
/// e.g. `ACTION/time`, `ACTION/ism_transition` (master05 §§ACTION,
/// ISM_TRANSITION).
///
/// # Errors
/// [`FlatError::UnknownPath`] when an identifier matches no template child and
/// no spec-listed RM path (master04 §Validation: field identifiers match WT
/// metadata structure), plus the RM-attribute rejections.
fn apply_container_attrs(
    node: &WebTemplateNode,
    sim: &SimNode,
    path: &str,
    obj: &mut Map<String, Value>,
    history_origin: &mut Option<String>,
) -> Result<(), FlatError> {
    for (seg, child) in &sim.children {
        if seg.starts_with('_') {
            apply_rm_attr(obj, seg, &child.occurrences, base_type(&node.rm_type), path)?;
            continue;
        }
        let known = node.children.iter().any(|c| {
            (c.id == *seg || c.alt_json_id.as_deref() == Some(seg)) && child_is_walked(node, c)
        });
        let ctx_covered = node.rm_type == "COMPOSITION"
            && matches!(
                seg.as_str(),
                "language" | "territory" | "composer" | "category"
            );
        if known || ctx_covered {
            continue;
        }
        if place_direct_rm_path(
            obj,
            &node.rm_type,
            seg,
            &child.occurrences,
            path,
            history_origin,
        )? {
            continue;
        }
        return Err(FlatError::UnknownPath(format!("{path}/{seg}")));
    }
    Ok(())
}

/// Whether a leaf occurrence expresses a **value-less** ELEMENT: no datum part
/// of its own, and a `/_null_flavour` family (master05 §ELEMENT). RM
/// data_structures §ELEMENT `Inv_null_flavour_indicated` makes `value` and
/// `null_flavour` mutually exclusive, so this is the only shape in which a
/// null flavour can legitimately reach the builder.
fn is_null_flavoured(sim: &SimNode) -> bool {
    sim.attrs.is_empty()
        && sim
            .children
            .get("_null_flavour")
            .is_some_and(|c| c.occurrences.iter().any(|o| !o.is_empty()))
}

/// Whether the template-child walk builds `child` from its own sim sub-tree.
///
/// Four in-context families are routed elsewhere and are therefore NOT walked:
///
/// * **EVENT_CONTEXT** standard fields (everything but archetyped
///   `other_context` content) — `start_time`/`setting` come from the `ctx/`
///   vocabulary (master06 §§time, setting) via `apply_composition_ctx`, and
///   their master05 §EVENT_CONTEXT PATH spellings are honoured by
///   [`direct_rm_path`].
/// * **COMPOSITION** `language`/`territory`/`composer` — resolved through
///   `ctx::resolve`, which reads their path spellings too
///   (`merge_root_ctx_spellings`). The `context` child itself IS walked: its
///   archetyped `other_context` content and `_`-attribute families
///   (`_health_care_facility`, `_participation:i`, `_end_time`, `_location` —
///   master05 §EVENT_CONTEXT) are tree data, and `category` is real tree data
///   (master05 §COMPOSITION).
/// * **ENTRY** `language`/`encoding` — defaulted from the composition context
///   (master06 §"Language and Territory") by `apply_entry_defaults`; the
///   master05 ENTRY-table `/language` path spelling is honoured by
///   [`direct_rm_path`]. `subject` is NOT in this set — a non-`PARTY_SELF`
///   subject is real data (master05 §OBSERVATION `/subject`) and builds as a
///   PARTY_PROXY leaf.
/// * **ACTIVITY** `action_archetype_id` — a String attribute (master05
///   §ACTIVITY), set by [`direct_rm_path`] from the bare value.
///
/// A skipped child's identifier must never be treated as "already handled" by
/// the datum loop: every non-walked spelling either reaches [`direct_rm_path`]
/// or is rejected as an unknown path (master04 §Validation).
fn child_is_walked(node: &WebTemplateNode, child: &WebTemplateNode) -> bool {
    if node.rm_type == "EVENT_CONTEXT" && !child.aql_path.contains("other_context") {
        return false;
    }
    if node.rm_type == "COMPOSITION"
        && matches!(child.id.as_str(), "language" | "territory" | "composer")
    {
        return false;
    }
    if is_entry_family(&node.rm_type) && matches!(child.id.as_str(), "language" | "encoding") {
        return false;
    }
    if node.rm_type == "ACTIVITY" && child.id == "action_archetype_id" {
        return false;
    }
    true
}

/// An interval assembled from bound CHILDREN (a WT tree whose
/// `lower`/`upper` are their own nodes — vs the leaf form
/// `map::build_interval` covers) must still carry the four boundary flags:
/// BASE foundation_types Interval declares them mandatory, and a half-open
/// instance without `*_unbounded: true` violates Limits_consistent
/// (`(not upper_unbounded and not lower_unbounded) implies lower <= upper`
/// — unevaluable against an absent bound). Derived from bound presence; an
/// explicit datum flag wins.
fn apply_interval_flags(m: &mut Map<String, Value>, rm_type: &str) {
    if base_type(rm_type) != "DV_INTERVAL" {
        return;
    }
    let has_lower = m.contains_key("lower");
    let has_upper = m.contains_key("upper");
    m.entry("lower_unbounded").or_insert(json!(!has_lower));
    m.entry("upper_unbounded").or_insert(json!(!has_upper));
    m.entry("lower_included").or_insert(json!(has_lower));
    m.entry("upper_included").or_insert(json!(has_upper));
}

/// A direct RM-attribute path (non-`_`, non-`|`) that the master05 per-type
/// mapping tables declare addressable on a node of `host` even when the OPT
/// leaves it unconstrained — so the compacted web-template carries no child
/// for it and the datum-driven walk must build it here
/// (`master05-rm_mapping.adoc`).
enum DirectPath {
    /// A single `DATA_VALUE` leaf attribute of the named RM type.
    Leaf {
        /// The RM attribute name the value is inserted under.
        attr: &'static str,
        /// The concrete leaf RM type to build.
        rm_type: &'static str,
    },
    /// `ACTION.ism_transition` — the ISM_TRANSITION object built from its
    /// `current_state`/`transition`/`careflow_step` + `_reason:i` sub-tree
    /// (master05 §ISM_TRANSITION).
    Ism,
    /// A `DV_CODED_TEXT` attribute whose master05 row binds it to an openEHR
    /// terminology group in its Note column, so a bare `|code` resolves its
    /// rubric from the bundle instead of standing as a `local` code.
    CodedGroup {
        /// The RM attribute name the value is inserted under.
        attr: &'static str,
        /// The openEHR terminology group id the row's ValueSet names.
        group: &'static str,
    },
    /// `ACTIVITY.action_archetype_id` — a plain-String RM field
    /// (master05 §ACTIVITY).
    ActionArchetypeId,
    /// `OBSERVATION.history_origin` — the alias for `data.origin`
    /// (master05 §OBSERVATION `/history_origin`).
    HistoryOrigin,
    /// `ROLE.performer` — the `PARTY_REF` to the actor playing the role (RM
    /// demographic §ROLE), built from the master05 §OBJECT_REF suffixes.
    Performer,
}

/// The direct RM-attribute path (if any) named by `seg` on a node of base RM
/// type `host`, per the master05 per-type mapping tables.
fn direct_rm_path(host: &str, seg: &str) -> Option<DirectPath> {
    use DirectPath::{ActionArchetypeId, CodedGroup, HistoryOrigin, Ism, Leaf, Performer};
    Some(match (host, seg) {
        // master05 §§ADMIN_ENTRY, INSTRUCTION, ACTION, EVALUATION, OBSERVATION
        // `/language` (CODE_PHRASE → `language`). Output takes the master06
        // §"Language and Territory" `ctx/language` route, so the template child
        // is not walked ([`child_is_walked`]) — the table's PATH spelling is
        // honoured here instead of being ignored.
        (_, "language") if is_entry_family(host) => Leaf {
            attr: "language",
            rm_type: "CODE_PHRASE",
        },
        // `/encoding` has no row of its own in any ENTRY table (an editorial
        // hole — RM ehr §ENTRY declares `encoding` 1..1), but the master05
        // §COMPOSITION example block spells
        // `…/conformance_observation/encoding|code`, so the same path form is
        // accepted for it.
        (_, "encoding") if is_entry_family(host) => Leaf {
            attr: "encoding",
            rm_type: "CODE_PHRASE",
        },
        // master05 §§ACTION, POINT_EVENT, INTERVAL_EVENT: `/time` (DV_DATE_TIME)
        // is addressable on the ACTION and on every EVENT concrete type.
        ("ACTION" | "POINT_EVENT" | "INTERVAL_EVENT" | "EVENT", "time") => Leaf {
            attr: "time",
            rm_type: "DV_DATE_TIME",
        },
        // master05 §ACTION: `/ism_transition`. Reached when the template
        // constrains no transition at all; a constrained one is a merged web
        // template child and its sub-paths take the three rows below.
        ("ACTION", "ism_transition") => Ism,
        // master05 §ISM_TRANSITION: `/current_state`, `/transition`,
        // `/careflow_step`. `current_state` and `transition` name an openEHR
        // terminology group in their RM invariants (RM
        // `UML/classes/org.openehr.rm.composition.ism_transition.adoc`
        // §Invariants), so a bare `|code` resolves its rubric there.
        ("ISM_TRANSITION", "current_state") => CodedGroup {
            attr: "current_state",
            group: "instruction_states",
        },
        ("ISM_TRANSITION", "transition") => CodedGroup {
            attr: "transition",
            group: "instruction_transitions",
        },
        ("ISM_TRANSITION", "careflow_step") => Leaf {
            attr: "careflow_step",
            rm_type: "DV_CODED_TEXT",
        },
        // master05 §INSTRUCTION: `/narrative` (DV_TEXT).
        ("INSTRUCTION", "narrative") => Leaf {
            attr: "narrative",
            rm_type: "DV_TEXT",
        },
        // master05 §OBSERVATION: `/history_origin` → `history.origin`.
        ("OBSERVATION", "history_origin") => HistoryOrigin,
        // master05 §ACTIVITY: `/timing` (DV_PARSABLE), `/action_archetype_id`.
        ("ACTIVITY", "timing") => Leaf {
            attr: "timing",
            rm_type: "DV_PARSABLE",
        },
        ("ACTIVITY", "action_archetype_id") => ActionArchetypeId,
        // master05 §INTERVAL_EVENT: `/width` (DV_DURATION), `/math_function`.
        ("INTERVAL_EVENT", "width") => Leaf {
            attr: "width",
            rm_type: "DV_DURATION",
        },
        ("INTERVAL_EVENT", "math_function") => Leaf {
            attr: "math_function",
            rm_type: "DV_CODED_TEXT",
        },
        // master05 §EVENT_CONTEXT: `/start_time` (DV_DATE_TIME) and `/setting`
        // (DV_CODED_TEXT, Note column "ValueSet (openEHR `setting` group)").
        // Output takes the master06 §§time, setting `ctx/` route, so neither
        // template child is walked ([`child_is_walked`]) — the table's PATH
        // spellings are honoured here instead of being ignored.
        ("EVENT_CONTEXT", "start_time") => Leaf {
            attr: "start_time",
            rm_type: "DV_DATE_TIME",
        },
        ("EVENT_CONTEXT", "setting") => CodedGroup {
            attr: "setting",
            group: "setting",
        },
        // RM demographic §ROLE: `performer: PARTY_REF` (1..1). A party template
        // rarely constrains it, so its path is honoured here.
        // NOTE: Simplified Formats define no party rows; the master05 §OBJECT_REF suffixes reused here are our own extension.
        ("ROLE", "performer") => Performer,
        _ => return None,
    })
}

/// The RM attribute a datum suffix (`|suffix`) sets when the master05 per-type
/// tables place it on a **container** node rather than on a `DATA_VALUE` leaf.
///
/// `master05 §INTERVAL_EVENT`: `|sample_count` (INTEGER → `sample_count`, the
/// count of samples the interval summarises) is spelled directly on the event
/// node — the section's second example block is
/// `…/any_event:0|sample_count: 5`, not a sub-path. The mirror of
/// [`crate::flat::flatten`]'s INTERVAL_EVENT emission.
/// Apply the master05 container-level datum suffixes (`|sample_count`, …) to a
/// container node under construction, rejecting any suffix the per-type tables
/// do not place on this container ([`container_datum_attr`]).
fn apply_container_datum_attrs(
    node: &WebTemplateNode,
    sim: &SimNode,
    path: &str,
    obj: &mut Map<String, Value>,
) -> Result<(), FlatError> {
    let host = base_type(&node.rm_type);
    for (chain, datum) in &sim.attrs {
        if let Some(attr) = container_datum_attr(host, chain) {
            obj.insert(attr.to_owned(), datum.clone());
        }
    }
    if let Some((chain, _)) = sim
        .attrs
        .iter()
        .find(|(c, _)| !c.is_empty() && container_datum_attr(host, c.as_str()).is_none())
    {
        return Err(FlatError::UnknownSuffix {
            rm_type: node.rm_type.clone(),
            suffix: chain.clone(),
            path: path.to_owned(),
        });
    }
    Ok(())
}

fn container_datum_attr(host: &str, suffix: &str) -> Option<&'static str> {
    match (host, suffix) {
        ("INTERVAL_EVENT", "sample_count") => Some("sample_count"),
        // master05 §DV_INTERVAL: the four BOOLEAN flags sit on the interval
        // itself when the template gives its bounds their own nodes.
        ("DV_INTERVAL", "lower_unbounded") => Some("lower_unbounded"),
        ("DV_INTERVAL", "upper_unbounded") => Some("upper_unbounded"),
        ("DV_INTERVAL", "lower_included") => Some("lower_included"),
        ("DV_INTERVAL", "upper_included") => Some("upper_included"),
        _ => None,
    }
}

/// Build and place a direct RM-attribute path onto `obj` (see [`direct_rm_path`]).
/// Returns `true` when `seg` was a recognised direct RM path (built or captured),
/// `false` when it is not — the caller then rejects it as an unknown path.
///
/// The direct fallback NEVER clobbers a value the template-child walk already
/// produced (`entry().or_insert`): when the web template realizes the RM
/// attribute — possibly under a node-id-specialized child whose id is not the
/// attribute name, e.g. the CKM careflow-state `ism_transition[at0109,…]` —
/// that WT-child realization (which carries the constrained node identity/name)
/// wins entirely; the direct path only fills an attribute the template left
/// unmodeled (master05 per-type mapping tables).
fn place_direct_rm_path(
    obj: &mut Map<String, Value>,
    host_rm_type: &str,
    seg: &str,
    occurrences: &[SimNode],
    path: &str,
    history_origin: &mut Option<String>,
) -> Result<bool, FlatError> {
    let Some(dp) = direct_rm_path(base_type(host_rm_type), seg) else {
        return Ok(false);
    };
    let occ = occurrences.iter().find(|o| !o.is_empty());
    let sub_path = format!("{path}/{seg}");
    match dp {
        DirectPath::Leaf { attr, rm_type } => {
            if let Some(node) = occ
                && !obj.contains_key(attr)
            {
                let value = map::build_leaf(node, rm_type, None, &sub_path)?;
                obj.insert(attr.to_owned(), value);
            }
        }
        DirectPath::CodedGroup { attr, group } => {
            if let Some(node) = occ
                && !obj.contains_key(attr)
            {
                let value = coded_group_value(node, group, &sub_path)?;
                obj.insert(attr.to_owned(), value);
            }
        }
        DirectPath::Ism => {
            if let Some(node) = occ
                && !obj.contains_key("ism_transition")
            {
                let value = build_ism_transition(node, &sub_path)?;
                obj.insert("ism_transition".to_owned(), value);
            }
        }
        DirectPath::ActionArchetypeId => {
            if let Some(v) = occ.and_then(SimNode::bare) {
                obj.entry("action_archetype_id".to_owned())
                    .or_insert_with(|| v.clone());
            }
        }
        DirectPath::HistoryOrigin => {
            *history_origin = occ
                .and_then(SimNode::bare)
                .and_then(Value::as_str)
                .map(str::to_owned);
        }
        DirectPath::Performer => {
            if let Some(node) = occ
                && !obj.contains_key("performer")
            {
                obj.insert("performer".to_owned(), build_party_ref(node, &sub_path)?);
            }
        }
    }
    Ok(true)
}

/// Builds a `PARTY_REF` from the master05 §OBJECT_REF suffixes `|id`,
/// `|namespace`, `|type` and the optional `|id_scheme`, or takes it whole
/// from `|raw` (master04 §Raw canonical JSON).
///
/// All of `id`, `namespace` and `type` are mandatory on an `OBJECT_REF` (BASE
/// `base_types/master05-identification_package.adoc` §References), and a reference
/// to a real actor has no sensible default for any of them, so each is required.
/// A `|id_scheme` makes the id a `GENERIC_ID`; without one it is the
/// `HIER_OBJECT_ID` a versioned party carries.
///
/// # Errors
/// [`FlatError::MissingRequiredSuffix`] naming the first absent suffix,
/// [`FlatError::UnknownSuffix`] for any other suffix, and
/// [`FlatError::RawWithoutType`] or [`FlatError::InvalidRaw`] for a `|raw`
/// value that is no lone `PARTY_REF`.
fn build_party_ref(node: &SimNode, path: &str) -> Result<Value, FlatError> {
    if let Some(raw) = map::raw_value(node, path, &["PARTY_REF"]) {
        return raw;
    }
    if let Some(suffix) = node
        .attrs
        .keys()
        .find(|k| !matches!(k.as_str(), "id" | "namespace" | "type" | "id_scheme"))
    {
        return Err(FlatError::UnknownSuffix {
            rm_type: "PARTY_REF".to_owned(),
            suffix: suffix.clone(),
            path: path.to_owned(),
        });
    }
    let required = |suffix: &str| {
        node.attrs
            .get(suffix)
            .and_then(Value::as_str)
            .ok_or_else(|| FlatError::MissingRequiredSuffix {
                key: format!("{path}|{suffix}"),
            })
    };
    let id = required("id")?;
    let namespace = required("namespace")?;
    let party_type = required("type")?;
    let id_obj = match node.attrs.get("id_scheme").and_then(Value::as_str) {
        Some(scheme) => json!({"_type": "GENERIC_ID", "value": id, "scheme": scheme}),
        None => json!({"_type": "HIER_OBJECT_ID", "value": id}),
    };
    Ok(json!({
        "_type": "PARTY_REF",
        "namespace": namespace,
        "type": party_type,
        "id": id_obj,
    }))
}

/// The DV_CODED_TEXT of a direct RM path bound to an openEHR terminology
/// group.
///
/// A bare `|code` binds to the row's group, resolving its rubric exactly as
/// the equivalent `ctx/` shortcut does (master06 §setting: "either value or
/// code is accepted"). Once the client spells out `|value` or `|terminology`,
/// the datum parts stand as given (master05 §DV_CODED_TEXT).
///
/// # Errors
/// [`FlatError`] from the leaf build.
fn coded_group_value(node: &SimNode, group: &str, sub_path: &str) -> Result<Value, FlatError> {
    let bound = node
        .attrs
        .get("code")
        .and_then(Value::as_str)
        .filter(|_| !node.attrs.contains_key("value") && !node.attrs.contains_key("terminology"))
        .map(|code| map::coded_from_group(group, code));
    match bound {
        Some(v) => Ok(v),
        None => map::build_leaf(node, "DV_CODED_TEXT", None, sub_path),
    }
}

/// Build an `ACTION.ism_transition` (ISM_TRANSITION) from its simplified
/// sub-tree: `/current_state` (DV_CODED_TEXT, required), `/transition`,
/// `/careflow_step` (DV_CODED_TEXT), and the `/_reason:i` DV_TEXT list
/// (master05 §ISM_TRANSITION). `current_state` is 1..1 DV_CODED_TEXT, the other
/// two 0..1 DV_CODED_TEXT (RM ehr `ism_transition.adoc`).
fn build_ism_transition(node: &SimNode, path: &str) -> Result<Value, FlatError> {
    let mut o = Map::new();
    o.insert("_type".into(), json!("ISM_TRANSITION"));
    for (seg, group) in [
        ("current_state", Some("instruction_states")),
        ("transition", Some("instruction_transitions")),
        ("careflow_step", None),
    ] {
        if let Some(cs) = node.child(seg).filter(|n| !n.is_empty()) {
            o.insert(
                seg.to_owned(),
                build_ism_coded(cs, group, &format!("{path}/{seg}"))?,
            );
        }
    }
    for (seg, child) in &node.children {
        if seg.starts_with('_') {
            apply_rm_attr(&mut o, seg, &child.occurrences, "ISM_TRANSITION", path)?;
        } else if !matches!(
            seg.as_str(),
            "current_state" | "transition" | "careflow_step"
        ) {
            return Err(FlatError::UnknownPath(format!("{path}/{seg}")));
        }
    }
    Ok(Value::Object(o))
}

/// Build one ISM_TRANSITION state field as a DV_CODED_TEXT. With an explicit
/// `|value` the datum parts stand as given; with only a `|code` in the openEHR
/// terminology, the rubric is resolved from the state's openEHR group
/// (`group`) — the same idiom the `ctx/action_ism_transition_current_state`
/// shortcut uses ([`crate::flat::ctx`]; master05 §DV_CODED_TEXT).
fn build_ism_coded(node: &SimNode, group: Option<&str>, path: &str) -> Result<Value, FlatError> {
    let has_value = node.attrs.contains_key("value");
    let terminology = node.attrs.get("terminology").and_then(Value::as_str);
    if !has_value
        && let Some(group) = group
        && let Some(code) = node.attrs.get("code").and_then(Value::as_str)
        && matches!(terminology, None | Some("openehr"))
    {
        return Ok(map::coded_from_group(group, code));
    }
    map::build_leaf(node, "DV_CODED_TEXT", None, path)
}

/// Apply one `_`-segment RM attribute family onto the RM object under
/// construction.
fn apply_rm_attr(
    obj: &mut Map<String, Value>,
    seg: &str,
    occurrences: &[SimNode],
    host_rm_type: &str,
    path: &str,
) -> Result<(), FlatError> {
    if let Some((attr, value)) = map::build_rm_attr(seg, occurrences, host_rm_type, path)? {
        obj.insert(attr, value);
    }
    Ok(())
}

// ── structural re-materialisation ──────────────────────────────────────────

/// Insert `child_value` into `parent` at the relative RM path `rel`,
/// re-materialising the collapsed structural nodes it passes through
/// (`master04 §Level Removal`).
///
/// A `None` `child_value` is a value-less null-flavoured ELEMENT (see
/// [`build`]): the collapsed wrapper chain is still re-materialised and the
/// ELEMENT's own `_`-attribute family applied, but no `value` is inserted
/// (master05 §ELEMENT; RM data_structures §ELEMENT
/// `Inv_null_flavour_indicated`).
fn place(
    parent: &mut Map<String, Value>,
    rel: &[PathSegment],
    child_value: Option<Value>,
    child: &WebTemplateNode,
    occ: &SimNode,
    path: &str,
    ctx: &BuildCtx<'_>,
) -> Result<(), FlatError> {
    if rel.is_empty() {
        return Ok(());
    }
    // Per relative segment, the template-constrained concrete type and name of
    // the structural wrapper at that absolute path.
    let types = wrapper_types(&child.aql_path, rel.len(), &ctx.slots);
    let placement = Placement {
        rel,
        id_idx: rel.iter().rposition(|s| is_multiple(&s.attribute)),
        child,
        occ,
        path,
        types: &types,
        ctx,
    };
    place_rec(parent, 0, child_value, &placement)
}

/// The invariant context of one placement walk: the relative path being
/// materialised, the child it terminates at, that child's occurrence, and the
/// template's wrapper types. Only the receiving map, the segment cursor and
/// the value being placed move through the recursion.
struct Placement<'a> {
    rel: &'a [PathSegment],
    /// The index of the child's OWN repeating array level, if it has one.
    id_idx: Option<usize>,
    child: &'a WebTemplateNode,
    occ: &'a SimNode,
    path: &'a str,
    types: &'a [WrapperFacts],
    ctx: &'a BuildCtx<'a>,
}

impl Placement<'_> {
    /// The constrained RM type of the wrapper at relative segment `i`.
    fn type_at(&self, i: usize) -> Option<&str> {
        self.types.get(i).and_then(|facts| facts.rm_type.as_deref())
    }

    /// The template's name for the wrapper at relative segment `i`.
    fn name_at(&self, i: usize) -> Option<&str> {
        self.types.get(i).and_then(|facts| facts.name.as_deref())
    }
}

/// Materialise the wrapper chain of one relative segment, recursing into the
/// next.
///
/// # Errors
/// [`FlatError`] from a nested placement or an ELEMENT attribute family.
#[expect(
    clippy::indexing_slicing,
    reason = "`i` is a cursor into `rel` that the recursion only advances while `i + 1 < rel.len()` (the `last` guard), so `rel[i]` and `rel[i + 1..]` are in bounds at every call"
)]
fn place_rec(
    cur: &mut Map<String, Value>,
    i: usize,
    child_value: Option<Value>,
    p: &Placement<'_>,
) -> Result<(), FlatError> {
    if Some(i) == p.id_idx {
        return place_own_level(cur, i, child_value, p);
    }
    if is_multiple(&p.rel[i].attribute) {
        return place_structural_level(cur, i, child_value, p);
    }
    place_single_attribute(cur, i, child_value, p)
}

/// The child's own (repeating) array level: the value is either the array
/// element itself (a container child) or is wrapped in a fresh ELEMENT — or
/// deeper structural — node carrying the rest of the path.
///
/// # Errors
/// [`FlatError`] from the nested placement or the ELEMENT attribute family.
#[expect(
    clippy::indexing_slicing,
    reason = "`i` indexes `rel` under the same cursor invariant as `place_rec`"
)]
fn place_own_level(
    cur: &mut Map<String, Value>,
    i: usize,
    child_value: Option<Value>,
    p: &Placement<'_>,
) -> Result<(), FlatError> {
    let seg = &p.rel[i];
    let Some(arr) = cur
        .entry(seg.attribute.clone())
        .or_insert_with(|| json!([]))
        .as_array_mut()
    else {
        return Ok(());
    };
    if i + 1 == p.rel.len() {
        let Some(mut el) = child_value else {
            return Ok(());
        };
        set_node_id(&mut el, seg.predicate.archetype_node_id.as_deref());
        arr.push(el);
        return Ok(());
    }
    let mut el = new_struct(
        seg,
        p.rel.get(i + 1),
        p.child.name.as_deref(),
        p.child.name_coded.as_ref(),
        p.type_at(i),
    );
    if let Value::Object(m) = &mut el {
        place(
            m,
            &p.rel[i + 1..],
            child_value,
            p.child,
            p.occ,
            p.path,
            p.ctx,
        )?;
        // The ELEMENT wrapper's own `_` attribute family (master05 §ELEMENT).
        apply_element_attrs(m, p.occ, p.path)?;
    }
    arr.push(el);
    Ok(())
}

/// A structural (single-occurrence) array level: find-or-create the element
/// carrying this node id, then recurse into it.
///
/// # Errors
/// [`FlatError`] from the nested placement.
#[expect(
    clippy::indexing_slicing,
    reason = "`i` indexes `rel` under the same cursor invariant as `place_rec`"
)]
fn place_structural_level(
    cur: &mut Map<String, Value>,
    i: usize,
    child_value: Option<Value>,
    p: &Placement<'_>,
) -> Result<(), FlatError> {
    let seg = &p.rel[i];
    let node_id = seg.predicate.archetype_node_id.as_deref();
    let Some(arr) = cur
        .entry(seg.attribute.clone())
        .or_insert_with(|| json!([]))
        .as_array_mut()
    else {
        return Ok(());
    };
    // Same-archetype siblings told apart by name (`events[at0002,'Baseline']`
    // beside `events[at0002,'Follow up']`) are distinct nodes, so a name
    // conjunct on the segment takes part in finding the element (BASE
    // `architecture_overview/master11-paths.adoc` §"Using a Name-based Predicate").
    let name = seg.predicate.name_value.as_deref();
    let existing = arr.iter().position(|e| {
        e.get("archetype_node_id").and_then(Value::as_str) == node_id
            && name.is_none_or(|n| e.pointer("/name/value").and_then(Value::as_str) == Some(n))
    });
    let idx = if let Some(pos) = existing {
        pos
    } else {
        arr.push(new_struct(
            seg,
            p.rel.get(i + 1),
            p.name_at(i),
            None,
            p.type_at(i),
        ));
        arr.len() - 1
    };
    if let Some(Value::Object(m)) = arr.get_mut(idx) {
        place_rec(m, i + 1, child_value, p)?;
    }
    Ok(())
}

/// A single-valued (object) attribute: the value lands here, or a fresh
/// structural node carries the rest of the path.
///
/// # Errors
/// [`FlatError`] from the nested placement or the ELEMENT attribute family.
#[expect(
    clippy::indexing_slicing,
    reason = "`i` indexes `rel` under the same cursor invariant as `place_rec`"
)]
fn place_single_attribute(
    cur: &mut Map<String, Value>,
    i: usize,
    child_value: Option<Value>,
    p: &Placement<'_>,
) -> Result<(), FlatError> {
    let seg = &p.rel[i];
    if i + 1 == p.rel.len() {
        let wraps_element = seg.attribute == "value";
        if let Some(child_value) = child_value {
            cur.insert(seg.attribute.clone(), child_value);
        }
        if wraps_element {
            // The map receiving `value` is the compacted-away ELEMENT
            // wrapper; apply its `_` attribute family (master05 §ELEMENT).
            apply_element_attrs(cur, p.occ, p.path)?;
        }
        return Ok(());
    }
    if !cur.contains_key(&seg.attribute) {
        cur.insert(
            seg.attribute.clone(),
            new_struct(seg, p.rel.get(i + 1), p.name_at(i), None, p.type_at(i)),
        );
    }
    if let Some(Value::Object(m)) = cur.get_mut(&seg.attribute) {
        place_rec(m, i + 1, child_value, p)?;
    }
    Ok(())
}

/// Apply the ELEMENT-level `_` attributes of a leaf occurrence onto its
/// re-materialised ELEMENT wrapper (`master05 §ELEMENT`).
fn apply_element_attrs(
    element: &mut Map<String, Value>,
    occ: &SimNode,
    path: &str,
) -> Result<(), FlatError> {
    for (seg, child) in &occ.children {
        if is_element_level(seg) {
            apply_rm_attr(element, seg, &child.occurrences, "ELEMENT", path)?;
        }
    }
    Ok(())
}

/// The set of RM attribute names whose value is a multi-valued *structural*
/// container reachable from a versioned-object root, computed once from the
/// generated BMM RM attribute model ([`openehr_rm::v1_2::model`]) instead of a
/// hard-coded list.
///
/// "Structural" means the attribute's container is a `List`/`Set`/`Hash` **and**
/// its declared element type is not a primitive — so leaf byte
/// arrays such as `DV_MULTIMEDIA.data : Array<Octet>` are excluded (they are
/// values, not wrapper nodes the FLAT builder re-materialises), which keeps
/// single-valued structural attributes such as `OBSERVATION.data : HISTORY`
/// correctly single. The reachability walk starts at the versioned-object roots
/// (`COMPOSITION`, `EHR_STATUS`, `FOLDER`, the concrete parties and
/// `PARTY_RELATIONSHIP`) and follows every class-typed attribute through the RM
/// abstract→concrete descendant sets. Correctness reference: the attribute
/// cardinalities in openEHR RM `common`, `composition`, `ehr`,
/// `data_structures` and `demographic`.
static MULTIVALUED_ATTRS: LazyLock<HashSet<&str>> = LazyLock::new(|| {
    let mut set: HashSet<&'static str> = HashSet::new();
    let mut seen: HashSet<&'static str> = HashSet::new();
    // The versioned-object roots: the three of the EHR (RM ehr §Overview) and
    // the demographic ones (RM demographic `master02-demographic_package.adoc`
    // §Versioning Semantics), so a party build reaches `identities`, `contacts`,
    // `addresses`, `capabilities`, `roles`, `languages` and `relationships`.
    let mut queue: Vec<&'static str> = vec![
        "COMPOSITION",
        "EHR_STATUS",
        "FOLDER",
        "PERSON",
        "ORGANISATION",
        "GROUP",
        "AGENT",
        "ROLE",
        "PARTY_RELATIONSHIP",
    ];
    while let Some(cls) = queue.pop() {
        if !seen.insert(cls) {
            continue;
        }
        for attr in openehr_rm::v1_2::model::attributes(cls) {
            // Only follow (and count) attributes whose value is itself an RM
            // object; a primitive (e.g. `Octet`) is a JSON scalar, never a
            // structural wrapper.
            if openehr_rm::v1_2::model::is_primitive(attr.declared_type) {
                continue;
            }
            if attr.container != openehr_rm::v1_2::model::Container::None {
                set.insert(attr.name);
            }
            queue.push(attr.declared_type);
            queue.extend(
                openehr_rm::v1_2::model::descendants(attr.declared_type)
                    .iter()
                    .copied(),
            );
        }
    }
    set
});

/// Whether `attr` is a multi-valued structural RM attribute — the model-driven
/// membership test of the FLAT composition builder.
fn is_multiple(attr: &str) -> bool {
    MULTIVALUED_ATTRS.contains(attr)
}

/// Map a (possibly abstract/generic) web-template rm type to the concrete
/// RM type to instantiate. `EVENT` is abstract → `POINT_EVENT`.
/// Whether the input at an abstract `EVENT` node asks for an `INTERVAL_EVENT`.
///
/// RM data_structures `master06-history_package.adoc` §EVENT makes `EVENT`
/// abstract over `POINT_EVENT` and `INTERVAL_EVENT`, and only the latter
/// carries `width`, `math_function` and `sample_count` (master05
/// §INTERVAL_EVENT `/width`, `/math_function`, `|sample_count`). Input naming
/// any of them chooses the interval; otherwise the node builds as the point
/// event [`concrete_type`] gives.
fn is_interval_input(node: &WebTemplateNode, sim: &SimNode) -> bool {
    base_type(&node.rm_type) == "EVENT"
        && (sim.children.contains_key("width")
            || sim.children.contains_key("math_function")
            || sim.attrs.contains_key("sample_count"))
}

fn concrete_type(rm_type: &str) -> &str {
    match base_type(rm_type) {
        "EVENT" => "POINT_EVENT",
        other => other,
    }
}

/// Concretise an abstract structural narrowing to the default concrete subtype
/// (`EVENT` → `POINT_EVENT`, `ITEM_STRUCTURE` → `ITEM_TREE`); a concrete type
/// passes through. A structural `_type` must never be abstract.
fn concretize_structural(rm_type: &str) -> &str {
    match rm_type {
        "EVENT" => "POINT_EVENT",
        "ITEM_STRUCTURE" => "ITEM_TREE",
        other => other,
    }
}

fn base_type(rm_type: &str) -> &str {
    rm_type.split('<').next().unwrap_or(rm_type)
}

/// The ENTRY family (`RM/docs/UML/classes/org.openehr.rm.composition.*`): the
/// concrete ENTRY subtypes that carry the RM-mandatory
/// `language`/`encoding`/`subject` in-context attributes.
fn is_entry_family(rm_type: &str) -> bool {
    matches!(
        rm_type,
        "OBSERVATION" | "EVALUATION" | "INSTRUCTION" | "ACTION" | "ADMIN_ENTRY" | "GENERIC_ENTRY"
    )
}

/// Create a collapsed structural RM node for `seg`. Its `_type` is the
/// template-constrained concrete type (`constrained`, when the template narrowed
/// the hoisted wrapper — `ITEM_LIST`/`ITEM_SINGLE`/`INTERVAL_EVENT` — per AOM 1.4
/// type conformance), else inferred from the attribute it sits under and the next
/// step (`master04 §Level Removal`). Mandatory fields are filled per the concrete
/// type.
fn new_struct(
    seg: &PathSegment,
    next: Option<&PathSegment>,
    name: Option<&str>,
    coded_name: Option<&CodedName>,
    constrained: Option<&str>,
) -> Value {
    // An abstract narrowing (`EVENT`, `ITEM_STRUCTURE`) is concretised to the
    // default concrete subtype — so it never mis-stamps an abstract `_type` —
    // while a concrete narrowing (`INTERVAL_EVENT`, `ITEM_LIST`, `ITEM_SINGLE`)
    // passes through.
    let rm_type = constrained.map_or_else(
        || infer_type(&seg.attribute, next.map(|s| s.attribute.as_str())),
        concretize_structural,
    );
    let node_id = seg.predicate.archetype_node_id.as_deref();
    let mut o = Map::new();
    o.insert("_type".into(), json!(rm_type));
    // `name` is `LOCATABLE.name`, so stamping it on a class that does not
    // inherit LOCATABLE authors a member the RM does not declare — the live
    // case is `ISM_TRANSITION`, which inherits PATHABLE (RM
    // `UML/classes/org.openehr.rm.composition.ism_transition.adoc` §Inherit).
    // The generated RM model is the oracle rather than a hardcoded class list.
    if is_locatable(rm_type) {
        // A `[atNNNN,'Name']` conjunct on the path spells the name the ARCHETYPE
        // constrains for this node, so it outranks both the web-template child's
        // display name and the node-id placeholder: a synthesised wrapper named
        // anything else does not satisfy its own template path, and every datum
        // under it becomes unaddressable (RM common
        // `master03-archetyped_package.adoc` §"The `LOCATABLE` class"; BASE
        // `architecture_overview/master11-paths.adoc` §"Using a Name-based
        // Predicate").
        let display = seg
            .predicate
            .name_value
            .as_deref()
            .or(name)
            .map_or_else(|| default_name(rm_type), str::to_owned);
        o.insert("name".into(), name_value(&display, coded_name));
        if let Some(nid) = node_id {
            o.insert("archetype_node_id".into(), json!(nid));
        }
    }
    match rm_type {
        // No `events` until an event lands: ITS-JSON `HISTORY.json` gives the
        // array `minItems: 1`.
        "HISTORY" => {
            o.insert("origin".into(), dv_date_time(DEFAULT_TIME));
        }
        "POINT_EVENT" | "EVENT" | "INTERVAL_EVENT" => {
            o.insert("time".into(), dv_date_time(DEFAULT_TIME));
        }
        // ITEM_SINGLE carries a single `item: ELEMENT` (1..1), ITEM_TABLE a
        // `rows: List<CLUSTER>`; the other ITEM_STRUCTUREs + CLUSTER carry
        // `items` (RM data_structures §ITEM_STRUCTURE). The mandatory member is
        // otherwise filled from content (or by `fill_structural_mandatory`).
        "ITEM_TREE" | "ITEM_LIST" | "CLUSTER" => {
            o.insert("items".into(), json!([]));
        }
        _ => {}
    }
    Value::Object(o)
}

/// Infer the RM type of a collapsed structural step (`master04 §Level
/// Removal`: the elided container attributes name their owner types).
fn infer_type(attr: &str, next: Option<&str>) -> &'static str {
    match (attr, next) {
        ("data", Some("events")) => "HISTORY",
        ("events", _) => "POINT_EVENT",
        // ELEMENT under either the multi-valued `items` (ITEM_TREE/ITEM_LIST/
        // CLUSTER) or the single `item` (ITEM_SINGLE) attribute — both hold an
        // ELEMENT (RM data_structures §ITEM_STRUCTURE).
        ("items" | "item", _) => "ELEMENT",
        ("activities", _) => "ACTIVITY",
        _ => "ITEM_TREE",
    }
}

/// Does `rm_type` inherit `LOCATABLE`, i.e. carry the `name` /
/// `archetype_node_id` / `uid` / `links` / `feeder_audit` attribute set?
///
/// The generated RM model is the oracle rather than a hardcoded class list, so
/// a structural type that is NOT a LOCATABLE never gets a LOCATABLE member
/// stamped on it. `ISM_TRANSITION` is the live case — it inherits `PATHABLE`
/// (`docs/specs/openehr/RM/docs/UML/classes/org.openehr.rm.composition.ism_transition.adoc`
/// §Inherit) and the CKM careflow-state path form `ism_transition[at0109,…]`
/// reaches these builders through a path predicate.
pub(crate) fn is_locatable(rm_type: &str) -> bool {
    openehr_rm::v1_2::model::is_a(rm_type, "LOCATABLE")
}

fn set_node_id(v: &mut Value, node_id: Option<&str>) {
    if let (Value::Object(m), Some(nid)) = (v, node_id) {
        m.entry("archetype_node_id".to_owned())
            .or_insert_with(|| json!(nid));
    }
}

// ── identity + mandatory-field completion ──────────────────────────────────

pub(crate) fn dv_date_time(time: &str) -> Value {
    json!({"_type": "DV_DATE_TIME", "value": time})
}

pub(crate) fn code_phrase(terminology: &str, code: &str) -> Value {
    json!({
        "_type": "CODE_PHRASE",
        "terminology_id": {"_type": "TERMINOLOGY_ID", "value": terminology},
        "code_string": code,
    })
}

pub(crate) fn dv_coded_text(value: &str, terminology: &str, code: &str) -> Value {
    json!({
        "_type": "DV_CODED_TEXT",
        "value": value,
        "defining_code": code_phrase(terminology, code),
    })
}

fn empty_item_tree() -> Value {
    // The `at0001` "Any" placeholder keeps the synthesized filler a valid
    // LOCATABLE (`archetype_node_id` is mandatory; ADL 1.4 master05-cadl
    // §"Any" Constraints — an unconstrained attribute admits any RM-valid
    // value).
    json!({
        "_type": "ITEM_TREE",
        "archetype_node_id": "at0001",
        "name": {"_type": "DV_TEXT", "value": "Tree"},
        "items": []
    })
}

/// Fill the mandatory identity/occurrence fields for a built locatable node.
fn finish_identity(
    obj: &mut Map<String, Value>,
    node: &WebTemplateNode,
    is_root: bool,
    template_id: &str,
    rm_version: &str,
) {
    let rm_type = concrete_type(&node.rm_type);
    if fill_non_locatable(obj, rm_type) {
        return;
    }
    stamp_locatable_identity(obj, node, rm_type);
    fill_time_anchor(obj, rm_type);
    stamp_archetype_details(obj, node, is_root, template_id, rm_version);
    fill_mandatory_entry_attributes(obj, node, rm_type);
}

/// Completes a node whose RM class is not `LOCATABLE`, reporting whether it did.
///
/// A `true` return means the node needs none of the locatable identity,
/// archetype-details or ENTRY-attribute filling that follows it.
fn fill_non_locatable(obj: &mut Map<String, Value>, rm_type: &str) -> bool {
    if rm_type.starts_with("DV_") || rm_type == "CODE_PHRASE" {
        return true; // leaves already complete
    }
    if rm_type == "EVENT_CONTEXT" {
        return true; // PATHABLE, not LOCATABLE; fields come from ctx/
    }
    // PARTICIPATION is not LOCATABLE (RM common
    // `UML/classes/org.openehr.rm.common.participation.adoc` declares exactly
    // `function`/`mode`/`performer`/`time`), so it carries no locatable `name`;
    // its `performer: PARTY_PROXY [1..1]` is mandatory, and the identity-free
    // `PARTY_SELF` fills it without inventing a person.
    if rm_type == "PARTICIPATION" {
        obj.entry("performer".to_owned())
            .or_insert_with(|| json!({"_type": "PARTY_SELF"}));
        return true;
    }
    // PARTY_PROXY subtypes are not LOCATABLE either, and `PARTY_IDENTIFIED.name`
    // is a plain String, never a `DV_TEXT` (RM common
    // `UML/classes/org.openehr.rm.common.party_identified.adoc`). Its
    // `Basic_validity` requires one of `name`/`identifiers`/`external_ref`, so a
    // party built with none of the three gets a plain-String name.
    if matches!(rm_type, "PARTY_SELF" | "PARTY_IDENTIFIED" | "PARTY_RELATED") {
        if rm_type != "PARTY_SELF"
            && !obj.contains_key("name")
            && !obj.contains_key("identifiers")
            && !obj.contains_key("external_ref")
        {
            obj.insert("name".to_owned(), json!("Example party"));
        }
        return true;
    }
    false
}

/// Fills the mandatory time anchor of the two RM classes that carry one.
fn fill_time_anchor(obj: &mut Map<String, Value>, rm_type: &str) {
    match rm_type {
        "POINT_EVENT" | "INTERVAL_EVENT" => {
            obj.entry("time".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
        }
        "HISTORY" => {
            obj.entry("origin".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
        }
        _ => {}
    }
}

/// Fills the RM-mandatory ENTRY attributes the simplified form carried no
/// content under.
///
/// When the template constrains the attribute to a node-identified structural
/// child, the recorded structural stub's identity is stamped — a value the
/// closed-archetype walk admits (AOM 1.4
/// `master04-constraint_model_package.adoc` §Valid_value). Unconstrained
/// attributes get the spec-legal `at0001` "Any" placeholder (ADL 1.4
/// `master05-cadl.adoc` §"Any" Constraints).
fn fill_mandatory_entry_attributes(
    obj: &mut Map<String, Value>,
    node: &WebTemplateNode,
    rm_type: &str,
) {
    if matches!(
        rm_type,
        "OBSERVATION" | "EVALUATION" | "INSTRUCTION" | "ACTION" | "ADMIN_ENTRY" | "GENERIC_ENTRY"
    ) {
        obj.entry("subject".to_owned())
            .or_insert_with(|| json!({"_type": "PARTY_SELF"}));
    }
    match rm_type {
        "OBSERVATION" => {
            obj.entry("data".to_owned())
                .or_insert_with(|| structural_from_stub(node, "data", "HISTORY", "History"));
        }
        "EVALUATION" | "ADMIN_ENTRY" => {
            obj.entry("data".to_owned())
                .or_insert_with(|| structural_from_stub(node, "data", "ITEM_TREE", "Tree"));
        }
        // NOTE: master06 §§instruction_narrative, action_ism_transition_current_state make
        // `INSTRUCTION.narrative` and the ISM state ctx defaults, so complete_tree fills them last.
        "ACTION" => {
            obj.entry("time".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
            obj.entry("description".to_owned())
                .or_insert_with(|| structural_from_stub(node, "description", "ITEM_TREE", "Tree"));
        }
        _ => {}
    }
}

/// Synthesize an empty structural node for a missing mandatory ENTRY
/// attribute (see [`finish_identity`]).
///
/// The stub is looked up by the attribute's absolute path, since the compactor
/// re-homes a hoisted wrapper's stubs (an EVENT's `data`/`state`) onto `node`.
fn structural_from_stub(
    node: &WebTemplateNode,
    attr: &str,
    default_rm_type: &str,
    default_name: &str,
) -> Value {
    let path = format!("{}/{attr}", node.aql_path);
    match node.structural_stubs.iter().find(|s| s.path == path) {
        Some(stub) => structural_from(stub, default_name),
        None => structural_container(default_rm_type, "at0001", default_name),
    }
}

/// Synthesizes the empty structural node a [`WebTemplateStructuralStub`]
/// constrains, named by its rubric or else `default_name`.
pub(crate) fn structural_from(stub: &WebTemplateStructuralStub, default_name: &str) -> Value {
    let name = stub.name.as_deref().unwrap_or(default_name);
    structural_container(concrete_structural(&stub.rm_type), &stub.node_id, name)
}

/// An abstract `ITEM_STRUCTURE` constraint materialises as `ITEM_TREE`; a
/// concrete type passes through.
fn concrete_structural(rm_type: &str) -> &str {
    match rm_type {
        "ITEM_STRUCTURE" => "ITEM_TREE",
        other => other,
    }
}

fn structural_container(rm_type: &str, node_id: &str, name: &str) -> Value {
    let mut o = Map::new();
    o.insert("_type".into(), json!(rm_type));
    o.insert("archetype_node_id".into(), json!(node_id));
    o.insert("name".into(), json!({"_type": "DV_TEXT", "value": name}));
    match rm_type {
        "HISTORY" => {
            o.insert("origin".into(), dv_date_time(DEFAULT_TIME));
        }
        _ => {
            o.insert("items".into(), json!([]));
        }
    }
    Value::Object(o)
}

/// Supplies the mandatory `COMPOSITION.category` when the input named none,
/// taking the default from the template's constraint on it.
///
/// # Errors
///
/// [`FlatError::MissingRequiredSuffix`] naming `<root>/category|code` when the
/// template admits several codes and fixes no default.
fn ensure_category(comp: &mut Map<String, Value>, root: &WebTemplateNode) -> Result<(), FlatError> {
    if comp.contains_key("category") {
        return Ok(());
    }
    let category =
        template_category(root).map_err(|_admitted| FlatError::MissingRequiredSuffix {
            key: format!("{}/category|code", root.id),
        })?;
    comp.insert("category".to_owned(), category);
    Ok(())
}

/// Returns the `COMPOSITION.category` a build supplies for an input that names
/// none, from the template's constraint on `/category`.
///
/// `COMPOSITION.category` is mandatory (RM
/// `UML/classes/org.openehr.rm.composition.composition.adoc` §Attributes, `1..1`), so a default must satisfy
/// the template: its default value (the archetype's assumed value) when it
/// fixes one, else its single admitted code, else `433` (event) when the
/// template leaves the category unconstrained.
///
/// NOTE: no openEHR spec governs the default for an omitted category — our own design/extension.
///
/// # Errors
///
/// The admitted codes when the template admits several and fixes no default:
/// no one of them is the input's.
pub(crate) fn template_category(root: &WebTemplateNode) -> Result<Value, Vec<String>> {
    let input = root
        .children
        .iter()
        .find(|child| child.aql_path == "/category")
        .and_then(|node| {
            node.inputs
                .iter()
                .find(|input| input.suffix.as_deref() == Some("code"))
        });
    let Some(input) = input.filter(|input| !input.list.is_empty()) else {
        return Ok(dv_coded_text("event", "openehr", "433"));
    };
    let terminology = input.terminology.as_deref().unwrap_or("openehr");
    let assumed = input.default_value.as_ref().and_then(Value::as_str);
    let chosen = match (assumed, input.list.as_slice()) {
        (Some(code), list) => list.iter().find(|entry| entry.value == code),
        (None, [only]) => Some(only),
        (None, _) => None,
    };
    match chosen {
        Some(entry) => Ok(dv_coded_text(
            entry.label.as_deref().unwrap_or(&entry.value),
            terminology,
            &entry.value,
        )),
        None => Err(input.list.iter().map(|entry| entry.value.clone()).collect()),
    }
}

/// Ensure the composition's `archetype_details` carries `archetype_id` +
/// `template_id` (the composition must be self-describing for its
/// template; the `openehr-template-id` REST header exists exactly because
/// the simplified payload cannot carry it — ITS-REST
/// `Requests_and_responses.md §openehr-template-id`).
fn ensure_template_id(
    comp: &mut Map<String, Value>,
    root: &WebTemplateNode,
    template_id: &str,
    rm_version: &str,
) {
    let ad = comp
        .entry("archetype_details".to_owned())
        .or_insert_with(|| {
            json!({"_type": "ARCHETYPED",
                   "archetype_id": {"_type": "ARCHETYPE_ID", "value": recorded_archetype_id(root)},
                   "rm_version": rm_version})
        });
    if let Value::Object(ad) = ad {
        ad.entry("template_id".to_owned())
            .or_insert_with(|| json!({"_type": "TEMPLATE_ID", "value": template_id}));
    }
}

// ── context application ────────────────────────────────────────────────────

/// Apply the composition-level context (`master06`: language, territory,
/// composer, and the EVENT_CONTEXT when warranted).
fn apply_composition_ctx(
    comp: &mut Map<String, Value>,
    defaults: &ctx::CtxDefaults,
    explicit_event_context: bool,
) {
    if let Some(language) = defaults.language_code_phrase() {
        comp.entry("language".to_owned()).or_insert(language);
    }
    if let Some(territory) = defaults.territory_code_phrase() {
        comp.entry("territory".to_owned()).or_insert(territory);
    }
    if let Some(composer) = &defaults.composer {
        comp.entry("composer".to_owned())
            .or_insert_with(|| composer.clone());
    }
    // An EVENT_CONTEXT is built only when the client expressed event-context
    // content (explicit ctx/ keys per master06, or archetyped other_context
    // tree data) — never fabricated from the category alone. NOTE: no openEHR
    // spec mandates synthesizing a context; the master06 time/setting
    // defaults apply when a context is being expressed, and round-trip
    // stability requires not inventing one (RM ehr master05 §"Persistent
    // Compositions may optionally have an Event context").
    if !explicit_event_context && !comp.contains_key("context") {
        return;
    }
    let context = comp
        .entry("context".to_owned())
        .or_insert_with(|| json!({"_type": "EVENT_CONTEXT"}));
    let Value::Object(context) = context else {
        return;
    };
    context
        .entry("start_time".to_owned())
        .or_insert_with(|| dv_date_time(&defaults.time));
    context
        .entry("setting".to_owned())
        .or_insert_with(|| defaults.setting.clone());
    if let Some(end_time) = &defaults.end_time {
        context
            .entry("end_time".to_owned())
            .or_insert_with(|| dv_date_time(end_time));
    }
    if let Some(location) = &defaults.location {
        context
            .entry("location".to_owned())
            .or_insert_with(|| json!(location));
    }
    if let Some(facility) = &defaults.health_care_facility {
        context
            .entry("health_care_facility".to_owned())
            .or_insert_with(|| facility.clone());
    }
    if !defaults.participations.is_empty() {
        context
            .entry("participations".to_owned())
            .or_insert_with(|| json!(defaults.participations));
    }
}

/// Walk the built tree applying the per-entry `ctx/` defaults
/// (`master06`: ENTRY language/encoding/subject/provider/workflow_id/
/// other_participations, OBSERVATION history origin + event times, ACTION
/// time/ism state, INSTRUCTION narrative, ACTIVITY timing, LOCATABLE
/// links on the root).
fn apply_entry_defaults(value: &mut Value, defaults: &ctx::CtxDefaults) {
    if !defaults.links.is_empty()
        && let Value::Object(root) = value
    {
        root.entry("links".to_owned())
            .or_insert_with(|| json!(defaults.links));
    }
    walk_entry_defaults(value, defaults);
}

fn walk_entry_defaults(value: &mut Value, defaults: &ctx::CtxDefaults) {
    match value {
        Value::Array(items) => {
            for item in items {
                walk_entry_defaults(item, defaults);
            }
        }
        Value::Object(obj) => {
            let rm_type = obj
                .get("_type")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned();
            apply_common_entry_defaults(obj, &rm_type, defaults);
            match rm_type.as_str() {
                "OBSERVATION" => apply_observation_defaults(obj, defaults),
                "ACTION" => apply_action_defaults(obj, defaults),
                "INSTRUCTION" => {
                    if let Some(narrative) = &defaults.instruction_narrative {
                        obj.entry("narrative".to_owned())
                            .or_insert_with(|| json!({"_type": "DV_TEXT", "value": narrative}));
                    }
                }
                "ACTIVITY" => {
                    if let Some(timing) = &defaults.activity_timing {
                        obj.entry("timing".to_owned()).or_insert_with(|| {
                            json!({"_type": "DV_PARSABLE", "value": timing, "formalism": "timing"})
                        });
                    }
                }
                _ => {}
            }
            for child in obj.values_mut() {
                walk_entry_defaults(child, defaults);
            }
        }
        _ => {}
    }
}

/// The defaults every ENTRY subtype takes: language, encoding, provider and
/// workflow id.
///
/// NOTE: master06 §Participation also names `ENTRY.other_participations`, but
/// master05's explicit `_other_participation:i` path form wins, so ctx lands
/// here only.
fn apply_common_entry_defaults(
    obj: &mut Map<String, Value>,
    rm_type: &str,
    defaults: &ctx::CtxDefaults,
) {
    if !matches!(
        rm_type,
        "OBSERVATION" | "EVALUATION" | "INSTRUCTION" | "ACTION" | "ADMIN_ENTRY" | "GENERIC_ENTRY"
    ) {
        return;
    }
    if let Some(language) = defaults.language_code_phrase() {
        obj.entry("language".to_owned()).or_insert(language);
    }
    obj.entry("encoding".to_owned())
        .or_insert_with(|| code_phrase("IANA_character-sets", "UTF-8"));
    if let Some(provider) = &defaults.provider {
        obj.entry("provider".to_owned())
            .or_insert_with(|| provider.clone());
    }
    if let Some(wf) = &defaults.work_flow_id {
        obj.entry("workflow_id".to_owned())
            .or_insert_with(|| wf.clone());
    }
}

/// The OBSERVATION defaults: the HISTORY origin, and each EVENT's time, which
/// defaults to that origin (master06 §time).
///
/// An origin the input does not set is the `ctx/history_origin` default, else
/// the time of the earliest event that states one ("will be set to the time of
/// the earliest event if not explicitly set", master05 §OBSERVATION
/// `/history_origin`), else the composition's context time.
fn apply_observation_defaults(obj: &mut Map<String, Value>, defaults: &ctx::CtxDefaults) {
    let Some(Value::Object(history)) = obj.get_mut("data") else {
        return;
    };
    let origin = defaults
        .history_origin
        .clone()
        .or_else(|| earliest_event_time(history))
        .unwrap_or_else(|| defaults.time.clone());
    let origin_value = history
        .entry("origin".to_owned())
        .or_insert_with(|| dv_date_time(&origin));
    if origin_value.get("value").and_then(Value::as_str) == Some(DEFAULT_TIME) {
        *origin_value = dv_date_time(&origin);
    }
    let origin_now = origin_value.clone();
    let Some(Value::Array(events)) = history.get_mut("events") else {
        return;
    };
    for event in events {
        if let Value::Object(ev) = event {
            let time = ev
                .entry("time".to_owned())
                .or_insert_with(|| origin_now.clone());
            if time.get("value").and_then(Value::as_str) == Some(DEFAULT_TIME) {
                *time = origin_now.clone();
            }
        }
    }
}

/// The earliest time an EVENT of `history` states, as written; `None` when no
/// event states a time this reader can order.
///
/// Times are compared as instants: each is read as an ISO 8601 extended date
/// time with its offset, and one that does not read leaves the comparison.
fn earliest_event_time(history: &Map<String, Value>) -> Option<String> {
    let Some(Value::Array(events)) = history.get("events") else {
        return None;
    };
    events
        .iter()
        .filter_map(|event| event.pointer("/time/value").and_then(Value::as_str))
        .filter(|time| *time != DEFAULT_TIME)
        .filter_map(|time| instant(time).map(|at| (at, time)))
        .min_by_key(|(at, _)| *at)
        .map(|(_, time)| time.to_owned())
}

/// An ISO 8601 extended date time (`YYYY-MM-DDThh:mm[:ss[.f…]]` with `Z` or
/// `±hh:mm`, or none for local time read as UTC) as nanoseconds since
/// 1970-01-01T00:00Z, or `None` when `text` is not of that form.
fn instant(text: &str) -> Option<i128> {
    let (date, rest) = text.split_once('T')?;
    let mut ymd = date.splitn(3, '-');
    let year: i64 = ymd.next()?.parse().ok()?;
    let month: i64 = ymd.next()?.parse().ok()?;
    let day: i64 = ymd.next()?.parse().ok()?;
    let (clock, offset_minutes) = if let Some(clock) = rest.strip_suffix('Z') {
        (clock, 0)
    } else if let Some(at) = rest.rfind(['+', '-']) {
        let (clock, offset) = rest.split_at(at);
        let sign = if offset.starts_with('-') { -1 } else { 1 };
        let (hours, minutes) = offset.get(1..)?.split_once(':')?;
        let minutes = hours.parse::<i64>().ok()? * 60 + minutes.parse::<i64>().ok()?;
        (clock, sign * minutes)
    } else {
        (rest, 0)
    };
    let mut hms = clock.splitn(3, ':');
    let hour: i64 = hms.next()?.parse().ok()?;
    let minute: i64 = hms.next()?.parse().ok()?;
    let (second, nanos) = match hms.next() {
        None => (0, 0),
        Some(sec) => match sec.split_once(['.', ',']) {
            None => (sec.parse::<i64>().ok()?, 0),
            Some((whole, frac)) => {
                let digits: String = frac.chars().chain("000000000".chars()).take(9).collect();
                (whole.parse::<i64>().ok()?, digits.parse::<i64>().ok()?)
            }
        },
    };
    // NOTE: the days-from-civil count of the proleptic Gregorian calendar
    // (H. Hinnant, "chrono-Compatible Low-Level Date Algorithms").
    let y = if month <= 2 { year - 1 } else { year };
    let era = y.div_euclid(400);
    let yoe = y - era * 400;
    let mp = (month + 9) % 12;
    let doy = (153 * mp + 2).div_euclid(5) + day - 1;
    let doe = yoe * 365 + yoe.div_euclid(4) - yoe.div_euclid(100) + doy;
    let days = era * 146_097 + doe - 719_468;
    let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_minutes * 60;
    Some(i128::from(seconds) * 1_000_000_000 + i128::from(nanos))
}

/// The ACTION defaults: the action time and the ISM transition's current
/// state.
fn apply_action_defaults(obj: &mut Map<String, Value>, defaults: &ctx::CtxDefaults) {
    let time = defaults
        .action_time
        .clone()
        .unwrap_or_else(|| defaults.time.clone());
    let entry = obj
        .entry("time".to_owned())
        .or_insert_with(|| dv_date_time(&time));
    if entry.get("value").and_then(Value::as_str) == Some(DEFAULT_TIME) {
        *entry = dv_date_time(&time);
    }
    let Some(state) = &defaults.action_ism_current_state else {
        return;
    };
    let ism = obj
        .entry("ism_transition".to_owned())
        .or_insert_with(|| json!({"_type": "ISM_TRANSITION"}));
    if let Value::Object(ism) = ism {
        ism.entry("current_state".to_owned())
            .or_insert_with(|| state.clone());
    }
}

/// Recursively fill each node's remaining RM-mandatory structural fields.
fn complete_tree(v: &mut Value) {
    match v {
        Value::Object(m) => {
            if let Some(ty) = m.get("_type").and_then(Value::as_str).map(str::to_owned) {
                fill_structural_mandatory(m, &ty);
            }
            for child in m.values_mut() {
                complete_tree(child);
            }
        }
        Value::Array(a) => {
            for e in a.iter_mut() {
                complete_tree(e);
            }
        }
        _ => {}
    }
}

/// Fill the RM-mandatory fields of an RM node that are never surfaced on
/// the simplified wire and are therefore absent after the datum-driven
/// build. Only missing fields are added, so a datum-driven value is never
/// overwritten and the round-trip stays stable.
fn fill_structural_mandatory(obj: &mut Map<String, Value>, rm_type: &str) {
    match rm_type {
        "HISTORY" => {
            obj.entry("origin".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
        }
        "POINT_EVENT" | "EVENT" => {
            obj.entry("time".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
            obj.entry("data".to_owned()).or_insert_with(empty_item_tree);
        }
        "INTERVAL_EVENT" => {
            obj.entry("time".to_owned())
                .or_insert_with(|| dv_date_time(DEFAULT_TIME));
            obj.entry("data".to_owned()).or_insert_with(empty_item_tree);
            // width + math_function are RM-mandatory on INTERVAL_EVENT but
            // never data-entry leaves (openEHR `146` = "mean").
            obj.entry("width".to_owned())
                .or_insert_with(|| json!({"_type": "DV_DURATION", "value": "P0D"}));
            obj.entry("math_function".to_owned())
                .or_insert_with(|| dv_coded_text("mean", "openehr", "146"));
        }
        "ITEM_TREE" | "ITEM_LIST" | "CLUSTER" => {
            obj.entry("items".to_owned()).or_insert_with(|| json!([]));
        }
        // ITEM_SINGLE carries one mandatory `item: ELEMENT` (1..1, RM
        // data_structures §ITEM_SINGLE); when the wrapper carried no content, a
        // null-flavoured ELEMENT is the minimal conforming filler
        // (`ELEMENT.Is_null`: value xor null_flavour — openEHR `253` = "unknown").
        "ITEM_SINGLE" => {
            obj.entry("item".to_owned()).or_insert_with(|| {
                json!({
                    "_type": "ELEMENT",
                    "archetype_node_id": "at0001",
                    "name": {"_type": "DV_TEXT", "value": "Element"},
                    "null_flavour": dv_coded_text("unknown", "openehr", "253"),
                })
            });
        }
        // ITEM_TABLE carries `rows: List<CLUSTER>` (RM data_structures §ITEM_TABLE).
        "ITEM_TABLE" => {
            obj.entry("rows".to_owned()).or_insert_with(|| json!([]));
        }
        "ACTIVITY" => {
            // action_archetype_id defaults to the match-all form
            // (master05 §ACTIVITY: "Will be set to /.*/ if not set
            // explicit.").
            obj.entry("action_archetype_id".to_owned())
                .or_insert_with(|| json!("/.*/"));
            obj.entry("description".to_owned())
                .or_insert_with(empty_item_tree);
        }
        "ISM_TRANSITION" => {
            obj.entry("current_state".to_owned())
                .or_insert_with(|| dv_coded_text("initial", "openehr", "524"));
        }
        "INSTRUCTION" => {
            obj.entry("narrative".to_owned())
                .or_insert_with(|| json!({"_type": "DV_TEXT", "value": "<narrative>"}));
        }
        "ACTION" => {
            obj.entry("ism_transition".to_owned())
                .or_insert_with(|| json!({"_type": "ISM_TRANSITION"}));
        }
        _ => {}
    }
}

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

    /// ITS-JSON `Data_structures/HISTORY.json` gives `events` `minItems: 1`,
    /// so neither a synthesised nor a completed HISTORY carries `events: []`.
    #[test]
    fn a_history_without_an_event_carries_no_events_member() {
        let built = structural_container("HISTORY", "at0001", "History");
        assert!(built.get("events").is_none(), "{built}");
        let mut obj = Map::new();
        fill_structural_mandatory(&mut obj, "HISTORY");
        assert!(
            obj.contains_key("origin") && !obj.contains_key("events"),
            "{obj:?}"
        );
    }

    /// master05 §OBSERVATION `/history_origin`: an origin the input does not
    /// set is "the time of the earliest event", compared as instants, not as
    /// text.
    #[test]
    fn an_unset_history_origin_is_the_earliest_event_time() {
        let mut obj = json!({
            "_type": "OBSERVATION",
            "data": { "_type": "HISTORY", "events": [
                { "_type": "POINT_EVENT", "time": dv_date_time("2026-03-02T10:00:00+01:00") },
                { "_type": "POINT_EVENT", "time": dv_date_time("2026-03-02T08:30:00Z") },
                { "_type": "POINT_EVENT" }
            ]}
        });
        let defaults = ctx::CtxDefaults {
            time: "2026-03-05T12:00:00Z".to_owned(),
            ..ctx::CtxDefaults::default()
        };
        let Value::Object(map) = &mut obj else {
            panic!("an object")
        };
        apply_observation_defaults(map, &defaults);
        assert_eq!(obj["data"]["origin"]["value"], "2026-03-02T08:30:00Z");
        assert_eq!(
            obj["data"]["events"][2]["time"]["value"], "2026-03-02T08:30:00Z",
            "an event without a time takes the origin"
        );

        let mut none = json!({"_type": "OBSERVATION", "data": {"_type": "HISTORY", "events": []}});
        let Value::Object(map) = &mut none else {
            panic!("an object")
        };
        apply_observation_defaults(map, &defaults);
        assert_eq!(
            none["data"]["origin"]["value"], "2026-03-05T12:00:00Z",
            "with no event time the context time stands"
        );
    }

    #[test]
    fn instants_order_across_offsets() {
        assert!(instant("2026-03-02T10:00:00+01:00") > instant("2026-03-02T08:30:00Z"));
        assert_eq!(instant("1970-01-01T00:00:00Z"), Some(0));
        assert_eq!(instant("1970-01-01T01:00:00.5+01:00"), Some(500_000_000));
        assert_eq!(instant("not a time"), None);
    }

    /// The two `_`-families a PARTY leaf builder consumes itself, so the
    /// generic router never sees them twice (master05 §§PARTY_IDENTIFIED,
    /// PARTY_RELATED). The empty-edge consequence of the identifier half is
    /// pinned in `map::parties::tests`.
    #[test]
    fn a_party_leaf_consumes_its_relationship_and_identifier_families() {
        for base in [
            "PARTY_PROXY",
            "PARTY_SELF",
            "PARTY_IDENTIFIED",
            "PARTY_RELATED",
        ] {
            assert!(leaf_consumes_segment(base, "_relationship"), "{base}");
            assert!(leaf_consumes_segment(base, "_identifier"), "{base}");
            // Everything else still routes generically.
            assert!(!leaf_consumes_segment(base, "_feeder_audit"), "{base}");
        }
        // Only a party consumes them: on any other host the router owns the
        // segment (and reports an unknown suffix where there is no arm).
        assert!(!leaf_consumes_segment("DV_TEXT", "_identifier"));
        assert!(!leaf_consumes_segment("ELEMENT", "_relationship"));
    }

    #[test]
    fn infer_type_matches_level_removal_owners() {
        // master04 §Level Removal: the elided container attributes.
        assert_eq!(infer_type("data", Some("events")), "HISTORY");
        assert_eq!(infer_type("events", None), "POINT_EVENT");
        assert_eq!(infer_type("items", None), "ELEMENT");
        assert_eq!(infer_type("activities", None), "ACTIVITY");
        assert_eq!(infer_type("state", Some("items")), "ITEM_TREE");
    }
}

#[cfg(test)]
mod multiplicity_tests {
    use super::is_multiple;

    /// Completeness guard: the model-driven set must cover every member of the
    /// former hard-coded COMPOSITION/HISTORY/ITEM/ENTRY envelope, so replacing
    /// the list with the RM-model lookup does not lose coverage.
    #[test]
    fn covers_legacy_hardcoded_set() {
        for attr in ["content", "items", "events", "activities"] {
            assert!(
                is_multiple(attr),
                "model-driven multiplicity set must include the legacy member `{attr}`",
            );
        }
    }

    /// Behaviour guard: `data` must stay single. Its only container use in the RM
    /// is `DV_MULTIMEDIA.data : Array<Octet>` (a byte array, not a structural
    /// wrapper); the structural `data` attributes (`OBSERVATION.data : HISTORY`,
    /// `ADMIN_ENTRY.data : ITEM_STRUCTURE`) are single-valued and must not be
    /// re-materialised as arrays.
    #[test]
    fn data_stays_single() {
        assert!(
            !is_multiple("data"),
            "`data` must not be treated as multi-valued (OBSERVATION.data is a single HISTORY)",
        );
    }

    /// The derivation now reaches genuinely multi-valued structural attributes
    /// beyond the legacy four.
    #[test]
    fn covers_reachable_multi_valued_attributes() {
        assert!(is_multiple("other_participations"));
    }

    /// An unknown / non-container attribute is not multi-valued.
    #[test]
    fn rejects_single_and_unknown() {
        assert!(!is_multiple("value"));
        assert!(!is_multiple("not_a_real_attribute"));
    }
}