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
//! StaticGraph and IndexedGraph types.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

use super::cards::{StaticCard, StaticCardsXNodesXWidgets, StaticFunctionsXGraphs};
use super::descriptors::{DescriptorConfig, StaticResourceDescriptors, DESCRIPTOR_FUNCTION_ID};
use super::nodes::{StaticEdge, StaticNode, StaticNodegroup};
use super::tile::StaticTile;
use super::translatable::StaticTranslatableString;

/// Wrapper for loading from JSON files with {graph: [...]} structure
#[derive(Debug, Deserialize)]
pub struct GraphWrapper {
    pub graph: Vec<StaticGraph>,
}

/// The main graph structure containing nodes, edges, and metadata
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StaticGraph {
    pub graphid: String,
    pub name: StaticTranslatableString,
    #[serde(default)]
    pub author: Option<String>,
    #[serde(default)]
    pub subtitle: Option<StaticTranslatableString>,
    #[serde(default)]
    pub description: Option<StaticTranslatableString>,
    pub nodes: Vec<StaticNode>,
    #[serde(default)]
    pub nodegroups: Vec<StaticNodegroup>,
    #[serde(default)]
    pub edges: Vec<StaticEdge>,
    pub root: StaticNode,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(default)]
    pub iconclass: Option<String>,
    #[serde(default)]
    pub color: Option<String>,
    #[serde(default)]
    pub isresource: Option<bool>,
    #[serde(default)]
    pub slug: Option<String>,
    #[serde(default)]
    pub is_editable: Option<bool>,
    /// Ontology IDs used by this graph. Accepts a single string or an array
    /// of strings on the wire; a single-element list is serialised as a plain
    /// string for round-trip compatibility with upstream Arches.
    #[serde(default, with = "super::serde_helpers::optional_string_or_vec")]
    pub ontology_id: Option<Vec<String>>,
    #[serde(default)]
    pub template_id: Option<String>,
    #[serde(default)]
    pub deploymentdate: Option<String>,
    #[serde(default)]
    pub deploymentfile: Option<String>,
    #[serde(default)]
    pub jsonldcontext: Option<String>,
    #[serde(default)]
    pub config: serde_json::Value,
    #[serde(default)]
    pub relatable_resource_model_ids: Vec<String>,
    #[serde(default)]
    pub publication: Option<serde_json::Value>,
    #[serde(default)]
    pub resource_2_resource_constraints: Option<Vec<serde_json::Value>>,

    // Arches-HER 2.0+ fields (backwards-compatible with older formats)
    /// Source identifier for import/export tracking
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_identifier_id: Option<String>,
    /// Whether graph is active
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// Whether graph has unpublished changes
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub has_unpublished_changes: Option<bool>,
    /// Whether copy is immutable
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_copy_immutable: Option<bool>,
    /// Resource instance lifecycle configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_instance_lifecycle: Option<serde_json::Value>,
    /// Spatial views configuration
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spatial_views: Option<serde_json::Value>,
    /// Group permissions
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_permissions: Option<serde_json::Value>,
    /// User permissions
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_permissions: Option<serde_json::Value>,

    // UI-specific fields
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cards: Option<Vec<StaticCard>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cards_x_nodes_x_widgets: Option<Vec<StaticCardsXNodesXWidgets>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub functions_x_graphs: Option<Vec<StaticFunctionsXGraphs>>,

    // Internal lookup tables (not serialized)
    #[serde(skip)]
    node_by_id: Option<HashMap<String, usize>>,
    #[serde(skip)]
    node_by_alias: Option<HashMap<String, usize>>,
    #[serde(skip)]
    edges_map: Option<HashMap<String, Vec<String>>>,
    #[serde(skip)]
    nodes_by_nodegroup: Option<HashMap<String, Vec<usize>>>,
    #[serde(skip)]
    nodegroup_by_id: Option<HashMap<String, usize>>,
    // Arc-wrapped node caches for pseudo_value infrastructure (avoids cloning on every conversion)
    #[serde(skip)]
    nodes_by_alias_arc: Option<HashMap<String, Arc<StaticNode>>>,
    // Card hierarchy index (built when cards are present)
    #[serde(skip)]
    card_index: Option<super::card_index::CardIndex>,
}

impl StaticGraph {
    /// Load a graph from a JSON string
    /// Handles both direct graph objects and wrapped format: {"graph": [...]}
    pub fn from_json_string(json_str: &str) -> Result<StaticGraph, String> {
        // Try parsing as a direct StaticGraph first
        if let Ok(mut graph) = serde_json::from_str::<StaticGraph>(json_str) {
            graph.build_indices();
            return Ok(graph);
        }

        // Fall back to wrapped format {graph: [...]}
        let wrapper: GraphWrapper =
            serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;
        let mut graph = wrapper
            .graph
            .into_iter()
            .next()
            .ok_or_else(|| "No graphs found in JSON".to_string())?;
        graph.build_indices();
        Ok(graph)
    }

    /// Build the internal lookup indices
    pub fn build_indices(&mut self) {
        let mut node_by_id = HashMap::new();
        let mut node_by_alias = HashMap::new();
        let mut nodes_by_nodegroup: HashMap<String, Vec<usize>> = HashMap::new();

        for (idx, node) in self.nodes.iter().enumerate() {
            node_by_id.insert(node.nodeid.clone(), idx);
            if let Some(ref alias) = node.alias {
                if !alias.is_empty() {
                    node_by_alias.insert(alias.clone(), idx);
                }
            }
            if let Some(ref ng_id) = node.nodegroup_id {
                if !ng_id.is_empty() {
                    nodes_by_nodegroup
                        .entry(ng_id.clone())
                        .or_default()
                        .push(idx);
                }
            }
        }

        // Build edges map (parent_nodeid -> child_nodeids)
        let mut edges_map: HashMap<String, Vec<String>> = HashMap::new();
        for edge in &self.edges {
            edges_map
                .entry(edge.domainnode_id.clone())
                .or_default()
                .push(edge.rangenode_id.clone());
        }

        // Build nodegroup index
        let mut nodegroup_by_id = HashMap::new();
        for (idx, ng) in self.nodegroups.iter().enumerate() {
            nodegroup_by_id.insert(ng.nodegroupid.clone(), idx);
        }

        // Build Arc-wrapped nodes_by_alias for pseudo_value infrastructure
        let nodes_by_alias_arc: HashMap<String, Arc<StaticNode>> = self
            .nodes
            .iter()
            .filter_map(|n| {
                n.alias
                    .as_ref()
                    .filter(|a| !a.is_empty())
                    .map(|a| (a.clone(), Arc::new(n.clone())))
            })
            .collect();

        self.node_by_id = Some(node_by_id);
        self.node_by_alias = Some(node_by_alias);
        self.edges_map = Some(edges_map);
        self.nodes_by_nodegroup = Some(nodes_by_nodegroup);
        self.nodegroup_by_id = Some(nodegroup_by_id);
        self.nodes_by_alias_arc = Some(nodes_by_alias_arc);

        // Build card index when cards are present
        if self.cards.is_some() {
            self.card_index = Some(super::card_index::build_card_index(
                self.cards_slice(),
                self.cards_x_nodes_x_widgets_slice(),
                &self.nodegroups,
                &self.nodes,
                crate::graph_mutator::get_widget_name_by_id,
            ));
        }
    }

    /// Invalidate all internal lookup indices.
    ///
    /// This must be called after mutations that modify the nodes vector,
    /// especially operations like `retain()` that shift element positions.
    pub fn invalidate_indices(&mut self) {
        self.node_by_id = None;
        self.node_by_alias = None;
        self.edges_map = None;
        self.nodes_by_nodegroup = None;
        self.nodegroup_by_id = None;
        self.nodes_by_alias_arc = None;
        self.card_index = None;
    }

    /// Get the root node
    pub fn get_root(&self) -> &StaticNode {
        &self.root
    }

    /// Get node by index
    pub fn get_node_by_index(&self, idx: usize) -> Option<&StaticNode> {
        self.nodes.get(idx)
    }

    /// Get node by ID
    pub fn get_node_by_id(&self, id: &str) -> Option<&StaticNode> {
        self.node_by_id
            .as_ref()?
            .get(id)
            .and_then(|&idx| self.nodes.get(idx))
    }

    /// Get node by alias
    pub fn get_node_by_alias(&self, alias: &str) -> Option<&StaticNode> {
        self.node_by_alias
            .as_ref()?
            .get(alias)
            .and_then(|&idx| self.nodes.get(idx))
    }

    /// Get display name
    pub fn display_name(&self) -> String {
        self.name.to_string_default()
    }

    /// Get subtitle
    pub fn display_subtitle(&self) -> String {
        self.subtitle
            .as_ref()
            .map(|s| s.to_string_default())
            .unwrap_or_default()
    }

    /// Get author
    pub fn display_author(&self) -> String {
        self.author.clone().unwrap_or_default()
    }

    /// Get nodes slice
    pub fn nodes_slice(&self) -> &[StaticNode] {
        &self.nodes
    }

    /// Get nodegroups slice
    pub fn nodegroups_slice(&self) -> &[StaticNodegroup] {
        &self.nodegroups
    }

    /// Get edges slice
    pub fn edges_slice(&self) -> &[StaticEdge] {
        &self.edges
    }

    /// Get root node
    pub fn root_node(&self) -> &StaticNode {
        &self.root
    }

    /// Get graph ID
    pub fn graph_id(&self) -> &str {
        &self.graphid
    }

    /// Get the model class name for this graph.
    ///
    /// This returns the graph's display name, which is used as the
    /// ResourceInstanceCacheEntry "type" field in TypeScript.
    pub fn get_model_class_name(&self) -> Option<String> {
        let name = self.name.to_string_default();
        if name.is_empty() {
            None
        } else {
            Some(name)
        }
    }

    /// Get edges map (parent_nodeid -> child_nodeids)
    /// Returns None if indices haven't been built
    pub fn edges_map(&self) -> Option<&HashMap<String, Vec<String>>> {
        self.edges_map.as_ref()
    }

    /// Get child node IDs for a given node
    pub fn get_child_ids(&self, node_id: &str) -> Option<&Vec<String>> {
        self.edges_map.as_ref()?.get(node_id)
    }

    /// Get nodes by nodegroup (nodegroup_id -> node indices)
    /// Returns None if indices haven't been built
    pub fn nodes_by_nodegroup(&self) -> Option<&HashMap<String, Vec<usize>>> {
        self.nodes_by_nodegroup.as_ref()
    }

    /// Get nodes in a specific nodegroup
    pub fn get_nodes_in_nodegroup(&self, nodegroup_id: &str) -> Vec<&StaticNode> {
        self.nodes_by_nodegroup
            .as_ref()
            .and_then(|map| map.get(nodegroup_id))
            .map(|indices| {
                indices
                    .iter()
                    .filter_map(|&idx| self.nodes.get(idx))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get nodegroup by ID
    pub fn get_nodegroup_by_id(&self, nodegroup_id: &str) -> Option<&StaticNodegroup> {
        self.nodegroup_by_id
            .as_ref()?
            .get(nodegroup_id)
            .and_then(|&idx| self.nodegroups.get(idx))
    }

    /// Get Arc-wrapped nodes by alias map (for pseudo_value infrastructure)
    /// Returns None if indices haven't been built
    pub fn nodes_by_alias_arc(&self) -> Option<&HashMap<String, Arc<StaticNode>>> {
        self.nodes_by_alias_arc.as_ref()
    }

    /// Get Arc-wrapped node by alias
    pub fn get_node_arc_by_alias(&self, alias: &str) -> Option<Arc<StaticNode>> {
        self.nodes_by_alias_arc.as_ref()?.get(alias).cloned()
    }

    // =========================================================================
    // Mutation Methods (for GraphMutator)
    // =========================================================================

    /// Create a deep clone of the graph with fresh indices
    pub fn deep_clone(&self) -> Self {
        let mut cloned = self.clone();
        cloned.build_indices();
        cloned
    }

    /// Push a new node to the graph
    ///
    /// Note: You must call `build_indices()` after all mutations to rebuild lookup tables.
    pub fn push_node(&mut self, node: StaticNode) {
        self.nodes.push(node);
        self.invalidate_indices();
    }

    /// Push a new edge to the graph
    pub fn push_edge(&mut self, edge: StaticEdge) {
        self.edges.push(edge);
        self.edges_map = None;
    }

    /// Push a new nodegroup to the graph
    pub fn push_nodegroup(&mut self, nodegroup: StaticNodegroup) {
        self.nodegroups.push(nodegroup);
        self.nodegroup_by_id = None;
    }

    /// Push a new card to the graph
    pub fn push_card(&mut self, card: StaticCard) {
        if self.cards.is_none() {
            self.cards = Some(Vec::new());
        }
        if let Some(ref mut cards) = self.cards {
            cards.push(card);
        }
    }

    /// Push a new cards_x_nodes_x_widgets entry
    pub fn push_card_x_node_x_widget(&mut self, cxnxw: StaticCardsXNodesXWidgets) {
        if self.cards_x_nodes_x_widgets.is_none() {
            self.cards_x_nodes_x_widgets = Some(Vec::new());
        }
        if let Some(ref mut cxnxw_list) = self.cards_x_nodes_x_widgets {
            cxnxw_list.push(cxnxw);
        }
    }

    /// Get cards slice (for mutation checks)
    pub fn cards_slice(&self) -> &[StaticCard] {
        self.cards.as_deref().unwrap_or(&[])
    }

    /// Get the card hierarchy index (None if graph has no cards)
    pub fn card_index(&self) -> Option<&super::card_index::CardIndex> {
        self.card_index.as_ref()
    }

    /// Get cards_x_nodes_x_widgets slice
    pub fn cards_x_nodes_x_widgets_slice(&self) -> &[StaticCardsXNodesXWidgets] {
        self.cards_x_nodes_x_widgets.as_deref().unwrap_or(&[])
    }

    /// Find a card by nodegroup_id
    pub fn find_card_by_nodegroup(&self, nodegroup_id: &str) -> Option<&StaticCard> {
        self.cards
            .as_ref()?
            .iter()
            .find(|c| c.nodegroup_id == nodegroup_id)
    }

    /// Find a node by alias (without requiring indices to be built)
    pub fn find_node_by_alias(&self, alias: &str) -> Option<&StaticNode> {
        // Try indexed lookup first
        if let Some(node) = self.get_node_by_alias(alias) {
            return Some(node);
        }
        // Fall back to linear search
        self.nodes
            .iter()
            .find(|n| n.alias.as_deref() == Some(alias))
    }

    /// Get a simplified schema view of the graph showing node aliases and structure.
    ///
    /// Returns a nested structure representing the tree with:
    /// - Keys are node aliases (or nodeid if no alias)
    /// - Values contain 'datatype', 'nodeid', optionally 'required', and 'children'
    ///
    /// Useful for understanding what keys are available in tree output.
    pub fn get_schema(&self) -> serde_json::Value {
        // Build a map from nodeid to node for quick lookup
        let node_map: HashMap<&str, &StaticNode> =
            self.nodes.iter().map(|n| (n.nodeid.as_str(), n)).collect();

        // Build parent -> children map based on edges
        let mut children_map: HashMap<&str, Vec<&str>> = HashMap::new();
        for edge in &self.edges {
            children_map
                .entry(edge.domainnode_id.as_str())
                .or_default()
                .push(&edge.rangenode_id);
        }

        // Recursive function to build node schema
        fn build_node_schema(
            nodeid: &str,
            node_map: &HashMap<&str, &StaticNode>,
            children_map: &HashMap<&str, Vec<&str>>,
        ) -> serde_json::Value {
            let node = match node_map.get(nodeid) {
                Some(n) => n,
                None => return serde_json::json!({}),
            };

            let mut schema = serde_json::json!({
                "datatype": node.datatype,
                "nodeid": node.nodeid,
            });

            if node.isrequired {
                schema["required"] = serde_json::json!(true);
            }

            // Add children recursively
            if let Some(child_ids) = children_map.get(nodeid) {
                let mut children = serde_json::Map::new();
                for child_id in child_ids {
                    if let Some(child_node) = node_map.get(child_id) {
                        let key = child_node.alias.as_deref().unwrap_or(&child_node.nodeid);
                        children.insert(
                            key.to_string(),
                            build_node_schema(child_id, node_map, children_map),
                        );
                    }
                }
                if !children.is_empty() {
                    schema["children"] = serde_json::Value::Object(children);
                }
            }

            schema
        }

        // Start from root node and build tree
        let root_id = &self.root.nodeid;
        let mut root_schema = serde_json::Map::new();

        if let Some(child_ids) = children_map.get(root_id.as_str()) {
            for child_id in child_ids {
                if let Some(child_node) = node_map.get(child_id) {
                    let key = child_node.alias.as_deref().unwrap_or(&child_node.nodeid);
                    root_schema.insert(
                        key.to_string(),
                        build_node_schema(child_id, &node_map, &children_map),
                    );
                }
            }
        }

        serde_json::Value::Object(root_schema)
    }

    /// Set a descriptor template for a given descriptor type (e.g. "slug", "name").
    ///
    /// The `nodegroup_id` is inferred from the `<Node Name>` placeholders in the
    /// template by looking up nodes in the graph. All placeholder nodes must belong
    /// to exactly one nodegroup — returns an error otherwise.
    ///
    /// Creates or updates the descriptor function entry in `functions_x_graphs`.
    pub fn set_descriptor_template(
        &mut self,
        descriptor_type: &str,
        string_template: &str,
    ) -> Result<(), String> {
        use crate::graph::descriptors::DESCRIPTOR_FUNCTION_ID;
        use crate::graph::StaticFunctionsXGraphs;
        use std::collections::HashSet;

        let fxg = self.functions_x_graphs.get_or_insert_with(Vec::new);

        // Find existing descriptor function entry:
        // 1. Non-default function with empty/null config (just added via add_function,
        //    intended to replace the default descriptor — e.g. multicard descriptor)
        // 2. Non-default function that already has descriptor_types config
        // 3. Exact match on the default descriptor function ID
        let idx = fxg
            .iter()
            .position(|f| {
                f.function_id != DESCRIPTOR_FUNCTION_ID
                    && (f.config.is_null() || f.config == serde_json::json!({}))
            })
            .or_else(|| {
                fxg.iter().position(|f| {
                    f.function_id != DESCRIPTOR_FUNCTION_ID
                        && f.config
                            .as_object()
                            .is_some_and(|c| c.contains_key("descriptor_types"))
                })
            })
            .or_else(|| {
                fxg.iter()
                    .position(|f| f.function_id == DESCRIPTOR_FUNCTION_ID)
            });

        let is_default_function = idx
            .map(|i| fxg[i].function_id == DESCRIPTOR_FUNCTION_ID)
            .unwrap_or(true); // will create default if no match

        // Non-default functions (e.g. multicard descriptor) resolve templates
        // at runtime using node aliases — alizarin stores the template verbatim
        // with empty nodegroup_id. Default function requires name-based resolution
        // to a single nodegroup at build time.
        let entry = if is_default_function {
            let placeholders = IndexedGraph::extract_placeholders(string_template);
            if placeholders.is_empty() {
                return Err(format!(
                    "Template '{}' has no <Node Name> placeholders",
                    string_template
                ));
            }

            let mut nodegroup_ids = HashSet::new();
            for placeholder in &placeholders {
                let node_name = placeholder.trim_start_matches('<').trim_end_matches('>');
                let node = self
                    .nodes
                    .iter()
                    .find(|n| n.name == node_name)
                    .ok_or_else(|| {
                        format!("Node '{}' from template not found in graph", node_name)
                    })?;
                let ng_id = node
                    .nodegroup_id
                    .as_ref()
                    .ok_or_else(|| format!("Node '{}' has no nodegroup_id", node_name))?;
                nodegroup_ids.insert(ng_id.clone());
            }

            if nodegroup_ids.len() != 1 && descriptor_type != "slug" {
                return Err(format!(
                    "Template placeholders span {} nodegroups ({:?}), expected exactly 1",
                    nodegroup_ids.len(),
                    nodegroup_ids
                ));
            }

            let nodegroup_id = nodegroup_ids.into_iter().next().unwrap();
            serde_json::json!({
                "nodegroup_id": nodegroup_id,
                "string_template": string_template,
            })
        } else {
            // Non-default: store template as-is with empty nodegroup_id.
            // The function resolves aliases at runtime.
            serde_json::json!({
                "nodegroup_id": "",
                "string_template": string_template,
            })
        };

        let existing = idx.map(|i| &mut fxg[i]);

        if let Some(func) = existing {
            let needs_seed = !func.config.is_object()
                || !func
                    .config
                    .as_object()
                    .is_some_and(|c| c.contains_key("descriptor_types"));
            if needs_seed && !is_default_function {
                // Seed all descriptor types with empty defaults for non-default functions
                func.config = serde_json::json!({
                    "descriptor_types": {
                        "name": {"nodegroup_id": "", "string_template": ""},
                        "description": {"nodegroup_id": "", "string_template": ""},
                        "map_popup": {"nodegroup_id": "", "string_template": ""},
                    }
                });
            } else if !func.config.is_object() {
                func.config = serde_json::json!({"descriptor_types": {}});
            }
            let config = func.config.as_object_mut().unwrap();
            let dt = config
                .entry("descriptor_types")
                .or_insert_with(|| serde_json::json!({}));
            if let Some(dt_obj) = dt.as_object_mut() {
                dt_obj.insert(descriptor_type.to_string(), entry);
            }
        } else {
            let mut dt_map = serde_json::Map::new();
            dt_map.insert(descriptor_type.to_string(), entry);
            fxg.push(StaticFunctionsXGraphs {
                config: serde_json::json!({ "descriptor_types": dt_map }),
                function_id: DESCRIPTOR_FUNCTION_ID.to_string(),
                graph_id: self.graphid.clone(),
                id: crate::graph_mutator::generate_uuid_v5(
                    ("function", Some(&self.graphid)),
                    DESCRIPTOR_FUNCTION_ID,
                ),
            });
        }

        Ok(())
    }
}

/// Graph with precomputed indices for efficient tree traversal
pub struct IndexedGraph {
    pub graph: StaticGraph,
    /// node_id -> StaticNode
    pub nodes_by_id: HashMap<String, StaticNode>,
    /// node_id -> [child_node_ids]
    pub children_by_node: HashMap<String, Vec<String>>,
    /// alias -> StaticNode
    pub nodes_by_alias: HashMap<String, StaticNode>,
    /// nodegroup_id -> StaticNodegroup
    pub nodegroups_by_id: HashMap<String, StaticNodegroup>,
}

impl IndexedGraph {
    /// Create an indexed graph from a StaticGraph
    pub fn new(graph: StaticGraph) -> Self {
        let mut nodes_by_id = HashMap::new();
        let mut nodes_by_alias = HashMap::new();
        let mut children_by_node: HashMap<String, Vec<String>> = HashMap::new();
        let mut nodegroups_by_id = HashMap::new();

        // Index nodes by ID and alias
        for node in &graph.nodes {
            nodes_by_id.insert(node.nodeid.clone(), node.clone());
            if let Some(ref alias) = node.alias {
                if !alias.is_empty() {
                    nodes_by_alias.insert(alias.clone(), node.clone());
                }
            }
        }

        // Index edges (domainnode_id -> rangenode_id)
        for edge in &graph.edges {
            children_by_node
                .entry(edge.domainnode_id.clone())
                .or_default()
                .push(edge.rangenode_id.clone());
        }

        // Index nodegroups
        for ng in &graph.nodegroups {
            nodegroups_by_id.insert(ng.nodegroupid.clone(), ng.clone());
        }

        IndexedGraph {
            graph,
            nodes_by_id,
            nodes_by_alias,
            children_by_node,
            nodegroups_by_id,
        }
    }

    /// Get root node
    pub fn get_root(&self) -> &StaticNode {
        self.graph.get_root()
    }

    /// Get node by ID
    pub fn get_node(&self, node_id: &str) -> Option<&StaticNode> {
        self.nodes_by_id.get(node_id)
    }

    /// Get node by alias
    pub fn get_node_by_alias(&self, alias: &str) -> Option<&StaticNode> {
        self.nodes_by_alias.get(alias)
    }

    /// Get child nodes for a given node ID
    pub fn get_children(&self, node_id: &str) -> Vec<&StaticNode> {
        self.children_by_node
            .get(node_id)
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| self.nodes_by_id.get(id))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get child node IDs for a given node
    pub fn get_child_ids(&self, node_id: &str) -> Vec<&String> {
        self.children_by_node
            .get(node_id)
            .map(|v| v.iter().collect())
            .unwrap_or_default()
    }

    /// Check if a node has children
    pub fn has_children(&self, node_id: &str) -> bool {
        self.children_by_node
            .get(node_id)
            .map(|v| !v.is_empty())
            .unwrap_or(false)
    }

    /// Get the nodegroup for a node
    pub fn get_nodegroup(&self, node: &StaticNode) -> Option<&StaticNodegroup> {
        node.nodegroup_id
            .as_ref()
            .and_then(|id| self.nodegroups_by_id.get(id))
    }

    /// Build resource descriptors from tiles using graph configuration
    ///
    /// This replaces the TypeScript buildResourceDescriptors function, making
    /// descriptor computation completely platform-independent.
    ///
    /// # Arguments
    /// * `tiles` - The resource tiles containing data values
    ///
    /// # Returns
    /// Populated StaticResourceDescriptors with name, description, map_popup fields
    pub fn build_descriptors(&self, tiles: &[StaticTile]) -> StaticResourceDescriptors {
        self.build_descriptors_with_context(tiles, &mut Vec::new(), None, None)
    }

    /// Build descriptors with diagnostic warnings for silent failure cases
    pub fn build_descriptors_with_diagnostics(
        &self,
        tiles: &[StaticTile],
        warnings: &mut Vec<String>,
        cache: Option<&super::resources::ResourceCache>,
    ) -> StaticResourceDescriptors {
        self.build_descriptors_with_context(tiles, warnings, cache, None)
    }

    /// Build descriptors with full context (diagnostics, cache, extension registry)
    pub fn build_descriptors_with_context(
        &self,
        tiles: &[StaticTile],
        warnings: &mut Vec<String>,
        cache: Option<&super::resources::ResourceCache>,
        extension_registry: Option<&crate::extension_type_registry::ExtensionTypeRegistry>,
    ) -> StaticResourceDescriptors {
        // Get descriptor config from graph with diagnostics
        let config = match self.get_descriptor_config_with_diagnostics(warnings) {
            Some(c) => c,
            None => {
                // Warning already added by get_descriptor_config_with_diagnostics
                return StaticResourceDescriptors::default();
            }
        };

        let mut descriptors = StaticResourceDescriptors::default();

        // Process each descriptor type (name, description, map_popup)
        for (descriptor_type, type_config) in &config.descriptor_types {
            let mut template = type_config.string_template.clone();

            // Extract placeholders from template (e.g., <Node Name>)
            let placeholders = Self::extract_placeholders(&template);
            if placeholders.is_empty() {
                warnings.push(format!(
                    "Descriptor '{}': No placeholders found in template '{}'",
                    descriptor_type, template
                ));
                continue;
            }

            // Replace each placeholder with actual value from tiles
            for placeholder in &placeholders {
                let node_name = placeholder.trim_start_matches('<').trim_end_matches('>');

                if let Some(node) = self.find_node_by_name(node_name) {
                    let node_ng = match node.nodegroup_id.as_ref() {
                        Some(ng) => ng,
                        None => {
                            warnings.push(format!(
                                "Descriptor '{}': Node '{}' has no nodegroup_id",
                                descriptor_type, node_name
                            ));
                            continue;
                        }
                    };
                    let node_tiles: Vec<&StaticTile> = tiles
                        .iter()
                        .filter(|t| &t.nodegroup_id == node_ng)
                        .collect();
                    if let Some(value) = Self::extract_display_value_from_tiles(
                        &node_tiles,
                        &node.nodeid,
                        &node.datatype,
                        cache,
                        extension_registry,
                    ) {
                        template = template.replace(placeholder, &value);
                    } else {
                        let available_keys: Vec<_> =
                            node_tiles.iter().flat_map(|t| t.data.keys()).collect();
                        warnings.push(format!(
                            "Descriptor '{}': No value found for node '{}' (nodeid '{}') in tiles. Available data keys: {:?}",
                            descriptor_type, node_name, node.nodeid, available_keys
                        ));
                    }
                } else {
                    warnings.push(format!(
                        "Descriptor '{}': Node '{}' not found in graph",
                        descriptor_type, node_name
                    ));
                }
            }

            // Assign to appropriate descriptor field
            match descriptor_type.as_str() {
                "name" => descriptors.name = Some(template),
                "description" => descriptors.description = Some(template),
                "map_popup" => descriptors.map_popup = Some(template),
                "slug" => {
                    descriptors.slug =
                        Some(crate::graph_mutator::slugify(&template).replace('_', "-"))
                }
                _ => {} // Unknown descriptor type, ignore
            }
        }

        descriptors
    }

    /// Extract descriptor config with diagnostic warnings
    fn get_descriptor_config_with_diagnostics(
        &self,
        warnings: &mut Vec<String>,
    ) -> Option<DescriptorConfig> {
        let functions_x_graphs = match self.graph.functions_x_graphs.as_ref() {
            Some(fxg) => fxg,
            None => {
                warnings.push("Graph has no functions_x_graphs array".to_string());
                return None;
            }
        };

        // Find descriptor function: exact match on default ID, or any function
        // with descriptor_types config (e.g. Multi-card Resource Descriptor).
        let descriptor_func = functions_x_graphs
            .iter()
            .find(|f| f.function_id == DESCRIPTOR_FUNCTION_ID)
            .or_else(|| {
                functions_x_graphs.iter().find(|f| {
                    f.config
                        .as_object()
                        .is_some_and(|c| c.contains_key("descriptor_types"))
                })
            });

        if let Some(func) = descriptor_func {
            match serde_json::from_value::<DescriptorConfig>(func.config.clone()) {
                Ok(config) => return Some(config),
                Err(e) => {
                    warnings.push(format!(
                        "Failed to parse descriptor config: {}. Raw config: {}",
                        e,
                        serde_json::to_string(&func.config).unwrap_or_default()
                    ));
                    return None;
                }
            }
        }

        warnings.push(format!(
            "No descriptor function found in functions_x_graphs (looking for function_id {} or descriptor_types config). Available function_ids: {:?}",
            DESCRIPTOR_FUNCTION_ID,
            functions_x_graphs.iter().map(|f| &f.function_id).collect::<Vec<_>>()
        ));
        None
    }

    /// Extract placeholders from template using regex pattern
    /// Finds patterns like <Node Name> in the template string
    pub fn extract_placeholders(template: &str) -> Vec<String> {
        // Pattern matches: <[A-Za-z _-]+>
        // For now, use a simple manual parser to avoid regex dependency
        let mut placeholders = Vec::new();
        let mut in_placeholder = false;
        let mut current = String::new();

        for ch in template.chars() {
            if ch == '<' {
                in_placeholder = true;
                current.clear();
                current.push(ch);
            } else if ch == '>' && in_placeholder {
                current.push(ch);
                placeholders.push(current.clone());
                in_placeholder = false;
                current.clear();
            } else if in_placeholder {
                current.push(ch);
            }
        }

        placeholders
    }

    /// Find node by name (across all nodegroups)
    fn find_node_by_name(&self, name: &str) -> Option<&StaticNode> {
        self.nodes_by_id.values().find(|node| node.name == name)
    }

    /// Extract a display string from tiles for a given node, using:
    /// 1. Cache lookup (for resource-instance / resource-instance-list, uses titles from __cache)
    /// 2. Extension render_display (for extension datatypes like "reference")
    /// 3. Built-in serialize_display (for string, number, date, concept, etc.)
    /// 4. Fallback to extract_string_from_json (language maps, Arches format)
    fn extract_display_value_from_tiles(
        tiles: &[&StaticTile],
        node_id: &str,
        datatype: &str,
        cache: Option<&super::resources::ResourceCache>,
        extension_registry: Option<&crate::extension_type_registry::ExtensionTypeRegistry>,
    ) -> Option<String> {
        // For resource-instance / resource-instance-list, look up display names from __cache
        // (mirrors how TS ViewModels use __cache entries with title for display)
        if let Some(cache) = cache {
            if datatype == "resource-instance" || datatype == "resource-instance-list" {
                for tile in tiles {
                    if let Some(tile_id) = &tile.tileid {
                        if let Some(node_entries) = cache.get(tile_id) {
                            if let Some(entry) = node_entries.get(node_id) {
                                return Self::display_from_cache_entry(entry);
                            }
                        }
                    }
                }
            }
        }

        for tile in tiles {
            if let Some(value) = tile.data.get(node_id) {
                // 1. Try extension render_display (optional — not all extensions have it)
                if let Some(registry) = extension_registry {
                    if let Ok(Some(display)) = registry.render_display(datatype, value, "en") {
                        return Some(display);
                    }
                }

                // 2. Try built-in type serialization
                let result = crate::type_serialization::serialize_display(datatype, value, "en");
                if !result.is_error() {
                    match &result.value {
                        serde_json::Value::String(s) if !s.is_empty() => return Some(s.clone()),
                        serde_json::Value::Number(n) => return Some(n.to_string()),
                        serde_json::Value::Bool(b) => return Some(b.to_string()),
                        _ => {}
                    }
                }

                // 3. Fallback to raw JSON extraction (language maps, Arches format)
                if let Some(extracted) = Self::extract_string_from_json(value) {
                    return Some(extracted);
                }
            }
        }
        None
    }

    /// Extract display string from a cache entry (title, or comma-separated titles for lists)
    fn display_from_cache_entry(entry: &super::resources::CacheEntry) -> Option<String> {
        match entry {
            super::resources::CacheEntry::Single(r) => r.title.clone(),
            super::resources::CacheEntry::List(list) => {
                let titles: Vec<&str> = list
                    .entries
                    .iter()
                    .filter_map(|e| e.title.as_deref())
                    .collect();
                if titles.is_empty() {
                    None
                } else {
                    Some(titles.join(", "))
                }
            }
        }
    }

    /// Extract string value from JSON, handling language-nested objects
    /// Handles:
    /// - Simple strings: "value"
    /// - Language objects: {"en": "value"}
    /// - Arches localized strings: {"en": {"direction": "ltr", "value": "actual value"}}
    fn extract_string_from_json(value: &serde_json::Value) -> Option<String> {
        match value {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            serde_json::Value::Bool(b) => Some(b.to_string()),
            serde_json::Value::Object(map) => {
                // Try to get language-specific value
                Self::extract_lang_value(map, "en").or_else(|| {
                    // Fallback to first available language
                    map.values().find_map(Self::extract_single_lang_value)
                })
            }
            _ => None,
        }
    }

    /// Extract value for a specific language key
    fn extract_lang_value(
        map: &serde_json::Map<String, serde_json::Value>,
        lang: &str,
    ) -> Option<String> {
        map.get(lang).and_then(Self::extract_single_lang_value)
    }

    /// Extract string from a single language value, handling both formats:
    /// - Direct string: "value"
    /// - Arches format: {"direction": "ltr", "value": "actual value"}
    fn extract_single_lang_value(value: &serde_json::Value) -> Option<String> {
        match value {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Object(obj) => {
                // Arches localized string format: {"direction": "...", "value": "..."}
                obj.get("value")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
            }
            _ => None,
        }
    }
}