alizarin-core 2.0.0-alpha.118

Core data structures and algorithms for Arches heritage graph and tile processing
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
//! Resource types for resource instances and metadata.

use super::descriptors::StaticResourceDescriptors;
use super::tile::StaticTile;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Metadata about a resource instance
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StaticResourceMetadata {
    pub descriptors: StaticResourceDescriptors,
    pub graph_id: String,
    pub name: String,
    pub resourceinstanceid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub publication_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub principaluser_id: Option<i32>,
    #[serde(default)]
    pub legacyid: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph_publication_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub createdtime: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lastmodified: Option<String>,
}

/// Summary info for a resource (used for lazy loading)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StaticResourceSummary {
    pub resourceinstanceid: String,
    pub graph_id: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub descriptors: Option<StaticResourceDescriptors>,
    #[serde(default)]
    pub metadata: HashMap<String, String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub createdtime: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lastmodified: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub publication_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub principaluser_id: Option<i32>,
    #[serde(default)]
    pub legacyid: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph_publication_id: Option<String>,
}

impl StaticResourceSummary {
    /// Convert summary to metadata
    pub fn to_metadata(&self) -> StaticResourceMetadata {
        StaticResourceMetadata {
            descriptors: self.descriptors.clone().unwrap_or_default(),
            graph_id: self.graph_id.clone(),
            name: self.name.clone(),
            resourceinstanceid: self.resourceinstanceid.clone(),
            publication_id: self.publication_id.clone(),
            principaluser_id: self.principaluser_id,
            legacyid: self.legacyid.clone(),
            graph_publication_id: self.graph_publication_id.clone(),
            createdtime: self.createdtime.clone(),
            lastmodified: self.lastmodified.clone(),
        }
    }
}

/// Reference to another resource instance (for resource-instance datatype)
///
/// Used in ResourceInstanceViewModel to represent relationships between resources.
/// Can include the full resource tree if cascade is enabled.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StaticResourceReference {
    /// Resource instance ID
    pub id: String,
    /// Graph ID for the resource model
    #[serde(rename = "graphId")]
    pub graph_id: String,
    /// Resource model type/name (optional)
    #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
    pub resource_type: Option<String>,
    /// Display title for the resource (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Full resource tree data (when cascaded, optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub root: Option<serde_json::Value>,
    /// Additional metadata (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

impl StaticResourceReference {
    /// Create a minimal resource reference with just ID and graph ID
    pub fn new(id: String, graph_id: String) -> Self {
        StaticResourceReference {
            id,
            graph_id,
            resource_type: None,
            title: None,
            root: None,
            meta: None,
        }
    }

    /// Create a reference with type information
    pub fn with_type(id: String, graph_id: String, resource_type: String) -> Self {
        StaticResourceReference {
            id,
            graph_id,
            resource_type: Some(resource_type),
            title: None,
            root: None,
            meta: None,
        }
    }

    /// Add title to reference (builder pattern)
    pub fn with_title(mut self, title: String) -> Self {
        self.title = Some(title);
        self
    }

    /// Add metadata to reference (builder pattern)
    pub fn with_meta(mut self, meta: HashMap<String, serde_json::Value>) -> Self {
        self.meta = Some(meta);
        self
    }

    /// Add root data to reference for cascaded loading (builder pattern)
    pub fn with_root(mut self, root: serde_json::Value) -> Self {
        self.root = Some(root);
        self
    }
}

/// Complete resource data with tiles
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StaticResource {
    pub resourceinstance: StaticResourceMetadata,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tiles: Option<Vec<StaticTile>>,
    #[serde(default)]
    pub metadata: HashMap<String, String>,

    // Optional cache and scopes - stored as JSON for platform independence
    #[serde(skip_serializing_if = "Option::is_none", default, rename = "__cache")]
    pub cache: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none", default, rename = "__scopes")]
    pub scopes: Option<serde_json::Value>,

    // Tracking flag for lazy loading
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub tiles_loaded: Option<bool>,
}

impl StaticResource {
    /// Convert to a summary (for registry storage)
    pub fn to_summary(&self) -> StaticResourceSummary {
        StaticResourceSummary {
            resourceinstanceid: self.resourceinstance.resourceinstanceid.clone(),
            graph_id: self.resourceinstance.graph_id.clone(),
            name: self.resourceinstance.name.clone(),
            descriptors: Some(self.resourceinstance.descriptors.clone()),
            metadata: self.metadata.clone(),
            createdtime: self.resourceinstance.createdtime.clone(),
            lastmodified: self.resourceinstance.lastmodified.clone(),
            publication_id: self.resourceinstance.publication_id.clone(),
            principaluser_id: self.resourceinstance.principaluser_id,
            legacyid: self.resourceinstance.legacyid.clone(),
            graph_publication_id: self.resourceinstance.graph_publication_id.clone(),
        }
    }
}

/// Cache entry for a related resource, matching ResourceInstanceCacheEntry from TypeScript.
///
/// This structure is compatible with TypeScript's getValueCache format,
/// allowing direct lookup by tileId/nodeId when rendering ViewModels.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RelatedResourceEntry {
    /// Datatype marker (always "resource-instance")
    pub datatype: String,
    /// Resource instance ID (UUID)
    pub id: String,
    /// Model class name (derived from graph name, e.g., "Person")
    #[serde(rename = "type")]
    pub resource_type: String,
    /// Graph ID
    #[serde(rename = "graphId")]
    pub graph_id: String,
    /// Display title (resource name)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Resource descriptors (name, description, map_popup, slug)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub descriptors: Option<StaticResourceDescriptors>,
    /// Additional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

impl RelatedResourceEntry {
    /// Create from a resource entry with optional model class name
    pub fn from_resource_entry(entry: &ResourceEntry, model_class_name: Option<&str>) -> Self {
        RelatedResourceEntry {
            datatype: "resource-instance".to_string(),
            id: entry.resourceinstanceid().to_string(),
            resource_type: model_class_name
                .map(|s| s.to_string())
                .unwrap_or_else(|| entry.graph_id().to_string()),
            graph_id: entry.graph_id().to_string(),
            title: Some(entry.name().to_string()),
            descriptors: entry.descriptors().cloned(),
            meta: None,
        }
    }

    /// Create from a resource summary with optional model class name
    pub fn from_summary(summary: &StaticResourceSummary, model_class_name: Option<&str>) -> Self {
        RelatedResourceEntry {
            datatype: "resource-instance".to_string(),
            id: summary.resourceinstanceid.clone(),
            resource_type: model_class_name
                .map(|s| s.to_string())
                .unwrap_or_else(|| summary.graph_id.clone()),
            graph_id: summary.graph_id.clone(),
            title: Some(summary.name.clone()),
            descriptors: summary.descriptors.clone(),
            meta: if summary.metadata.is_empty() {
                None
            } else {
                Some(
                    summary
                        .metadata
                        .iter()
                        .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
                        .collect(),
                )
            },
        }
    }

    /// Get the resource instance ID
    pub fn resourceinstanceid(&self) -> &str {
        &self.id
    }
}

impl From<&StaticResourceSummary> for RelatedResourceEntry {
    fn from(summary: &StaticResourceSummary) -> Self {
        RelatedResourceEntry::from_summary(summary, None)
    }
}

impl From<&StaticResource> for RelatedResourceEntry {
    fn from(resource: &StaticResource) -> Self {
        let descriptors = &resource.resourceinstance.descriptors;
        RelatedResourceEntry {
            datatype: "resource-instance".to_string(),
            id: resource.resourceinstance.resourceinstanceid.clone(),
            resource_type: resource.resourceinstance.graph_id.clone(),
            graph_id: resource.resourceinstance.graph_id.clone(),
            title: Some(resource.resourceinstance.name.clone()),
            descriptors: if descriptors.is_empty() {
                None
            } else {
                Some(descriptors.clone())
            },
            meta: None,
        }
    }
}

impl From<RelatedResourceEntry> for StaticResourceSummary {
    /// Hydrate a cache entry back to a full summary (with optional fields as None/empty)
    fn from(entry: RelatedResourceEntry) -> Self {
        StaticResourceSummary {
            resourceinstanceid: entry.id,
            graph_id: entry.graph_id,
            name: entry.title.unwrap_or_default(),
            descriptors: entry.descriptors,
            metadata: HashMap::new(),
            createdtime: None,
            lastmodified: None,
            publication_id: None,
            principaluser_id: None,
            legacyid: None,
            graph_publication_id: None,
        }
    }
}

impl From<&ResourceEntry> for RelatedResourceEntry {
    fn from(entry: &ResourceEntry) -> Self {
        RelatedResourceEntry::from_resource_entry(entry, None)
    }
}

/// Cache entry for resource-instance-list nodes.
///
/// Contains an array of resource entries to match TypeScript's ResourceInstanceListCacheEntry.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RelatedResourceListEntry {
    /// Datatype marker (always "resource-instance-list")
    pub datatype: String,
    /// List of resource entries
    #[serde(rename = "_")]
    pub entries: Vec<RelatedResourceEntry>,
    /// Additional metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

impl RelatedResourceListEntry {
    /// Create a new empty list entry
    pub fn new() -> Self {
        RelatedResourceListEntry {
            datatype: "resource-instance-list".to_string(),
            entries: Vec::new(),
            meta: None,
        }
    }

    /// Add an entry to the list
    pub fn push(&mut self, entry: RelatedResourceEntry) {
        self.entries.push(entry);
    }

    /// Check if the list is empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

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

/// Cache entry that can be either a single resource or a list of resources.
///
/// Uses untagged serialization to match TypeScript's expected format:
/// - resource-instance: `{datatype: "resource-instance", id, type, graphId, title}`
/// - resource-instance-list: `{datatype: "resource-instance-list", _: [...], meta}`
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CacheEntry {
    /// Single resource reference (for resource-instance datatype)
    Single(RelatedResourceEntry),
    /// List of resource references (for resource-instance-list datatype)
    List(RelatedResourceListEntry),
}

/// Cache structure for __cache field, matching TypeScript's getValueCache format.
///
/// Structure: { tileId: { nodeId: CacheEntry, ... }, ... }
///
/// This allows direct lookup in TypeScript via:
/// `cacheEntries[tile.tileid][node.nodeid]`
pub type ResourceCache = HashMap<String, HashMap<String, CacheEntry>>;

/// Mutable context passed through resource-instance processing
struct ProcessResourceContext<'a> {
    cache: &'a mut ResourceCache,
    enrich_relationships: bool,
    source_resource_id: &'a str,
    result: &'a mut PopulateCachesResult,
}

/// Reference to an unknown resource found during cache population
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UnknownReference {
    /// Resource that contains the reference
    pub source_resource_id: String,
    /// Node ID where the reference was found
    pub node_id: String,
    /// Node alias (if any)
    pub node_alias: Option<String>,
    /// The unknown resource ID that was referenced
    pub referenced_id: String,
}

/// Result of populate_caches operation
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PopulateCachesResult {
    /// References to resources not found in the registry
    pub unknown_references: Vec<UnknownReference>,
}

impl PopulateCachesResult {
    /// Check if there were any unknown references
    pub fn has_unknown_references(&self) -> bool {
        !self.unknown_references.is_empty()
    }

    /// Get error messages for unknown references
    pub fn error_messages(&self) -> Vec<String> {
        self.unknown_references
            .iter()
            .map(|r| {
                let node_desc = r
                    .node_alias
                    .as_ref()
                    .map(|a| format!("node '{}' ({})", a, r.node_id))
                    .unwrap_or_else(|| format!("node '{}'", r.node_id));
                format!(
                    "Resource '{}': {} references unknown resource '{}'",
                    r.source_resource_id, node_desc, r.referenced_id
                )
            })
            .collect()
    }
}

/// Entry in the resource registry - either full resource or summary only
///
/// This allows the registry to store minimal summaries (memory efficient) or
/// full resources with tiles (for traversal), similar to staticStore's cacheMetadataOnly pattern.
#[derive(Clone, Debug)]
pub enum ResourceEntry {
    /// Summary only - minimal memory, no tiles
    Summary(Box<StaticResourceSummary>),
    /// Full resource with tiles
    Full(Box<StaticResource>),
}

impl ResourceEntry {
    /// Get the resource instance ID
    pub fn resourceinstanceid(&self) -> &str {
        match self {
            ResourceEntry::Summary(s) => &s.resourceinstanceid,
            ResourceEntry::Full(r) => &r.resourceinstance.resourceinstanceid,
        }
    }

    /// Get the graph ID
    pub fn graph_id(&self) -> &str {
        match self {
            ResourceEntry::Summary(s) => &s.graph_id,
            ResourceEntry::Full(r) => &r.resourceinstance.graph_id,
        }
    }

    /// Get the resource name
    pub fn name(&self) -> &str {
        match self {
            ResourceEntry::Summary(s) => &s.name,
            ResourceEntry::Full(r) => &r.resourceinstance.name,
        }
    }

    /// Get the resource descriptors (if available)
    pub fn descriptors(&self) -> Option<&StaticResourceDescriptors> {
        match self {
            ResourceEntry::Summary(s) => s.descriptors.as_ref(),
            ResourceEntry::Full(r) => Some(&r.resourceinstance.descriptors),
        }
    }

    /// Check if this entry has tiles (is a full resource with tiles loaded)
    pub fn has_tiles(&self) -> bool {
        match self {
            ResourceEntry::Summary(_) => false,
            ResourceEntry::Full(r) => r.tiles.as_ref().map(|t| !t.is_empty()).unwrap_or(false),
        }
    }

    /// Check if this is a full resource entry
    pub fn is_full(&self) -> bool {
        matches!(self, ResourceEntry::Full(_))
    }

    /// Get as full resource reference (if available)
    pub fn as_full(&self) -> Option<&StaticResource> {
        match self {
            ResourceEntry::Full(r) => Some(r),
            ResourceEntry::Summary(_) => None,
        }
    }

    /// Get as full resource mutable reference (if available)
    pub fn as_full_mut(&mut self) -> Option<&mut StaticResource> {
        match self {
            ResourceEntry::Full(r) => Some(r),
            ResourceEntry::Summary(_) => None,
        }
    }

    /// Convert to summary (extracts summary from full resource if needed)
    pub fn to_summary(&self) -> StaticResourceSummary {
        match self {
            ResourceEntry::Summary(s) => *s.clone(),
            ResourceEntry::Full(r) => r.to_summary(),
        }
    }

    /// Convert to minimal cache entry
    pub fn to_cache_entry(&self) -> RelatedResourceEntry {
        match self {
            ResourceEntry::Summary(s) => RelatedResourceEntry::from(s.as_ref()),
            ResourceEntry::Full(r) => RelatedResourceEntry::from(r.as_ref()),
        }
    }
}

impl From<StaticResourceSummary> for ResourceEntry {
    fn from(summary: StaticResourceSummary) -> Self {
        ResourceEntry::Summary(Box::new(summary))
    }
}

impl From<StaticResource> for ResourceEntry {
    fn from(resource: StaticResource) -> Self {
        ResourceEntry::Full(Box::new(resource))
    }
}

/// Diagnostic stats for the resource registry
#[derive(Clone, Debug, Serialize)]
pub struct RegistryMemoryStats {
    pub total: usize,
    pub full_count: usize,
    pub summary_count: usize,
    pub total_tiles: usize,
    pub cache_entries: usize,
    /// Estimated bytes of __cache JSON across all full resources
    pub cache_bytes_est: usize,
    /// Estimated bytes of tile data JSON across all full resources
    pub tile_bytes_est: usize,
}

/// In-memory registry of resources for relationship resolution and caching
///
/// Stores either full resources or summaries, allowing memory-efficient storage
/// when only metadata is needed, with the ability to upgrade to full resources
/// when tiles are required.
///
/// Used to:
/// - Look up graph_id for referenced resources
/// - Populate __cache on resources with related resource summaries
/// - Enrich resource-instance tile data with ontologyProperty from node config
/// - Cache full resources for traversal (like staticStore)
#[derive(Clone, Debug, Default)]
pub struct StaticResourceRegistry {
    resources: HashMap<String, ResourceEntry>,
}

impl StaticResourceRegistry {
    /// Create an empty registry
    pub fn new() -> Self {
        Self {
            resources: HashMap::new(),
        }
    }

    /// Get the graph_id for a resource
    pub fn get_graph_id(&self, resource_id: &str) -> Option<&str> {
        self.resources.get(resource_id).map(|e| e.graph_id())
    }

    /// Get the entry for a resource
    pub fn get(&self, resource_id: &str) -> Option<&ResourceEntry> {
        self.resources.get(resource_id)
    }

    /// Get a mutable entry for a resource
    pub fn get_mut(&mut self, resource_id: &str) -> Option<&mut ResourceEntry> {
        self.resources.get_mut(resource_id)
    }

    /// Get the full resource if available (returns None if only summary stored)
    pub fn get_full(&self, resource_id: &str) -> Option<&StaticResource> {
        self.resources.get(resource_id).and_then(|e| e.as_full())
    }

    /// Get a summary for a resource (works for both summary and full entries)
    pub fn get_summary(&self, resource_id: &str) -> Option<StaticResourceSummary> {
        self.resources.get(resource_id).map(|e| e.to_summary())
    }

    /// Check if a resource is known
    pub fn contains(&self, resource_id: &str) -> bool {
        self.resources.contains_key(resource_id)
    }

    /// Check if a resource has full data with tiles
    pub fn has_full(&self, resource_id: &str) -> bool {
        self.resources
            .get(resource_id)
            .map(|e| e.is_full())
            .unwrap_or(false)
    }

    /// Get a breakdown of registry contents for memory diagnostics.
    ///
    /// Returns (total_entries, full_count, summary_count, total_tiles, total_cache_bytes)
    /// where total_cache_bytes is an estimate of serialized __cache JSON size.
    pub fn memory_stats(&self) -> RegistryMemoryStats {
        let mut full_count: usize = 0;
        let mut summary_count: usize = 0;
        let mut total_tiles: usize = 0;
        let mut cache_entries: usize = 0;

        for entry in self.resources.values() {
            match entry {
                ResourceEntry::Full(r) => {
                    full_count += 1;
                    total_tiles += r.tiles.as_ref().map(|t| t.len()).unwrap_or(0);
                    if r.cache.is_some() {
                        cache_entries += 1;
                    }
                }
                ResourceEntry::Summary(_) => {
                    summary_count += 1;
                }
            }
        }

        RegistryMemoryStats {
            total: self.resources.len(),
            full_count,
            summary_count,
            total_tiles,
            cache_entries,
            cache_bytes_est: 0,
            tile_bytes_est: 0,
        }
    }

    /// Expensive version that estimates byte sizes by re-serializing.
    /// Call once, not in a loop.
    pub fn memory_stats_detailed(&self) -> RegistryMemoryStats {
        let mut stats = self.memory_stats();
        let mut cache_bytes_est: usize = 0;
        let mut tile_bytes_est: usize = 0;

        for entry in self.resources.values() {
            if let ResourceEntry::Full(r) = entry {
                if let Some(ref cache) = r.cache {
                    cache_bytes_est += serde_json::to_string(cache).map(|s| s.len()).unwrap_or(0);
                }
                if let Some(ref tiles) = r.tiles {
                    tile_bytes_est += serde_json::to_string(tiles).map(|s| s.len()).unwrap_or(0);
                }
            }
        }

        stats.cache_bytes_est = cache_bytes_est;
        stats.tile_bytes_est = tile_bytes_est;
        stats
    }

    /// Number of resources in the registry
    pub fn len(&self) -> usize {
        self.resources.len()
    }

    /// Check if registry is empty
    pub fn is_empty(&self) -> bool {
        self.resources.is_empty()
    }

    /// Add a single resource summary (won't overwrite full resources)
    pub fn insert_summary(&mut self, summary: StaticResourceSummary) {
        let id = summary.resourceinstanceid.clone();
        // Don't downgrade full → summary
        if !self.has_full(&id) {
            self.resources
                .insert(id, ResourceEntry::Summary(Box::new(summary)));
        }
    }

    /// Add a single resource summary (legacy alias for insert_summary)
    pub fn insert(&mut self, summary: StaticResourceSummary) {
        self.insert_summary(summary);
    }

    /// Add a full resource (always overwrites, as it's more complete)
    pub fn insert_full(&mut self, resource: StaticResource) {
        let id = resource.resourceinstance.resourceinstanceid.clone();
        self.resources
            .insert(id, ResourceEntry::Full(Box::new(resource)));
    }

    /// Upgrade a summary to a full resource (if the resource exists)
    pub fn upgrade_to_full(&mut self, resource: StaticResource) {
        let id = resource.resourceinstance.resourceinstanceid.clone();
        self.resources
            .insert(id, ResourceEntry::Full(Box::new(resource)));
    }

    /// Merge resources into registry
    ///
    /// - If store_full is true, stores full resources (for traversal)
    /// - If store_full is false, stores only summaries (memory efficient)
    /// - If include_caches is true, also merges any __cache.relatedResources as summaries
    pub fn merge_from_resources(
        &mut self,
        resources: &[StaticResource],
        store_full: bool,
        include_caches: bool,
    ) {
        for resource in resources {
            // Register the resource itself
            if store_full {
                self.insert_full(resource.clone());
            } else {
                self.insert_summary(resource.to_summary());
            }

            // Merge from __cache if present and requested (always as summaries)
            if include_caches {
                if let Some(ref cache_json) = resource.cache {
                    if let Ok(cache) = serde_json::from_value::<ResourceCache>(cache_json.clone()) {
                        // Cache is now keyed by tileId -> nodeId -> entry
                        for (_tile_id, node_entries) in cache {
                            for (_node_id, cache_entry) in node_entries {
                                // Extract entries based on cache entry type
                                let entries: Vec<&RelatedResourceEntry> = match &cache_entry {
                                    CacheEntry::Single(entry) => vec![entry],
                                    CacheEntry::List(list) => list.entries.iter().collect(),
                                };

                                for entry in entries {
                                    let id = entry.id.clone();
                                    // Don't overwrite existing entries (first wins, and don't downgrade)
                                    self.resources.entry(id).or_insert_with(|| {
                                        ResourceEntry::Summary(Box::new(
                                            StaticResourceSummary::from(entry.clone()),
                                        ))
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Iterate over all entries
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ResourceEntry)> {
        self.resources.iter()
    }

    /// Iterate over all full resources
    pub fn iter_full(&self) -> impl Iterator<Item = (&String, &StaticResource)> {
        self.resources
            .iter()
            .filter_map(|(id, entry)| entry.as_full().map(|r| (id, r)))
    }

    /// Get all resource IDs
    pub fn ids(&self) -> impl Iterator<Item = &String> {
        self.resources.keys()
    }

    /// Populate __cache on resources with summaries for referenced resources
    ///
    /// Uses the graph to identify resource-instance/resource-instance-list nodes,
    /// then populates cache entries for each referenced resource.
    ///
    /// If `enrich_relationships` is true, also adds ontologyProperty/inverseOntologyProperty
    /// to tile data based on node config and the target resource's graph.
    ///
    /// Returns information about unknown references found during processing.
    pub fn populate_caches(
        &self,
        resources: &mut [StaticResource],
        graph: &super::StaticGraph,
        enrich_relationships: bool,
        strict: bool,
        recompute_descriptors: bool,
    ) -> Result<PopulateCachesResult, String> {
        let mut result = PopulateCachesResult::default();

        for resource in resources.iter_mut() {
            let mut cache: ResourceCache = HashMap::new();
            let resource_id = resource.resourceinstance.resourceinstanceid.clone();

            if let Some(ref mut tiles) = resource.tiles {
                for tile in tiles.iter_mut() {
                    // Get tile ID (generate if missing)
                    let tile_id = tile
                        .tileid
                        .clone()
                        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

                    // Get all nodes in this nodegroup
                    let nodes = graph.get_nodes_in_nodegroup(&tile.nodegroup_id);

                    for node in nodes {
                        // Only process resource-instance datatypes
                        if node.datatype != "resource-instance"
                            && node.datatype != "resource-instance-list"
                        {
                            continue;
                        }

                        // Get tile data for this node
                        if let Some(data) = tile.data.get_mut(&node.nodeid) {
                            let mut ctx = ProcessResourceContext {
                                cache: &mut cache,
                                enrich_relationships,
                                source_resource_id: &resource_id,
                                result: &mut result,
                            };
                            self.process_resource_instance_data(data, node, &tile_id, &mut ctx);
                        }
                    }
                }
            }

            // Merge with existing cache if present
            if !cache.is_empty() {
                if let Some(ref existing_json) = resource.cache {
                    if let Ok(existing) =
                        serde_json::from_value::<ResourceCache>(existing_json.clone())
                    {
                        // Merge existing into new cache (new wins for conflicts)
                        for (tile_id, node_entries) in existing {
                            let tile_cache = cache.entry(tile_id).or_default();
                            for (node_id, entry) in node_entries {
                                tile_cache.entry(node_id).or_insert(entry);
                            }
                        }
                    }
                }
                resource.cache = serde_json::to_value(&cache).ok();
            }
        }

        // Recompute descriptors using the freshly-built caches
        if recompute_descriptors {
            let indexed = super::static_graph::IndexedGraph::new(graph.clone());
            for resource in resources.iter_mut() {
                let tiles = resource.tiles.as_deref().unwrap_or(&[]);
                let cache: Option<ResourceCache> = resource
                    .cache
                    .as_ref()
                    .and_then(|v| serde_json::from_value(v.clone()).ok());
                let descriptors = indexed.build_descriptors_with_diagnostics(
                    tiles,
                    &mut Vec::new(),
                    cache.as_ref(),
                );
                if let Some(ref name) = descriptors.name {
                    if !name.is_empty() {
                        resource.resourceinstance.name = name.clone();
                    }
                }
                resource.resourceinstance.descriptors = descriptors;
            }
        }

        if strict && result.has_unknown_references() {
            let msgs = result.error_messages();
            return Err(format!("Unknown resource references:\n{}", msgs.join("\n")));
        }

        Ok(result)
    }

    /// Process resource-instance data: populate cache and optionally enrich with relationship properties
    fn process_resource_instance_data(
        &self,
        data: &mut serde_json::Value,
        node: &super::StaticNode,
        tile_id: &str,
        ctx: &mut ProcessResourceContext<'_>,
    ) {
        let is_list = node.datatype == "resource-instance-list";

        // For lists, collect all entries first
        let mut list_entries: Vec<RelatedResourceEntry> = Vec::new();

        // resource-instance data is an array of {resourceId: "..."}
        if let Some(arr) = data.as_array_mut() {
            for entry in arr.iter_mut() {
                if let Some(resource_id) = entry.get("resourceId").and_then(|r| r.as_str()) {
                    // Add to cache if we know this resource
                    if let Some(resource_entry) = self.resources.get(resource_id) {
                        // Get model class name from graph registry if available
                        let model_class_name = crate::get_graph(resource_entry.graph_id())
                            .and_then(|g| g.get_model_class_name());

                        let related_entry = RelatedResourceEntry::from_resource_entry(
                            resource_entry,
                            model_class_name.as_deref(),
                        );

                        if is_list {
                            // Collect entries for list
                            list_entries.push(related_entry);
                        } else {
                            // Store single entry in cache keyed by tileId -> nodeId
                            let tile_cache = ctx.cache.entry(tile_id.to_string()).or_default();
                            tile_cache
                                .insert(node.nodeid.clone(), CacheEntry::Single(related_entry));
                        }

                        // Enrich with relationship properties if requested
                        if ctx.enrich_relationships {
                            self.enrich_entry_with_relationship(entry, resource_entry, node);
                        }
                    } else {
                        // Track unknown reference
                        ctx.result.unknown_references.push(UnknownReference {
                            source_resource_id: ctx.source_resource_id.to_string(),
                            node_id: node.nodeid.clone(),
                            node_alias: node.alias.clone(),
                            referenced_id: resource_id.to_string(),
                        });
                    }
                }
            }
        }

        // For list datatype, store all collected entries as a list
        if is_list && !list_entries.is_empty() {
            let tile_cache = ctx.cache.entry(tile_id.to_string()).or_default();
            tile_cache.insert(
                node.nodeid.clone(),
                CacheEntry::List(RelatedResourceListEntry {
                    datatype: "resource-instance-list".to_string(),
                    entries: list_entries,
                    meta: None,
                }),
            );
        }
    }

    /// Add ontologyProperty/inverseOntologyProperty to a resource-instance entry
    /// based on node config and target resource's graph
    fn enrich_entry_with_relationship(
        &self,
        entry: &mut serde_json::Value,
        target_entry: &ResourceEntry,
        node: &super::StaticNode,
    ) {
        // Skip if already has ontologyProperty
        if entry.get("ontologyProperty").is_some() {
            return;
        }

        // Get node config graphs array
        let graphs = match node.config.get("graphs").and_then(|g| g.as_array()) {
            Some(g) => g,
            None => return,
        };

        // Find matching graph config for target resource's graph_id
        let target_graph_id = target_entry.graph_id();
        let graph_config = graphs.iter().find(|g| {
            g.get("graphid")
                .and_then(|id| id.as_str())
                .map(|id| id == target_graph_id)
                .unwrap_or(false)
        });

        let graph_config = match graph_config {
            Some(g) => g,
            None => return, // Target graph not configured for this node
        };

        // Determine which properties to use based on useOntologyRelationship
        let use_ontology = graph_config
            .get("useOntologyRelationship")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let (ont_key, inv_key) = if use_ontology {
            ("ontologyProperty", "inverseOntologyProperty")
        } else {
            ("relationshipConcept", "inverseRelationshipConcept")
        };

        // Add properties to entry (using ontologyProperty key for Arches compatibility)
        if let Some(prop) = graph_config.get(ont_key).and_then(|v| v.as_str()) {
            if !prop.is_empty() {
                entry["ontologyProperty"] = serde_json::json!(prop);
            }
        }
        if let Some(prop) = graph_config.get(inv_key).and_then(|v| v.as_str()) {
            if !prop.is_empty() {
                entry["inverseOntologyProperty"] = serde_json::json!(prop);
            }
        }
    }

    /// Build an index from resource IDs to node values for a given node.
    ///
    /// Efficiently iterates through tiles, filtering by nodegroup and extracting
    /// values for the specified node.
    ///
    /// # Arguments
    /// * `graph` - The graph to use for node lookup
    /// * `node_identifier` - Node alias or node ID to extract values for
    ///
    /// # Returns
    /// * `Ok(HashMap<String, Vec<Value>>)` - Map from resource_id to list of values
    /// * `Err(String)` - Error if node not found
    pub fn get_node_values_index(
        &self,
        graph: &super::StaticGraph,
        node_identifier: &str,
    ) -> Result<HashMap<String, Vec<serde_json::Value>>, String> {
        // Find the node by alias or ID
        let node = graph
            .nodes
            .iter()
            .find(|n| n.alias.as_deref() == Some(node_identifier) || n.nodeid == node_identifier)
            .ok_or_else(|| {
                format!(
                    "Node '{}' not found in graph {}",
                    node_identifier, graph.graphid
                )
            })?;

        let node_id = &node.nodeid;
        let nodegroup_id = node
            .nodegroup_id
            .as_ref()
            .ok_or_else(|| format!("Node '{}' has no nodegroup_id", node_identifier))?;

        let mut index: HashMap<String, Vec<serde_json::Value>> = HashMap::new();

        for (_, resource) in self.iter_full() {
            // Filter by graph
            if resource.resourceinstance.graph_id != graph.graphid {
                continue;
            }

            let resource_id = &resource.resourceinstance.resourceinstanceid;

            // Find tiles matching the nodegroup
            if let Some(ref tiles) = resource.tiles {
                for tile in tiles {
                    if tile.nodegroup_id.as_str() == nodegroup_id {
                        if let Some(value) = tile.data.get(node_id) {
                            index
                                .entry(resource_id.clone())
                                .or_default()
                                .push(value.clone());
                        }
                    }
                }
            }
        }

        Ok(index)
    }

    /// Build an inverted index from node display values to resource IDs.
    ///
    /// Uses the type serialization infrastructure to extract display strings,
    /// which handles built-in types (string, concept, domain-value, etc.) and
    /// extension-registered types (reference, etc.) via the global registry.
    ///
    /// # Arguments
    /// * `graph` - The graph to use for node lookup
    /// * `node_identifier` - Node alias or node ID to extract values for
    /// * `flatten_localized` - If true, extract string from localized values {"en": "value"}
    ///
    /// # Returns
    /// * `Ok(HashMap<String, Vec<String>>)` - Map from display value to list of resource_ids
    /// * `Err(String)` - Error if node not found
    pub fn get_value_to_resources_index(
        &self,
        graph: &super::StaticGraph,
        node_identifier: &str,
        flatten_localized: bool,
    ) -> Result<HashMap<String, Vec<String>>, String> {
        self.get_value_to_resources_index_with_context(
            graph,
            node_identifier,
            flatten_localized,
            None,
        )
    }

    /// Build an inverted index from node display values to resource IDs,
    /// with an explicit serialization context for resolvers and extensions.
    ///
    /// # Arguments
    /// * `graph` - The graph to use for node lookup
    /// * `node_identifier` - Node alias or node ID to extract values for
    /// * `flatten_localized` - If true, extract string from localized values {"en": "value"}
    /// * `ctx` - Optional serialization context (resolvers, extension registry)
    ///
    /// # Returns
    /// * `Ok(HashMap<String, Vec<String>>)` - Map from display value to list of resource_ids
    /// * `Err(String)` - Error if node not found
    pub fn get_value_to_resources_index_with_context(
        &self,
        graph: &super::StaticGraph,
        node_identifier: &str,
        flatten_localized: bool,
        ctx: Option<&crate::type_serialization::SerializationContext>,
    ) -> Result<HashMap<String, Vec<String>>, String> {
        use crate::node_config::NodeConfigManager;
        use crate::type_serialization::{
            serialize_value, SerializationContext, SerializationOptions,
        };

        // Find the node by alias or ID
        let node = graph
            .nodes
            .iter()
            .find(|n| n.alias.as_deref() == Some(node_identifier) || n.nodeid == node_identifier)
            .ok_or_else(|| {
                format!(
                    "Node '{}' not found in graph {}",
                    node_identifier, graph.graphid
                )
            })?;

        let node_id = &node.nodeid;
        let datatype = &node.datatype;
        let nodegroup_id = node
            .nodegroup_id
            .as_ref()
            .ok_or_else(|| format!("Node '{}' has no nodegroup_id", node_identifier))?;

        // Build node config from graph for this node's datatype
        let mut ncm = NodeConfigManager::new();
        ncm.build_from_graph(graph);
        let node_config = ncm.get(node_id);

        let language = if flatten_localized { "en" } else { "" };
        let opts = SerializationOptions::display(language);

        let empty_ctx = SerializationContext::empty();
        let base_ctx = ctx.unwrap_or(&empty_ctx);
        let ser_ctx = SerializationContext {
            node_config,
            external_resolver: base_ctx.external_resolver,
            resource_resolver: base_ctx.resource_resolver,
            extension_registry: base_ctx.extension_registry,
        };

        let mut index: HashMap<String, Vec<String>> = HashMap::new();

        for (_, resource) in self.iter_full() {
            // Filter by graph
            if resource.resourceinstance.graph_id != graph.graphid {
                continue;
            }

            let resource_id = &resource.resourceinstance.resourceinstanceid;

            // Find tiles matching the nodegroup
            if let Some(ref tiles) = resource.tiles {
                for tile in tiles {
                    if tile.nodegroup_id.as_str() == nodegroup_id {
                        if let Some(value) = tile.data.get(node_id) {
                            let result = serialize_value(datatype, value, &opts, Some(&ser_ctx));
                            if result.is_error() {
                                continue;
                            }
                            let keys = extract_display_keys(&result.value);
                            for k in keys {
                                index.entry(k).or_default().push(resource_id.clone());
                            }
                        }
                    }
                }
            }
        }

        Ok(index)
    }

    /// Extract values from one node in tiles where another node matches a filter.
    ///
    /// Both nodes must be in the same nodegroup. For each tile in that nodegroup,
    /// the filter node's display value is checked against `filter_values`. If any
    /// filter value appears in the display string, the extract node's raw JSON
    /// value is included in the results.
    ///
    /// # Arguments
    /// * `graph` - The graph for node lookup
    /// * `filter_node` - Alias or ID of the node to filter on
    /// * `filter_values` - Display values that pass the filter (matched as substrings of comma-separated tags)
    /// * `extract_node` - Alias or ID of the node whose values to extract
    /// * `flatten_localized` - If true, flatten localized values for the filter node
    ///
    /// # Returns
    /// A `Vec<serde_json::Value>` of raw values from the extract node for matching tiles.
    #[allow(clippy::too_many_arguments)]
    pub fn get_filtered_tile_values(
        &self,
        graph: &super::StaticGraph,
        filter_node: &str,
        filter_values: &[&str],
        extract_node: &str,
        flatten_localized: bool,
        ctx: Option<&crate::type_serialization::SerializationContext>,
        required_scope: Option<&str>,
    ) -> Result<Vec<serde_json::Value>, String> {
        use crate::node_config::NodeConfigManager;
        use crate::type_serialization::{
            serialize_value, SerializationContext, SerializationOptions,
        };

        let find_node = |identifier: &str| {
            graph
                .nodes
                .iter()
                .find(|n| n.alias.as_deref() == Some(identifier) || n.nodeid == identifier)
                .ok_or_else(|| {
                    format!("Node '{}' not found in graph {}", identifier, graph.graphid)
                })
        };

        let filter = find_node(filter_node)?;
        let extract = find_node(extract_node)?;

        let filter_node_id = &filter.nodeid;
        let filter_datatype = &filter.datatype;
        let filter_nodegroup_id = filter
            .nodegroup_id
            .as_ref()
            .ok_or_else(|| format!("Node '{}' has no nodegroup_id", filter_node))?;

        let extract_node_id = &extract.nodeid;
        let extract_nodegroup_id = extract
            .nodegroup_id
            .as_ref()
            .ok_or_else(|| format!("Node '{}' has no nodegroup_id", extract_node))?;

        if filter_nodegroup_id != extract_nodegroup_id {
            return Err(format!(
                "Filter node '{}' (nodegroup {}) and extract node '{}' (nodegroup {}) are not in the same nodegroup",
                filter_node, filter_nodegroup_id, extract_node, extract_nodegroup_id
            ));
        }

        let mut ncm = NodeConfigManager::new();
        ncm.build_from_graph(graph);
        let node_config = ncm.get(filter_node_id);

        let language = if flatten_localized { "en" } else { "" };
        let opts = SerializationOptions::display(language);

        let empty_ctx = SerializationContext::empty();
        let base_ctx = ctx.unwrap_or(&empty_ctx);
        let ser_ctx = SerializationContext {
            node_config,
            external_resolver: base_ctx.external_resolver,
            resource_resolver: base_ctx.resource_resolver,
            extension_registry: base_ctx.extension_registry,
        };

        let mut results: Vec<serde_json::Value> = Vec::new();

        for (_, resource) in self.iter_full() {
            if resource.resourceinstance.graph_id != graph.graphid {
                continue;
            }

            // Check resource-level scope if required
            if let Some(scope) = required_scope {
                let has_scope = resource
                    .scopes
                    .as_ref()
                    .and_then(|s| s.as_array())
                    .map(|arr| arr.iter().any(|v| v.as_str() == Some(scope)))
                    .unwrap_or(false);
                if !has_scope {
                    continue;
                }
            }

            if let Some(ref tiles) = resource.tiles {
                for tile in tiles {
                    if tile.nodegroup_id.as_str() != filter_nodegroup_id.as_str() {
                        continue;
                    }

                    // Check filter node value
                    let matches = if let Some(filter_value) = tile.data.get(filter_node_id) {
                        let result =
                            serialize_value(filter_datatype, filter_value, &opts, Some(&ser_ctx));
                        if result.is_error() {
                            false
                        } else {
                            let keys = extract_display_keys(&result.value);
                            keys.iter().any(|display| {
                                let tags: Vec<&str> =
                                    display.split(',').map(|t| t.trim()).collect();
                                filter_values.iter().any(|fv| tags.contains(fv))
                            })
                        }
                    } else {
                        false
                    };

                    if matches {
                        if let Some(extract_value) = tile.data.get(extract_node_id) {
                            results.push(extract_value.clone());
                        }
                    }
                }
            }
        }

        Ok(results)
    }
}

/// Extract string keys from a serialized display value.
///
/// Handles:
/// - String: returns the single string
/// - Array of strings: returns each string element
/// - Array of objects: tries to extract string values from each
/// - Null: returns empty
/// - Other: uses JSON representation as key
fn extract_display_keys(value: &serde_json::Value) -> Vec<String> {
    match value {
        serde_json::Value::String(s) => vec![s.clone()],
        serde_json::Value::Array(arr) => arr
            .iter()
            .filter_map(|v| match v {
                serde_json::Value::String(s) => Some(s.clone()),
                serde_json::Value::Null => None,
                other => Some(other.to_string()),
            })
            .collect(),
        serde_json::Value::Null => vec![],
        other => vec![other.to_string()],
    }
}

impl crate::type_serialization::ResourceDisplayResolver for StaticResourceRegistry {
    fn resolve_resource_display(&self, resource_id: &str, _language: &str) -> Option<String> {
        let summary = self.get_summary(resource_id)?;
        // Try descriptors.name first, fall back to summary.name
        if let Some(ref descriptors) = summary.descriptors {
            if let Some(ref name) = descriptors.name {
                if !name.is_empty() {
                    return Some(name.clone());
                }
            }
        }
        if !summary.name.is_empty() {
            Some(summary.name)
        } else {
            None
        }
    }
}

/// Result of merging multiple resources (single resourceinstanceid)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MergeResult {
    /// The merged resource with combined tiles
    pub resource: StaticResource,
    /// Warnings about duplicate tileids that were skipped
    pub warnings: Vec<String>,
}

/// Result of batch merging resources grouped by resourceinstanceid
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BatchMergeResult {
    /// Merged resources, one per unique resourceinstanceid
    pub resources: Vec<StaticResource>,
    /// All warnings from merging (including which resource had issues)
    pub warnings: Vec<String>,
    /// Fatal error message if strict mode aborted early
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Merge multiple StaticResources into one
///
/// All resources must have the same `resourceinstanceid`. Tiles are concatenated,
/// with duplicate `tileid` values detected and skipped (first occurrence kept).
///
/// # Arguments
/// * `resources` - Vector of StaticResources to merge
///
/// # Returns
/// * `Ok(MergeResult)` - Merged resource and any warnings about duplicates
/// * `Err(String)` - Error if resources is empty or IDs don't match
///
/// # Example
/// ```ignore
/// let result = merge_resources(vec![resource1, resource2])?;
/// if !result.warnings.is_empty() {
///     eprintln!("Merge warnings: {:?}", result.warnings);
/// }
/// let merged = result.resource;
/// ```
pub fn merge_resources(resources: Vec<StaticResource>) -> Result<MergeResult, String> {
    if resources.is_empty() {
        return Err("No resources to merge".to_string());
    }

    // Clone first resource's metadata before we consume the vector
    let first_instance = resources[0].resourceinstance.clone();
    let resource_id = first_instance.resourceinstanceid.clone();

    // Verify all resources have the same resourceinstanceid
    for (i, r) in resources.iter().enumerate().skip(1) {
        if r.resourceinstance.resourceinstanceid != resource_id {
            return Err(format!(
                "Resource ID mismatch at index {}: expected '{}', found '{}'",
                i, resource_id, r.resourceinstance.resourceinstanceid
            ));
        }
    }

    let mut seen_tileids: HashSet<String> = HashSet::new();
    let mut merged_tiles: Vec<StaticTile> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();
    let mut merged_metadata: HashMap<String, String> = HashMap::new();
    let mut merged_cache: ResourceCache = ResourceCache::default();
    let mut merged_scopes: Option<serde_json::Value> = None;
    let mut first_scopes_index: Option<usize> = None;

    for (i, resource) in resources.into_iter().enumerate() {
        // Merge tiles with duplicate detection
        if let Some(tiles) = resource.tiles {
            for tile in tiles {
                if let Some(ref tileid) = tile.tileid {
                    if seen_tileids.contains(tileid) {
                        continue;
                    }
                    seen_tileids.insert(tileid.clone());
                }
                merged_tiles.push(tile);
            }
        }

        // Merge metadata dicts (later values override earlier ones)
        for (key, value) in resource.metadata {
            if let Some(existing) = merged_metadata.get(&key) {
                if existing != &value {
                    warnings.push(format!(
                        "Metadata key '{}' has conflicting values: '{}' vs '{}' (using latter)",
                        key, existing, value
                    ));
                }
            }
            merged_metadata.insert(key, value);
        }

        // Handle scopes: warn if different, use first non-None value
        if let Some(scopes) = resource.scopes {
            match &merged_scopes {
                None => {
                    merged_scopes = Some(scopes);
                    first_scopes_index = Some(i);
                }
                Some(existing) if existing != &scopes => {
                    warnings.push(format!(
                        "Scopes mismatch: resource {} has different scopes than resource {} (using first)",
                        i, first_scopes_index.unwrap_or(0)
                    ));
                }
                _ => {}
            }
        }

        // Merge cache entries (first wins for conflicts)
        // Cache is now keyed by tileId -> nodeId -> entry
        if let Some(cache_json) = resource.cache {
            if let Ok(cache) = serde_json::from_value::<ResourceCache>(cache_json) {
                for (tile_id, node_entries) in cache {
                    let tile_cache = merged_cache.entry(tile_id).or_default();
                    for (node_id, entry) in node_entries {
                        // First wins - don't overwrite existing entries
                        tile_cache.entry(node_id).or_insert(entry);
                    }
                }
            }
        }
    }

    // Sort merged tiles by (nodegroup_id, sortorder) for consistent ordering
    merged_tiles.sort_by(|a, b| {
        let ng_cmp = a.nodegroup_id.cmp(&b.nodegroup_id);
        if ng_cmp != std::cmp::Ordering::Equal {
            return ng_cmp;
        }
        let a_sort = a.sortorder.unwrap_or(i32::MAX);
        let b_sort = b.sortorder.unwrap_or(i32::MAX);
        a_sort.cmp(&b_sort)
    });

    // Convert merged_cache to JSON value if non-empty
    let final_cache = if merged_cache.is_empty() {
        None
    } else {
        serde_json::to_value(&merged_cache).ok()
    };

    Ok(MergeResult {
        resource: StaticResource {
            resourceinstance: first_instance,
            tiles: Some(merged_tiles),
            metadata: merged_metadata,
            cache: final_cache,
            scopes: merged_scopes,
            tiles_loaded: Some(true),
        },
        warnings,
    })
}

/// Parse a JSON string into a Vec of StaticResources.
///
/// Accepts multiple formats:
/// - An array of resources: `[{resourceinstance: ...}, ...]`
/// - A BusinessDataWrapper: `{business_data: {resources: [...]}}`
/// - A single resource: `{resourceinstance: ..., tiles: [...]}`
///
/// Takes ownership of the parsed JSON value internally to avoid cloning.
pub fn parse_resources_from_json_str(json_str: &str) -> Result<Vec<StaticResource>, String> {
    let value: serde_json::Value =
        serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;

    match value {
        serde_json::Value::Array(_) => serde_json::from_value(value)
            .map_err(|e| format!("Failed to parse resource array: {}", e)),
        serde_json::Value::Object(mut map) => {
            if let Some(bd) = map.remove("business_data") {
                if let serde_json::Value::Object(mut bd_map) = bd {
                    if let Some(resources) = bd_map.remove("resources") {
                        serde_json::from_value(resources)
                            .map_err(|e| format!("Failed to parse business_data.resources: {}", e))
                    } else {
                        Err("business_data missing 'resources' field".to_string())
                    }
                } else {
                    Err("business_data is not an object".to_string())
                }
            } else if map.contains_key("resourceinstance") {
                let resource: StaticResource =
                    serde_json::from_value(serde_json::Value::Object(map))
                        .map_err(|e| format!("Failed to parse as single resource: {}", e))?;
                Ok(vec![resource])
            } else {
                Err(
                    "Unrecognized format - expected array, BusinessDataWrapper, or StaticResource"
                        .to_string(),
                )
            }
        }
        _ => Err("Expected array or object".to_string()),
    }
}

/// Stateful accumulator for memory-efficient incremental resource merging.
///
/// Accepts resources in chunks (as JSON strings or pre-parsed), merges them
/// progressively, and produces a final `BatchMergeResult`. Only the accumulated
/// `StaticResource` structs persist between chunks — input JSON strings can be
/// dropped by the caller after each `add_json` call.
///
/// Platform-agnostic: the caller controls where data comes from (files, network, etc.).
pub struct MergeAccumulator {
    accumulated: Vec<StaticResource>,
    warnings: Vec<String>,
    chunk_size: usize,
    strict: bool,
    pending: Vec<Vec<StaticResource>>,
    error: Option<String>,
}

impl MergeAccumulator {
    pub fn new(chunk_size: usize, strict: bool) -> Self {
        Self {
            accumulated: Vec::new(),
            warnings: Vec::new(),
            chunk_size: if chunk_size == 0 { 10 } else { chunk_size },
            strict,
            pending: Vec::new(),
            error: None,
        }
    }

    /// Feed a JSON string. The string is parsed and can be dropped by the caller afterward.
    /// Returns Err if parsing fails or a previous error was recorded.
    pub fn add_json(&mut self, json_str: &str) -> Result<(), String> {
        if let Some(ref e) = self.error {
            return Err(format!("Accumulator already in error state: {}", e));
        }
        let resources = parse_resources_from_json_str(json_str)?;
        self.pending.push(resources);
        if self.pending.len() >= self.chunk_size {
            self.flush()?;
        }
        Ok(())
    }

    /// Feed pre-parsed resources directly.
    pub fn add_resources(&mut self, resources: Vec<StaticResource>) -> Result<(), String> {
        if let Some(ref e) = self.error {
            return Err(format!("Accumulator already in error state: {}", e));
        }
        self.pending.push(resources);
        if self.pending.len() >= self.chunk_size {
            self.flush()?;
        }
        Ok(())
    }

    /// Merge pending batches into the accumulated result.
    fn flush(&mut self) -> Result<(), String> {
        if self.pending.is_empty() {
            return Ok(());
        }

        let mut batches: Vec<Vec<StaticResource>> = Vec::new();
        if !self.accumulated.is_empty() {
            batches.push(std::mem::take(&mut self.accumulated));
        }
        batches.append(&mut self.pending);

        let result = batch_merge_resources(batches, false, self.strict);

        self.warnings.extend(result.warnings);
        if let Some(error) = result.error {
            self.error = Some(error.clone());
            self.accumulated = result.resources;
            return Err(error);
        }
        self.accumulated = result.resources;
        Ok(())
    }

    /// Flush remaining pending batches, optionally recompute descriptors, and return the result.
    pub fn finish(mut self, recompute_descriptors: bool) -> BatchMergeResult {
        if let Err(e) = self.flush() {
            return BatchMergeResult {
                resources: self.accumulated,
                warnings: self.warnings,
                error: Some(e),
            };
        }

        if recompute_descriptors && !self.accumulated.is_empty() {
            let result = batch_merge_resources(
                vec![std::mem::take(&mut self.accumulated)],
                true,
                self.strict,
            );
            self.warnings.extend(result.warnings);
            if let Some(ref error) = result.error {
                return BatchMergeResult {
                    resources: result.resources,
                    warnings: self.warnings,
                    error: Some(error.clone()),
                };
            }
            self.accumulated = result.resources;
        }

        BatchMergeResult {
            resources: self.accumulated,
            warnings: self.warnings,
            error: None,
        }
    }
}

/// Batch merge resources from multiple sources, grouping by resourceinstanceid
///
/// Takes multiple collections of resources (e.g., from different JSON files or API responses),
/// groups all resources by their `resourceinstanceid`, and merges each group.
///
/// # Arguments
/// * `resource_batches` - Vector of resource collections to merge
/// * `recompute_descriptors` - If true, recomputes descriptors from tiles after merging
///   using the graph from the registry (looked up by graph_id from the resource)
///
/// # Returns
/// * `BatchMergeResult` - Contains merged resources (one per unique ID) and all warnings
///
/// # Example
/// ```ignore
/// // Process disjoint subgraphs from multiple files
/// let batch1: Vec<StaticResource> = parse_file("part1.json");
/// let batch2: Vec<StaticResource> = parse_file("part2.json");
/// let result = batch_merge_resources(vec![batch1, batch2], true);
/// // result.resources contains one entry per unique resourceinstanceid
/// ```
pub fn batch_merge_resources(
    resource_batches: Vec<Vec<StaticResource>>,
    recompute_descriptors: bool,
    strict: bool,
) -> BatchMergeResult {
    use crate::registry::get_graph;
    use crate::IndexedGraph;
    use std::collections::BTreeMap;

    // Group all resources by resourceinstanceid
    let mut grouped: BTreeMap<String, Vec<StaticResource>> = BTreeMap::new();

    for batch in resource_batches {
        for resource in batch {
            let id = resource.resourceinstance.resourceinstanceid.clone();
            grouped.entry(id).or_default().push(resource);
        }
    }

    let mut merged_resources = Vec::new();
    let mut all_warnings = Vec::new();

    // Cache IndexedGraphs by graph_id to avoid rebuilding for each resource
    let mut indexed_graphs: BTreeMap<String, IndexedGraph> = BTreeMap::new();

    // Merge each group
    for (resource_id, resources) in grouped {
        match merge_resources(resources) {
            Ok(result) => {
                // Prefix warnings with resource ID for clarity
                for warning in result.warnings {
                    all_warnings.push(format!("[{}] {}", resource_id, warning));
                }

                let mut resource = result.resource;
                let graph_id = resource.resourceinstance.graph_id.clone();

                // Get or create IndexedGraph for this graph_id (needed for both unification and descriptors)
                if !indexed_graphs.contains_key(&graph_id) {
                    if let Some(graph) = get_graph(&graph_id) {
                        indexed_graphs
                            .insert(graph_id.clone(), IndexedGraph::new((*graph).clone()));
                    }
                }

                // Unify cardinality-1 tiles if we have the graph
                if let Some(indexed) = indexed_graphs.get(&graph_id) {
                    if let Some(ref mut tiles) = resource.tiles {
                        match unify_cardinality_one_tiles(tiles, indexed, strict) {
                            Ok(unify_warnings) => {
                                for warning in unify_warnings {
                                    all_warnings.push(format!("[{}] {}", resource_id, warning));
                                }
                            }
                            Err(e) => {
                                all_warnings.push(format!("[{}] Unify error: {}", resource_id, e));
                                if strict {
                                    return BatchMergeResult {
                                        resources: merged_resources,
                                        warnings: all_warnings,
                                        error: Some(format!("[{}] {}", resource_id, e)),
                                    };
                                }
                            }
                        }
                    }
                }

                // Recompute descriptors if requested (graph already fetched above for unification)
                if recompute_descriptors {
                    if let Some(indexed) = indexed_graphs.get(&graph_id) {
                        // Compute descriptors from merged tiles with diagnostics
                        let tiles = resource.tiles.as_deref().unwrap_or(&[]);
                        let mut descriptor_warnings = Vec::new();
                        // Deserialize __cache so resource-instance placeholders can resolve to titles
                        let cache: Option<ResourceCache> = resource
                            .cache
                            .as_ref()
                            .and_then(|v| serde_json::from_value(v.clone()).ok());
                        let descriptors = indexed.build_descriptors_with_diagnostics(
                            tiles,
                            &mut descriptor_warnings,
                            cache.as_ref(),
                        );

                        // Add descriptor warnings with resource context
                        for warning in descriptor_warnings {
                            all_warnings.push(format!("[{}] Descriptor: {}", resource_id, warning));
                        }

                        // Update resource with computed descriptors
                        resource.resourceinstance.descriptors = descriptors.clone();

                        // Update name from descriptors if available
                        if let Some(ref name) = descriptors.name {
                            if !name.is_empty() {
                                resource.resourceinstance.name = name.clone();
                            }
                        }
                    } else {
                        all_warnings.push(format!(
                            "[{}] Graph not found in registry for descriptor computation: {}",
                            resource_id, graph_id
                        ));
                    }
                }

                merged_resources.push(resource);
            }
            Err(e) => {
                // This shouldn't happen since we grouped by ID, but handle gracefully
                all_warnings.push(format!("[{}] Merge error: {}", resource_id, e));
            }
        }
    }

    BatchMergeResult {
        resources: merged_resources,
        warnings: all_warnings,
        error: None,
    }
}

/// Type alias for tile data merge mapping: canonical_idx -> Vec<(source_tile_id, data)>
type TileDataMergeMap = HashMap<usize, Vec<(String, HashMap<String, serde_json::Value>)>>;

/// Unify tiles for cardinality-1 nodegroups and update parenttile_id references.
///
/// When merging resources from multiple sources, cardinality-1 nodegroups may end up
/// with multiple tiles (one from each source). This function:
/// 1. Identifies cardinality-1 nodegroups with multiple tiles
/// 2. Keeps the first tile as canonical, merges data from duplicates
/// 3. Updates parenttile_id references in child tiles to point to the canonical tile
/// 4. Warns if there are conflicting data values
///
/// # Arguments
/// * `tiles` - Mutable reference to the tiles vector
/// * `indexed_graph` - The indexed graph for looking up nodegroup cardinality
///
/// # Returns
/// * Vector of warning messages about unified tiles and data conflicts
pub fn unify_cardinality_one_tiles(
    tiles: &mut Vec<StaticTile>,
    indexed_graph: &crate::IndexedGraph,
    strict: bool,
) -> Result<Vec<String>, String> {
    use std::collections::BTreeMap;

    let mut warnings = Vec::new();

    // Group tile indices by (nodegroup_id, parenttile_id).
    // Cardinality-1 means one tile per parent context, not one tile total —
    // tiles under different parent tiles are separate instances and must not be unified.
    let mut tiles_by_context: BTreeMap<(String, Option<String>), Vec<usize>> = BTreeMap::new();
    for (idx, tile) in tiles.iter().enumerate() {
        tiles_by_context
            .entry((tile.nodegroup_id.clone(), tile.parenttile_id.clone()))
            .or_default()
            .push(idx);
    }

    // Build mapping of old_tile_id -> canonical_tile_id for cardinality-1 nodegroups
    let mut tile_redirect: HashMap<String, String> = HashMap::new();
    let mut tiles_to_remove: HashSet<usize> = HashSet::new();
    // Store data to merge: canonical_idx -> Vec<(source_tile_id, data)>
    let mut data_to_merge: TileDataMergeMap = HashMap::new();

    for ((nodegroup_id, _parent_tile_id), tile_indices) in &tiles_by_context {
        if tile_indices.len() <= 1 {
            continue; // No unification needed
        }

        // Check cardinality
        let nodegroup = match indexed_graph.graph.get_nodegroup_by_id(nodegroup_id) {
            Some(ng) => ng,
            None => continue,
        };

        let is_single = nodegroup
            .cardinality
            .as_ref()
            .map(|c| c != "n")
            .unwrap_or(true);

        if !is_single {
            continue; // cardinality-n, multiple tiles are allowed
        }

        // Cardinality-1 with multiple tiles under the same parent - need to unify
        let canonical_idx = tile_indices[0];
        let canonical_tile_id = tiles[canonical_idx].tileid.clone();

        for &idx in tile_indices.iter().skip(1) {
            let tile = &tiles[idx];
            let tile_id = tile
                .tileid
                .clone()
                .unwrap_or_else(|| format!("(index {})", idx));

            // Record tile redirect
            if let Some(ref old_tile_id) = tile.tileid {
                if let Some(ref canon_id) = canonical_tile_id {
                    tile_redirect.insert(old_tile_id.clone(), canon_id.clone());
                }
            }

            // Collect data to merge
            if !tile.data.is_empty() {
                data_to_merge
                    .entry(canonical_idx)
                    .or_default()
                    .push((tile_id, tile.data.clone()));
            }

            tiles_to_remove.insert(idx);
        }

        // Conflict and error warnings are emitted during the data merge below.
        // Routine unification (no conflicts) is silent.
    }

    // Merge data into canonical tiles
    for (canonical_idx, sources) in data_to_merge {
        let canonical_tile = &mut tiles[canonical_idx];
        let canonical_tile_id = canonical_tile
            .tileid
            .clone()
            .unwrap_or_else(|| format!("(index {})", canonical_idx));

        for (source_tile_id, source_data) in sources {
            for (key, value) in source_data {
                if let Some(existing) = canonical_tile.data.get(&key) {
                    if existing != &value {
                        let msg = format!(
                            "Data conflict in nodegroup '{}': key '{}' has different values in tiles '{}' and '{}'",
                            canonical_tile.nodegroup_id,
                            key,
                            canonical_tile_id,
                            source_tile_id
                        );
                        if strict {
                            return Err(msg);
                        }
                        warnings.push(format!("{} (keeping first)", msg));
                    }
                    // Keep existing value (first wins)
                } else {
                    // New key, add it
                    canonical_tile.data.insert(key, value);
                }
            }
        }
    }

    // Update parenttile_id references
    for tile in tiles.iter_mut() {
        if let Some(ref old_parent_id) = tile.parenttile_id {
            if let Some(new_parent_id) = tile_redirect.get(old_parent_id) {
                tile.parenttile_id = Some(new_parent_id.clone());
            }
        }
    }

    // Remove duplicate tiles (in reverse order to preserve indices)
    let mut indices: Vec<usize> = tiles_to_remove.into_iter().collect();
    indices.sort_by(|a, b| b.cmp(a)); // Reverse order
    for idx in indices {
        tiles.remove(idx);
    }

    Ok(warnings)
}

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

    #[test]
    fn test_static_resource_serialization() {
        let resource = StaticResource {
            resourceinstance: StaticResourceMetadata {
                descriptors: StaticResourceDescriptors::default(),
                graph_id: "test-graph".to_string(),
                name: "Test".to_string(),
                resourceinstanceid: "test-id".to_string(),
                publication_id: None,
                principaluser_id: None,
                legacyid: None,
                graph_publication_id: None,
                createdtime: None,
                lastmodified: None,
            },
            tiles: Some(vec![]),
            metadata: HashMap::new(),
            cache: None,
            scopes: None,
            tiles_loaded: None,
        };

        let json = serde_json::to_string_pretty(&resource).unwrap();
        println!("StaticResource JSON:\n{}", json);

        // Check that resourceinstance is nested
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(
            value.get("resourceinstance").is_some(),
            "Should have nested resourceinstance"
        );
    }

    fn make_test_resource(resource_id: &str, tile_ids: &[&str]) -> StaticResource {
        let tiles: Vec<StaticTile> = tile_ids
            .iter()
            .map(|id| StaticTile {
                tileid: Some(id.to_string()),
                nodegroup_id: "ng1".to_string(),
                resourceinstance_id: resource_id.to_string(),
                parenttile_id: None,
                data: HashMap::new(),
                provisionaledits: None,
                sortorder: None,
            })
            .collect();

        StaticResource {
            resourceinstance: StaticResourceMetadata {
                descriptors: StaticResourceDescriptors::default(),
                graph_id: "test-graph".to_string(),
                name: "Test".to_string(),
                resourceinstanceid: resource_id.to_string(),
                publication_id: None,
                principaluser_id: None,
                legacyid: None,
                graph_publication_id: None,
                createdtime: None,
                lastmodified: None,
            },
            tiles: Some(tiles),
            metadata: HashMap::new(),
            cache: None,
            scopes: None,
            tiles_loaded: None,
        }
    }

    #[test]
    fn test_merge_resources_basic() {
        let r1 = make_test_resource("res-1", &["tile-a", "tile-b"]);
        let r2 = make_test_resource("res-1", &["tile-c", "tile-d"]);

        let result = merge_resources(vec![r1, r2]).unwrap();

        assert_eq!(result.resource.resourceinstance.resourceinstanceid, "res-1");
        let tiles = result.resource.tiles.unwrap();
        assert_eq!(tiles.len(), 4);
        assert!(result.warnings.is_empty());
    }

    #[test]
    fn test_merge_resources_duplicate_detection() {
        let r1 = make_test_resource("res-1", &["tile-a", "tile-b"]);
        let r2 = make_test_resource("res-1", &["tile-b", "tile-c"]); // tile-b is duplicate

        let result = merge_resources(vec![r1, r2]).unwrap();

        let tiles = result.resource.tiles.unwrap();
        assert_eq!(tiles.len(), 3); // tile-b counted once
        assert!(result.warnings.is_empty()); // duplicate skipping is silent
    }

    #[test]
    fn test_merge_resources_id_mismatch() {
        let r1 = make_test_resource("res-1", &["tile-a"]);
        let r2 = make_test_resource("res-2", &["tile-b"]); // Different ID

        let result = merge_resources(vec![r1, r2]);

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("mismatch"));
    }

    #[test]
    fn test_merge_resources_empty() {
        let result = merge_resources(vec![]);

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No resources"));
    }

    #[test]
    fn test_merge_resources_preserves_cache() {
        // Create resources with cache entries
        let mut r1 = make_test_resource("res-1", &["tile-a"]);
        let mut r2 = make_test_resource("res-1", &["tile-b"]);

        // Set up cache for r1: tileId -> nodeId -> entry
        let mut cache1: ResourceCache = HashMap::new();
        let mut tile_a_entries: HashMap<String, CacheEntry> = HashMap::new();
        tile_a_entries.insert(
            "node-1".to_string(),
            CacheEntry::Single(RelatedResourceEntry {
                datatype: "resource-instance".to_string(),
                id: "related-1".to_string(),
                resource_type: "TestModel".to_string(),
                graph_id: "graph-a".to_string(),
                title: Some("Related 1".to_string()),
                descriptors: None,
                meta: None,
            }),
        );
        tile_a_entries.insert(
            "node-2".to_string(),
            CacheEntry::Single(RelatedResourceEntry {
                datatype: "resource-instance".to_string(),
                id: "related-2".to_string(),
                resource_type: "TestModel".to_string(),
                graph_id: "graph-a".to_string(),
                title: Some("Related 2".to_string()),
                descriptors: None,
                meta: None,
            }),
        );
        cache1.insert("tile-a".to_string(), tile_a_entries);
        r1.cache = serde_json::to_value(&cache1).ok();

        // Set up cache for r2 with overlapping tile/node and new entries
        let mut cache2: ResourceCache = HashMap::new();
        let mut tile_a_entries_2: HashMap<String, CacheEntry> = HashMap::new();
        tile_a_entries_2.insert(
            "node-2".to_string(),
            CacheEntry::Single(RelatedResourceEntry {
                datatype: "resource-instance".to_string(),
                id: "related-2".to_string(),
                resource_type: "TestModel".to_string(),
                graph_id: "graph-a".to_string(),
                title: Some("Related 2 - Different Name".to_string()), // Should be ignored (first wins)
                descriptors: None,
                meta: None,
            }),
        );
        cache2.insert("tile-a".to_string(), tile_a_entries_2);

        let mut tile_b_entries: HashMap<String, CacheEntry> = HashMap::new();
        tile_b_entries.insert(
            "node-3".to_string(),
            CacheEntry::Single(RelatedResourceEntry {
                datatype: "resource-instance".to_string(),
                id: "related-3".to_string(),
                resource_type: "OtherModel".to_string(),
                graph_id: "graph-b".to_string(),
                title: Some("Related 3".to_string()),
                descriptors: None,
                meta: None,
            }),
        );
        cache2.insert("tile-b".to_string(), tile_b_entries);
        r2.cache = serde_json::to_value(&cache2).ok();

        let result = merge_resources(vec![r1, r2]).unwrap();

        // Check that cache was preserved
        assert!(result.resource.cache.is_some(), "Cache should be present");

        let merged_cache: ResourceCache =
            serde_json::from_value(result.resource.cache.unwrap()).unwrap();

        // Should have 2 tiles (tile-a, tile-b)
        assert_eq!(merged_cache.len(), 2);
        assert!(merged_cache.contains_key("tile-a"));
        assert!(merged_cache.contains_key("tile-b"));

        // tile-a should have 2 entries (node-1, node-2)
        let tile_a = merged_cache.get("tile-a").unwrap();
        assert_eq!(tile_a.len(), 2);
        assert!(tile_a.contains_key("node-1"));
        assert!(tile_a.contains_key("node-2"));

        // node-2 in tile-a should have the first resource's version (first wins)
        if let CacheEntry::Single(entry) = tile_a.get("node-2").unwrap() {
            assert_eq!(entry.title.as_deref(), Some("Related 2"));
        } else {
            panic!("Expected CacheEntry::Single");
        }

        // tile-b should have 1 entry (node-3)
        let tile_b = merged_cache.get("tile-b").unwrap();
        assert_eq!(tile_b.len(), 1);
        assert!(tile_b.contains_key("node-3"));
    }
}