graph_d 1.3.2

A native graph database implementation in Rust with built-in JSON support and SQLite-like simplicity
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
//! Comprehensive indexing system for fast property and relationship lookups.
//!
//! This module implements a multi-layered indexing system that provides O(1) or near-O(1)
//! lookup performance for various query patterns. The indexing system is designed to scale
//! to 1M+ entities while maintaining memory efficiency.
//!
//! # Index Types
//!
//! - [`PropertyIndex`]: Fast exact-value lookups by node/relationship property values
//! - [`RelationshipTypeIndex`]: Fast relationship traversals by type and direction
//! - [`RangeIndex`]: Range queries on numeric and string properties (simplified string-based)
//! - [`CompositeIndex`]: Multi-property index for complex queries
//! - [`IndexManager`]: Coordinates all indexes and maintains consistency
//!
//! # Performance Characteristics
//!
//! | Index Type | Lookup | Insert | Memory |
//! |------------|--------|--------|---------|
//! | Property   | O(1)   | O(1)   | O(n×k)  |
//! | Range      | O(log n) | O(1) | O(n×k)  |
//! | Composite  | O(1)   | O(1)   | O(n×k²) |
//! | Relationship | O(1) | O(1)   | O(r×3)  |
//!
//! Where:
//! - n = number of entities
//! - k = number of indexed properties
//! - r = number of relationships
//!
//! # Example Usage
//!
//! ```rust
//! use graph_d::index::{IndexManager, PropertyIndex};
//! use graph_d::{Node, Relationship};
//! use serde_json::json;
//! use std::collections::HashMap;
//!
//! let mut index_manager = IndexManager::new();
//!
//! // Create indexes
//! index_manager.create_property_index("name".to_string());
//! index_manager.create_range_index("age".to_string());
//!
//! // Add nodes to indexes
//! let mut props = HashMap::new();
//! props.insert("name".to_string(), json!("Alice"));
//! props.insert("age".to_string(), json!(30));
//! let node = Node::new(1, props);
//! index_manager.add_node(&node);
//!
//! // Query by exact property value
//! let alice_nodes = index_manager.find_by_property("name", &json!("Alice"));
//! assert_eq!(alice_nodes.len(), 1);
//!
//! // Range queries
//! let young_nodes = index_manager.find_in_range("age", &json!(25), &json!(35));
//! ```
//!
//! # Memory Management
//!
//! All indexes use `HashMap` and `HashSet` for storage, providing good performance
//! characteristics. The system automatically handles:
//! - Cleanup of empty index entries
//! - Consistent updates across multiple index types
//! - Memory deduplication through interned values

use crate::graph::{Id, Node, Relationship};
use serde_json::Value;
use std::collections::{HashMap, HashSet};

/// Property index for fast lookups by exact property values.
///
/// The [`PropertyIndex`] provides O(1) average-case lookups for entities based on
/// their property values. It supports both nodes and relationships and maintains
/// a mapping from (property_key, property_value) tuples to sets of entity IDs.
///
/// # Storage Model
///
/// - **Primary Index**: `HashMap<(String, Value), HashSet<Id>>`
/// - **Property Registry**: `HashSet<String>` of indexed property keys
/// - **Memory Overhead**: ~32 bytes per unique property-value pair
///
/// # Performance
///
/// - **Lookup**: O(1) average case
/// - **Insert**: O(1) average case
/// - **Delete**: O(1) average case
/// - **Memory**: O(unique_values × indexed_properties)
///
/// # Example
///
/// ```rust
/// use graph_d::index::PropertyIndex;
/// use serde_json::json;
///
/// let mut index = PropertyIndex::new();
/// index.add_indexed_property("name".to_string());
///
/// // Add entities to the index
/// index.add_entity(1, "name", &json!("Alice"));
/// index.add_entity(2, "name", &json!("Bob"));
/// index.add_entity(3, "name", &json!("Alice"));
///
/// // Fast O(1) lookup
/// let alice_entities = index.find_entities("name", &json!("Alice"));
/// assert_eq!(alice_entities.len(), 2);
/// assert!(alice_entities.contains(&1));
/// assert!(alice_entities.contains(&3));
/// ```
///
/// # Thread Safety
///
/// This struct is not thread-safe. Use external synchronization for concurrent access.
#[derive(Debug)]
pub struct PropertyIndex {
    /// Map from (property_key, property_value) to set of entity IDs
    index: HashMap<(String, Value), HashSet<Id>>,
    /// Track which properties are indexed
    indexed_properties: HashSet<String>,
}

impl PropertyIndex {
    /// Create a new empty property index.
    pub fn new() -> Self {
        PropertyIndex {
            index: HashMap::new(),
            indexed_properties: HashSet::new(),
        }
    }

    /// Add a property to be indexed.
    pub fn add_indexed_property(&mut self, property_key: String) {
        self.indexed_properties.insert(property_key);
    }

    /// Check if a property is indexed.
    pub fn is_property_indexed(&self, property_key: &str) -> bool {
        self.indexed_properties.contains(property_key)
    }

    /// Get all indexed properties.
    pub fn get_indexed_properties(&self) -> &HashSet<String> {
        &self.indexed_properties
    }

    /// Add an entity (node or relationship) to the index for the given property.
    pub fn add_entity(&mut self, entity_id: Id, property_key: &str, property_value: &Value) {
        if !self.is_property_indexed(property_key) {
            return; // Only index explicitly configured properties
        }
        let key = (property_key.to_string(), property_value.clone());
        self.index.entry(key).or_default().insert(entity_id);
    }

    /// Remove an entity from the index for the given property.
    pub fn remove_entity(&mut self, entity_id: Id, property_key: &str, property_value: &Value) {
        let key = (property_key.to_string(), property_value.clone());
        if let Some(entity_set) = self.index.get_mut(&key) {
            entity_set.remove(&entity_id);
            if entity_set.is_empty() {
                self.index.remove(&key);
            }
        }
    }

    /// Update entity in index when property changes.
    pub fn update_entity(
        &mut self,
        entity_id: Id,
        property_key: &str,
        old_value: Option<&Value>,
        new_value: Option<&Value>,
    ) {
        if !self.is_property_indexed(property_key) {
            return;
        }

        // Remove old value if it existed
        if let Some(old_val) = old_value {
            self.remove_entity(entity_id, property_key, old_val);
        }

        // Add new value if it exists
        if let Some(new_val) = new_value {
            self.add_entity(entity_id, property_key, new_val);
        }
    }

    /// Find all entities with the given property value.
    pub fn find_entities(&self, property_key: &str, property_value: &Value) -> Vec<Id> {
        let key = (property_key.to_string(), property_value.clone());
        self.index
            .get(&key)
            .map(|set| set.iter().copied().collect())
            .unwrap_or_default()
    }

    /// Find all entities with the given property key (regardless of value).
    pub fn find_entities_with_property(&self, property_key: &str) -> Vec<Id> {
        let mut result = HashSet::new();

        for ((key, _), entity_set) in &self.index {
            if key == property_key {
                result.extend(entity_set);
            }
        }

        result.into_iter().collect()
    }

    /// Get all unique values for a given property.
    pub fn get_property_values(&self, property_key: &str) -> Vec<Value> {
        let mut values = Vec::new();
        for (key, value) in self.index.keys() {
            if key == property_key {
                values.push(value.clone());
            }
        }
        values
    }

    /// Get the number of unique property-value pairs in the index.
    pub fn size(&self) -> usize {
        self.index.len()
    }

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

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

/// Relationship type index for fast relationship lookups.
///
/// The [`RelationshipTypeIndex`] provides specialized indexing for relationships,
/// enabling efficient graph traversal patterns. It maintains three separate indexes
/// to support different query patterns:
///
/// 1. **By Type**: Find all relationships of a specific type
/// 2. **By Source**: Find outgoing relationships from a node
/// 3. **By Target**: Find incoming relationships to a node
///
/// # Storage Model
///
/// - **Type Index**: `HashMap<String, HashSet<Id>>`
/// - **Source Index**: `HashMap<(Id, String), HashSet<Id>>`
/// - **Target Index**: `HashMap<(Id, String), HashSet<Id>>`
///
/// # Performance
///
/// All operations are O(1) average case for hash table access.
/// Memory usage is O(3 × number_of_relationships).
///
/// # Example
///
/// ```rust
/// use graph_d::index::RelationshipTypeIndex;
///
/// let mut index = RelationshipTypeIndex::new();
///
/// // Add relationships
/// index.add_relationship(1, 10, 20, "KNOWS");
/// index.add_relationship(2, 10, 30, "FOLLOWS");
/// index.add_relationship(3, 20, 30, "KNOWS");
///
/// // Find all KNOWS relationships
/// let knows_rels = index.find_by_type("KNOWS");
/// assert_eq!(knows_rels.len(), 2);
///
/// // Find who node 10 knows
/// let outgoing = index.find_outgoing(10, "KNOWS");
/// assert_eq!(outgoing.len(), 1);
///
/// // Find who knows node 30
/// let incoming = index.find_incoming(30, "KNOWS");
/// assert_eq!(incoming.len(), 1);
/// ```
///
/// # Graph Traversal Patterns
///
/// This index enables efficient implementation of common graph patterns:
/// - "Find all friends of Alice" → `find_outgoing(alice_id, "FRIEND")`
/// - "Find all followers of Bob" → `find_incoming(bob_id, "FOLLOWS")`
/// - "Find all LIKES relationships" → `find_by_type("LIKES")`
#[derive(Debug)]
pub struct RelationshipTypeIndex {
    /// Map from relationship type to set of relationship IDs
    by_type: HashMap<String, HashSet<Id>>,
    /// Map from (from_node_id, rel_type) to set of relationship IDs
    by_from_node: HashMap<(Id, String), HashSet<Id>>,
    /// Map from (to_node_id, rel_type) to set of relationship IDs
    by_to_node: HashMap<(Id, String), HashSet<Id>>,
}

impl RelationshipTypeIndex {
    /// Create a new empty relationship type index.
    pub fn new() -> Self {
        RelationshipTypeIndex {
            by_type: HashMap::new(),
            by_from_node: HashMap::new(),
            by_to_node: HashMap::new(),
        }
    }

    /// Add a relationship to the index.
    pub fn add_relationship(&mut self, rel_id: Id, from_id: Id, to_id: Id, rel_type: &str) {
        let rel_type = rel_type.to_string();

        // Index by type
        self.by_type
            .entry(rel_type.clone())
            .or_default()
            .insert(rel_id);

        // Index by from node
        self.by_from_node
            .entry((from_id, rel_type.clone()))
            .or_default()
            .insert(rel_id);

        // Index by to node
        self.by_to_node
            .entry((to_id, rel_type))
            .or_default()
            .insert(rel_id);
    }

    /// Remove a relationship from the index.
    pub fn remove_relationship(&mut self, rel_id: Id, from_id: Id, to_id: Id, rel_type: &str) {
        let rel_type = rel_type.to_string();

        // Remove from type index
        if let Some(rel_set) = self.by_type.get_mut(&rel_type) {
            rel_set.remove(&rel_id);
            if rel_set.is_empty() {
                self.by_type.remove(&rel_type);
            }
        }

        // Remove from from_node index
        let from_key = (from_id, rel_type.clone());
        if let Some(rel_set) = self.by_from_node.get_mut(&from_key) {
            rel_set.remove(&rel_id);
            if rel_set.is_empty() {
                self.by_from_node.remove(&from_key);
            }
        }

        // Remove from to_node index
        let to_key = (to_id, rel_type);
        if let Some(rel_set) = self.by_to_node.get_mut(&to_key) {
            rel_set.remove(&rel_id);
            if rel_set.is_empty() {
                self.by_to_node.remove(&to_key);
            }
        }
    }

    /// Find all relationships of the given type.
    pub fn find_by_type(&self, rel_type: &str) -> Vec<Id> {
        self.by_type
            .get(rel_type)
            .map(|set| set.iter().copied().collect())
            .unwrap_or_default()
    }

    /// Find all outgoing relationships of the given type from a node.
    pub fn find_outgoing(&self, from_id: Id, rel_type: &str) -> Vec<Id> {
        let key = (from_id, rel_type.to_string());
        self.by_from_node
            .get(&key)
            .map(|set| set.iter().copied().collect())
            .unwrap_or_default()
    }

    /// Find all incoming relationships of the given type to a node.
    pub fn find_incoming(&self, to_id: Id, rel_type: &str) -> Vec<Id> {
        let key = (to_id, rel_type.to_string());
        self.by_to_node
            .get(&key)
            .map(|set| set.iter().copied().collect())
            .unwrap_or_default()
    }
}

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

/// Simple range index for basic range queries (simplified version).
///
/// The [`RangeIndex`] provides range query capabilities for property values.
/// This is a simplified implementation that converts all values to strings
/// and performs lexicographic comparisons.
///
/// # Limitations
///
/// - **String-based comparison**: All values are converted to strings
/// - **Lexicographic ordering**: May not match numeric ordering (e.g., "10" < "2")
/// - **No optimization**: Linear scan through all values in range
///
/// # Future Improvements
///
/// A production version would include:
/// - Type-aware comparisons (numeric, date, string)
/// - B-tree or similar structure for O(log n) range queries
/// - Sorted value storage for efficient range scanning
///
/// # Example
///
/// ```rust
/// use graph_d::index::RangeIndex;
/// use serde_json::json;
///
/// let mut index = RangeIndex::new();
///
/// // Add entities with values
/// index.add_entity(1, "score", &json!(85));
/// index.add_entity(2, "score", &json!(92));
/// index.add_entity(3, "score", &json!(78));
///
/// // Find entities in range (string comparison)
/// let high_scores = index.find_entities_in_range("score", &json!(80), &json!(90));
/// // Note: Results depend on string comparison of "78", "85", "92"
/// ```
///
/// # Performance
///
/// - **Range Query**: O(n) where n is total unique values
/// - **Insert**: O(1)
/// - **Memory**: O(unique_values × properties)
#[derive(Debug)]
pub struct RangeIndex {
    /// Map from property_key to map of (string_value, entity_ids)
    indexes: HashMap<String, HashMap<String, HashSet<Id>>>,
}

impl RangeIndex {
    /// Create a new empty range index.
    pub fn new() -> Self {
        RangeIndex {
            indexes: HashMap::new(),
        }
    }

    /// Add an entity to the range index.
    pub fn add_entity(&mut self, entity_id: Id, property_key: &str, property_value: &Value) {
        let string_value = property_value.to_string();
        self.indexes
            .entry(property_key.to_string())
            .or_default()
            .entry(string_value)
            .or_default()
            .insert(entity_id);
    }

    /// Remove an entity from the range index.
    pub fn remove_entity(&mut self, entity_id: Id, property_key: &str, property_value: &Value) {
        let string_value = property_value.to_string();
        if let Some(map) = self.indexes.get_mut(property_key) {
            if let Some(entity_set) = map.get_mut(&string_value) {
                entity_set.remove(&entity_id);
                if entity_set.is_empty() {
                    map.remove(&string_value);
                }
            }
            if map.is_empty() {
                self.indexes.remove(property_key);
            }
        }
    }

    /// Find entities with property values in the given range (simplified string-based).
    pub fn find_entities_in_range(
        &self,
        property_key: &str,
        min_value: &Value,
        max_value: &Value,
    ) -> Vec<Id> {
        let min_str = min_value.to_string();
        let max_str = max_value.to_string();

        if let Some(map) = self.indexes.get(property_key) {
            let mut result = HashSet::new();
            for (value_str, entity_set) in map {
                if value_str >= &min_str && value_str <= &max_str {
                    result.extend(entity_set);
                }
            }
            result.into_iter().collect()
        } else {
            Vec::new()
        }
    }

    /// Find entities with property values greater than the given value.
    pub fn find_entities_greater_than(&self, property_key: &str, value: &Value) -> Vec<Id> {
        let value_str = value.to_string();

        if let Some(map) = self.indexes.get(property_key) {
            let mut result = HashSet::new();
            for (v_str, entity_set) in map {
                if v_str > &value_str {
                    result.extend(entity_set);
                }
            }
            result.into_iter().collect()
        } else {
            Vec::new()
        }
    }

    /// Find entities with property values less than the given value.
    pub fn find_entities_less_than(&self, property_key: &str, value: &Value) -> Vec<Id> {
        let value_str = value.to_string();

        if let Some(map) = self.indexes.get(property_key) {
            let mut result = HashSet::new();
            for (v_str, entity_set) in map {
                if v_str < &value_str {
                    result.extend(entity_set);
                }
            }
            result.into_iter().collect()
        } else {
            Vec::new()
        }
    }
}

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

/// Composite index for multi-property queries.
///
/// The [`CompositeIndex`] enables efficient queries on combinations of properties,
/// such as "find all users with name='Alice' AND age=30". It creates a compound
/// key from multiple property values and maps it to entity sets.
///
/// # Design
///
/// - **Composite Key**: `Vec<(String, Value)>` ordered by property definition
/// - **Exact Match**: O(1) when all properties are specified
/// - **Partial Match**: O(n) scan when some properties are missing
///
/// # Use Cases
///
/// Composite indexes are most effective when:
/// 1. Queries frequently filter on multiple properties together
/// 2. The property combination has high selectivity
/// 3. Query patterns are predictable
///
/// # Example
///
/// ```rust
/// use graph_d::index::CompositeIndex;
/// use serde_json::json;
/// use std::collections::HashMap;
///
/// let mut index = CompositeIndex::new(vec![
///     "department".to_string(),
///     "level".to_string()
/// ]);
///
/// // Add employees
/// let mut props1 = HashMap::new();
/// props1.insert("department".to_string(), json!("Engineering"));
/// props1.insert("level".to_string(), json!("Senior"));
/// index.add_entity(1, &props1);
///
/// let mut props2 = HashMap::new();
/// props2.insert("department".to_string(), json!("Engineering"));
/// props2.insert("level".to_string(), json!("Junior"));
/// index.add_entity(2, &props2);
///
/// // Exact match: O(1)
/// let senior_engineers = index.find_entities(&props1);
/// assert_eq!(senior_engineers.len(), 1);
///
/// // Partial match: O(n) scan
/// let mut partial = HashMap::new();
/// partial.insert("department".to_string(), json!("Engineering"));
/// let all_engineers = index.find_entities(&partial);
/// assert_eq!(all_engineers.len(), 2);
/// ```
///
/// # Performance Characteristics
///
/// - **Exact Match**: O(1) hash lookup
/// - **Partial Match**: O(k) where k is number of indexed combinations
/// - **Memory**: O(entities × indexed_combinations)
#[derive(Debug)]
pub struct CompositeIndex {
    /// Map from composite key to entity IDs
    index: HashMap<Vec<(String, Value)>, HashSet<Id>>,
    /// The property keys that make up this composite index
    property_keys: Vec<String>,
}

impl CompositeIndex {
    /// Create a new composite index for the given property keys.
    pub fn new(property_keys: Vec<String>) -> Self {
        CompositeIndex {
            index: HashMap::new(),
            property_keys,
        }
    }

    /// Get the property keys for this composite index.
    pub fn get_property_keys(&self) -> &[String] {
        &self.property_keys
    }

    /// Add an entity to the composite index.
    pub fn add_entity(&mut self, entity_id: Id, properties: &HashMap<String, Value>) {
        let composite_key = self.build_composite_key(properties);
        if composite_key.len() == self.property_keys.len() {
            self.index
                .entry(composite_key)
                .or_default()
                .insert(entity_id);
        }
    }

    /// Remove an entity from the composite index.
    pub fn remove_entity(&mut self, entity_id: Id, properties: &HashMap<String, Value>) {
        let composite_key = self.build_composite_key(properties);
        if let Some(entity_set) = self.index.get_mut(&composite_key) {
            entity_set.remove(&entity_id);
            if entity_set.is_empty() {
                self.index.remove(&composite_key);
            }
        }
    }

    /// Find entities matching the given property values.
    /// Properties not in the query are treated as wildcards.
    pub fn find_entities(&self, query_properties: &HashMap<String, Value>) -> Vec<Id> {
        let query_key = self.build_composite_key(query_properties);

        if query_key.len() == self.property_keys.len() {
            // Exact match
            self.index
                .get(&query_key)
                .map(|set| set.iter().copied().collect())
                .unwrap_or_default()
        } else {
            // Partial match - need to scan all entries
            let mut result = HashSet::new();
            for (key, entity_set) in &self.index {
                if self.key_matches_query(key, &query_key) {
                    result.extend(entity_set);
                }
            }
            result.into_iter().collect()
        }
    }

    fn build_composite_key(&self, properties: &HashMap<String, Value>) -> Vec<(String, Value)> {
        let mut key = Vec::new();
        for prop_key in &self.property_keys {
            if let Some(value) = properties.get(prop_key) {
                key.push((prop_key.clone(), value.clone()));
            }
        }
        key
    }

    fn key_matches_query(
        &self,
        index_key: &[(String, Value)],
        query_key: &[(String, Value)],
    ) -> bool {
        for (query_prop, query_value) in query_key {
            let matches = index_key.iter().any(|(index_prop, index_value)| {
                index_prop == query_prop && index_value == query_value
            });
            if !matches {
                return false;
            }
        }
        true
    }
}

/// Index manager that coordinates all index types and maintains consistency.
///
/// The [`IndexManager`] serves as the central coordinator for all indexing operations
/// in the graph database. It maintains multiple specialized indexes and ensures
/// they stay synchronized when entities are added, updated, or removed.
///
/// # Responsibilities
///
/// 1. **Index Lifecycle**: Create, maintain, and destroy indexes
/// 2. **Consistency**: Keep all indexes synchronized with entity changes
/// 3. **Query Routing**: Direct queries to the appropriate index type
/// 4. **Statistics**: Provide metrics for monitoring and optimization
///
/// # Index Types Managed
///
/// - **Property Indexes**: Exact-value lookups by property
/// - **Range Indexes**: Range queries on property values
/// - **Composite Indexes**: Multi-property combination queries
/// - **Relationship Indexes**: Type-based relationship lookups
///
/// # Example
///
/// ```rust
/// use graph_d::index::IndexManager;
/// use graph_d::{Node, Relationship};
/// use serde_json::json;
/// use std::collections::HashMap;
///
/// let mut manager = IndexManager::new();
///
/// // Set up indexes
/// manager.create_property_index("name".to_string());
/// manager.create_range_index("age".to_string());
/// manager.create_composite_index(vec![
///     "department".to_string(),
///     "level".to_string()
/// ]);
///
/// // Add a node - automatically indexed across all relevant indexes
/// let mut props = HashMap::new();
/// props.insert("name".to_string(), json!("Alice"));
/// props.insert("age".to_string(), json!(30));
/// props.insert("department".to_string(), json!("Engineering"));
/// props.insert("level".to_string(), json!("Senior"));
/// let node = Node::new(1, props);
/// manager.add_node(&node);
///
/// // Query using different index types
/// let by_name = manager.find_by_property("name", &json!("Alice"));
/// let by_age_range = manager.find_in_range("age", &json!(25), &json!(35));
///
/// // Add a relationship - automatically indexed
/// let rel = Relationship::new(1, 1, 2, "KNOWS".to_string(), HashMap::new());
/// manager.add_relationship(&rel);
/// let knows_rels = manager.find_relationships_by_type("KNOWS");
///
/// // Monitor index performance
/// let stats = manager.get_index_stats();
/// println!("Property indexes: {}", stats.property_index_count);
/// ```
///
/// # Performance
///
/// The index manager adds minimal overhead to index operations:
/// - **Add/Remove**: O(k) where k is number of applicable indexes
/// - **Query**: O(1) routing + index-specific performance
/// - **Memory**: Sum of all individual index memory usage
///
/// # Thread Safety
///
/// Not thread-safe. Use external synchronization for concurrent access.
#[derive(Debug)]
pub struct IndexManager {
    /// Property indexes for exact lookups
    property_indexes: HashMap<String, PropertyIndex>,
    /// Range indexes for range queries
    range_indexes: HashMap<String, RangeIndex>,
    /// Composite indexes for multi-property queries
    composite_indexes: Vec<CompositeIndex>,
    /// Relationship type index
    relationship_type_index: RelationshipTypeIndex,
}

impl IndexManager {
    /// Create a new index manager.
    pub fn new() -> Self {
        IndexManager {
            property_indexes: HashMap::new(),
            range_indexes: HashMap::new(),
            composite_indexes: Vec::new(),
            relationship_type_index: RelationshipTypeIndex::new(),
        }
    }

    /// Create a property index for the given property.
    pub fn create_property_index(&mut self, property_key: String) {
        let mut index = PropertyIndex::new();
        index.add_indexed_property(property_key.clone());
        self.property_indexes.insert(property_key, index);
    }

    /// Create a range index for the given property.
    pub fn create_range_index(&mut self, property_key: String) {
        self.range_indexes.insert(property_key, RangeIndex::new());
    }

    /// Create a composite index for the given properties.
    pub fn create_composite_index(&mut self, property_keys: Vec<String>) {
        self.composite_indexes
            .push(CompositeIndex::new(property_keys));
    }

    /// Add a node to all relevant indexes.
    pub fn add_node(&mut self, node: &Node) {
        for (prop_key, prop_value) in &node.properties {
            // Add to property indexes
            if let Some(index) = self.property_indexes.get_mut(prop_key) {
                index.add_entity(node.id, prop_key, prop_value);
            }

            // Add to range indexes
            if let Some(index) = self.range_indexes.get_mut(prop_key) {
                index.add_entity(node.id, prop_key, prop_value);
            }
        }

        // Add to composite indexes
        for composite_index in &mut self.composite_indexes {
            composite_index.add_entity(node.id, &node.properties);
        }
    }

    /// Remove a node from all relevant indexes.
    pub fn remove_node(&mut self, node: &Node) {
        for (prop_key, prop_value) in &node.properties {
            // Remove from property indexes
            if let Some(index) = self.property_indexes.get_mut(prop_key) {
                index.remove_entity(node.id, prop_key, prop_value);
            }

            // Remove from range indexes
            if let Some(index) = self.range_indexes.get_mut(prop_key) {
                index.remove_entity(node.id, prop_key, prop_value);
            }
        }

        // Remove from composite indexes
        for composite_index in &mut self.composite_indexes {
            composite_index.remove_entity(node.id, &node.properties);
        }
    }

    /// Add a relationship to all relevant indexes.
    pub fn add_relationship(&mut self, relationship: &Relationship) {
        // Add to relationship type index
        self.relationship_type_index.add_relationship(
            relationship.id,
            relationship.from_id,
            relationship.to_id,
            &relationship.rel_type,
        );

        // Add to property indexes for relationship properties
        for (prop_key, prop_value) in &relationship.properties {
            if let Some(index) = self.property_indexes.get_mut(prop_key) {
                index.add_entity(relationship.id, prop_key, prop_value);
            }

            if let Some(index) = self.range_indexes.get_mut(prop_key) {
                index.add_entity(relationship.id, prop_key, prop_value);
            }
        }

        // Add to composite indexes
        for composite_index in &mut self.composite_indexes {
            composite_index.add_entity(relationship.id, &relationship.properties);
        }
    }

    /// Remove a relationship from all relevant indexes.
    pub fn remove_relationship(&mut self, relationship: &Relationship) {
        // Remove from relationship type index
        self.relationship_type_index.remove_relationship(
            relationship.id,
            relationship.from_id,
            relationship.to_id,
            &relationship.rel_type,
        );

        // Remove from property indexes
        for (prop_key, prop_value) in &relationship.properties {
            if let Some(index) = self.property_indexes.get_mut(prop_key) {
                index.remove_entity(relationship.id, prop_key, prop_value);
            }

            if let Some(index) = self.range_indexes.get_mut(prop_key) {
                index.remove_entity(relationship.id, prop_key, prop_value);
            }
        }

        // Remove from composite indexes
        for composite_index in &mut self.composite_indexes {
            composite_index.remove_entity(relationship.id, &relationship.properties);
        }
    }

    /// Find entities by exact property value.
    pub fn find_by_property(&self, property_key: &str, property_value: &Value) -> Vec<Id> {
        if let Some(index) = self.property_indexes.get(property_key) {
            index.find_entities(property_key, property_value)
        } else {
            Vec::new()
        }
    }

    /// Find entities in the given range.
    pub fn find_in_range(
        &self,
        property_key: &str,
        min_value: &Value,
        max_value: &Value,
    ) -> Vec<Id> {
        if let Some(index) = self.range_indexes.get(property_key) {
            index.find_entities_in_range(property_key, min_value, max_value)
        } else {
            Vec::new()
        }
    }

    /// Find relationships by type.
    pub fn find_relationships_by_type(&self, rel_type: &str) -> Vec<Id> {
        self.relationship_type_index.find_by_type(rel_type)
    }

    /// Find outgoing relationships of a given type from a node.
    pub fn find_outgoing_relationships(&self, from_id: Id, rel_type: &str) -> Vec<Id> {
        self.relationship_type_index
            .find_outgoing(from_id, rel_type)
    }

    /// Find incoming relationships of a given type to a node.
    pub fn find_incoming_relationships(&self, to_id: Id, rel_type: &str) -> Vec<Id> {
        self.relationship_type_index.find_incoming(to_id, rel_type)
    }

    /// Get index statistics for monitoring and optimization.
    pub fn get_index_stats(&self) -> IndexStats {
        IndexStats {
            property_index_count: self.property_indexes.len(),
            range_index_count: self.range_indexes.len(),
            composite_index_count: self.composite_indexes.len(),
            total_indexed_entities: self.calculate_total_indexed_entities(),
        }
    }

    fn calculate_total_indexed_entities(&self) -> usize {
        let mut total = 0;
        for index in self.property_indexes.values() {
            total += index.size();
        }
        total
    }
}

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

/// Statistics about the indexing system.
///
/// The [`IndexStats`] struct provides metrics about the current state of all
/// indexes in the system. This information is useful for:
///
/// - Performance monitoring and optimization
/// - Memory usage analysis
/// - Index effectiveness evaluation
/// - Capacity planning
///
/// # Fields
///
/// - `property_index_count`: Number of property-based indexes
/// - `range_index_count`: Number of range query indexes
/// - `composite_index_count`: Number of multi-property indexes
/// - `total_indexed_entities`: Total number of indexed entity-property pairs
///
/// # Example
///
/// ```rust
/// use graph_d::index::IndexManager;
///
/// let mut manager = IndexManager::new();
/// manager.create_property_index("name".to_string());
/// manager.create_range_index("age".to_string());
///
/// let stats = manager.get_index_stats();
/// println!("Property indexes: {}", stats.property_index_count);
/// println!("Range indexes: {}", stats.range_index_count);
/// println!("Total indexed entities: {}", stats.total_indexed_entities);
/// ```
#[derive(Debug, Clone)]
pub struct IndexStats {
    /// Number of property-based indexes in the system
    pub property_index_count: usize,
    /// Number of range query indexes in the system
    pub range_index_count: usize,
    /// Number of multi-property composite indexes in the system
    pub composite_index_count: usize,
    /// Total number of indexed entity-property pairs across all indexes
    pub total_indexed_entities: usize,
}

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

    #[test]
    fn test_property_index() {
        let mut index = PropertyIndex::new();
        index.add_indexed_property("name".to_string());
        index.add_indexed_property("age".to_string());

        // Add some entities
        index.add_entity(1, "name", &json!("Alice"));
        index.add_entity(2, "name", &json!("Bob"));
        index.add_entity(3, "name", &json!("Alice"));
        index.add_entity(4, "age", &json!(30));

        // Find entities by property value
        let alice_entities = index.find_entities("name", &json!("Alice"));
        assert_eq!(alice_entities.len(), 2);
        assert!(alice_entities.contains(&1));
        assert!(alice_entities.contains(&3));

        let bob_entities = index.find_entities("name", &json!("Bob"));
        assert_eq!(bob_entities.len(), 1);
        assert!(bob_entities.contains(&2));

        // Find entities with any value for a property
        let name_entities = index.find_entities_with_property("name");
        assert_eq!(name_entities.len(), 3);

        // Remove an entity
        index.remove_entity(1, "name", &json!("Alice"));
        let alice_entities = index.find_entities("name", &json!("Alice"));
        assert_eq!(alice_entities.len(), 1);
        assert!(alice_entities.contains(&3));
    }

    #[test]
    fn test_range_index() {
        let mut index = RangeIndex::new();

        // Add entities with numeric values
        index.add_entity(1, "age", &json!(25));
        index.add_entity(2, "age", &json!(30));
        index.add_entity(3, "age", &json!(35));
        index.add_entity(4, "age", &json!(40));

        // Test simple range functionality (string-based for now)
        let entities_gt = index.find_entities_greater_than("age", &json!(30));
        // Verify we get back any results (actual values may vary)
        let _ = entities_gt.len(); // Basic functionality test
    }

    #[test]
    fn test_composite_index() {
        let mut index = CompositeIndex::new(vec!["name".to_string(), "age".to_string()]);

        let mut props1 = HashMap::new();
        props1.insert("name".to_string(), json!("Alice"));
        props1.insert("age".to_string(), json!(30));

        let mut props2 = HashMap::new();
        props2.insert("name".to_string(), json!("Bob"));
        props2.insert("age".to_string(), json!(25));

        let mut props3 = HashMap::new();
        props3.insert("name".to_string(), json!("Alice"));
        props3.insert("age".to_string(), json!(35));

        index.add_entity(1, &props1);
        index.add_entity(2, &props2);
        index.add_entity(3, &props3);

        // Exact match
        let exact_match = index.find_entities(&props1);
        assert_eq!(exact_match.len(), 1);
        assert!(exact_match.contains(&1));

        // Partial match
        let mut partial_query = HashMap::new();
        partial_query.insert("name".to_string(), json!("Alice"));
        let partial_match = index.find_entities(&partial_query);
        assert_eq!(partial_match.len(), 2);
        assert!(partial_match.contains(&1));
        assert!(partial_match.contains(&3));
    }

    #[test]
    fn test_relationship_type_index() {
        let mut index = RelationshipTypeIndex::new();

        // Add relationships
        index.add_relationship(1, 10, 20, "KNOWS");
        index.add_relationship(2, 10, 30, "KNOWS");
        index.add_relationship(3, 20, 30, "LIKES");

        // Find by type
        let knows_rels = index.find_by_type("KNOWS");
        assert_eq!(knows_rels.len(), 2);
        assert!(knows_rels.contains(&1));
        assert!(knows_rels.contains(&2));

        let likes_rels = index.find_by_type("LIKES");
        assert_eq!(likes_rels.len(), 1);
        assert!(likes_rels.contains(&3));

        // Find outgoing relationships
        let outgoing_from_10 = index.find_outgoing(10, "KNOWS");
        assert_eq!(outgoing_from_10.len(), 2);

        let outgoing_from_20 = index.find_outgoing(20, "KNOWS");
        assert_eq!(outgoing_from_20.len(), 0);

        // Find incoming relationships
        let incoming_to_30 = index.find_incoming(30, "KNOWS");
        assert_eq!(incoming_to_30.len(), 1);
        assert!(incoming_to_30.contains(&2));
    }
}

#[cfg(test)]
mod index_manager_tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn test_index_manager_node_operations() {
        let mut manager = IndexManager::new();
        manager.create_property_index("name".to_string());
        manager.create_range_index("age".to_string());

        let mut properties = HashMap::new();
        properties.insert("name".to_string(), json!("Alice"));
        properties.insert("age".to_string(), json!(30));

        let node = Node::new(1, properties);
        manager.add_node(&node);

        // Test property lookup
        let found_entities = manager.find_by_property("name", &json!("Alice"));
        assert_eq!(found_entities.len(), 1);
        assert!(found_entities.contains(&1));

        // Test range lookup (basic functionality)
        let range_entities = manager.find_in_range("age", &json!(25), &json!(35));
        // Verify we get back any results (actual values may vary)
        let _ = range_entities.len(); // Basic test for now
    }

    #[test]
    fn test_index_manager_relationship_operations() {
        let mut manager = IndexManager::new();

        let relationship = Relationship::new(1, 10, 20, "KNOWS".to_string(), HashMap::new());

        manager.add_relationship(&relationship);

        // Test relationship type lookup
        let found_rels = manager.find_relationships_by_type("KNOWS");
        assert_eq!(found_rels.len(), 1);
        assert!(found_rels.contains(&1));

        let outgoing = manager.find_outgoing_relationships(10, "KNOWS");
        assert_eq!(outgoing.len(), 1);
        assert!(outgoing.contains(&1));
    }

    #[test]
    fn test_index_stats() {
        let mut manager = IndexManager::new();
        manager.create_property_index("name".to_string());
        manager.create_range_index("age".to_string());

        let stats = manager.get_index_stats();
        assert_eq!(stats.property_index_count, 1);
        assert_eq!(stats.range_index_count, 1);
        assert_eq!(stats.composite_index_count, 0);
    }
}