oxirs-embed 0.4.1

Knowledge graph embeddings with TransE, ComplEx, and custom models
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
//! Integration utilities with other OxiRS components

use crate::{EmbeddingModel, Vector};
use anyhow::{anyhow, Result};
use oxirs_vec::index::{AdvancedVectorIndex, IndexConfig, IndexType};
use oxirs_vec::VectorIndex as OxirsVectorIndex;
use std::collections::HashMap;
use tracing::{debug, info, warn};

/// Integration bridge between oxirs-embed and vector stores
pub struct VectorStoreBridge {
    entity_mappings: HashMap<String, String>,
    relation_mappings: HashMap<String, String>,
    prefix_config: PrefixConfig,
    /// Flat (brute-force) vector index over synced entity embeddings, keyed
    /// by the same URI stored in `entity_mappings`, backing
    /// [`find_similar_entities`](Self::find_similar_entities).
    entity_index: AdvancedVectorIndex,
    /// Same as `entity_index` but for relation embeddings, backing
    /// [`find_similar_relations`](Self::find_similar_relations).
    relation_index: AdvancedVectorIndex,
}

fn flat_index() -> AdvancedVectorIndex {
    AdvancedVectorIndex::new(IndexConfig {
        index_type: IndexType::Flat,
        ..IndexConfig::default()
    })
}

/// Configuration for URI prefixes in vector store
#[derive(Debug, Clone)]
pub struct PrefixConfig {
    pub entity_prefix: String,
    pub relation_prefix: String,
    pub use_namespaces: bool,
}

impl Default for PrefixConfig {
    fn default() -> Self {
        Self {
            entity_prefix: "kg:entity:".to_string(),
            relation_prefix: "kg:relation:".to_string(),
            use_namespaces: true,
        }
    }
}

impl VectorStoreBridge {
    /// Create a new bridge
    pub fn new() -> Self {
        Self {
            entity_mappings: HashMap::new(),
            relation_mappings: HashMap::new(),
            prefix_config: PrefixConfig::default(),
            entity_index: flat_index(),
            relation_index: flat_index(),
        }
    }

    /// Create bridge with custom prefix config
    pub fn with_prefix_config(prefix_config: PrefixConfig) -> Self {
        Self {
            entity_mappings: HashMap::new(),
            relation_mappings: HashMap::new(),
            prefix_config,
            entity_index: flat_index(),
            relation_index: flat_index(),
        }
    }

    /// Sync all embeddings from a model to the vector store
    pub fn sync_model_embeddings(&mut self, model: &dyn EmbeddingModel) -> Result<SyncStats> {
        let start_time = std::time::Instant::now();
        let mut sync_stats = SyncStats::default();

        info!("Starting embedding synchronization to vector store");

        // Sync entity embeddings
        let entities = model.get_entities();
        for entity in &entities {
            match model.get_entity_embedding(entity) {
                Ok(embedding) => {
                    let uri = self.generate_entity_uri(entity);
                    if let Err(e) = self
                        .entity_index
                        .insert(uri.clone(), embedding.into_inner())
                    {
                        warn!("Failed to index embedding for entity {}: {}", entity, e);
                        sync_stats
                            .errors
                            .push(format!("Entity {entity} (indexing): {e}"));
                        continue;
                    }
                    self.entity_mappings.insert(entity.clone(), uri);
                    sync_stats.entities_synced += 1;
                }
                Err(e) => {
                    warn!("Failed to get embedding for entity {}: {}", entity, e);
                    sync_stats.errors.push(format!("Entity {entity}: {e}"));
                }
            }
        }

        // Sync relation embeddings
        let relations = model.get_relations();
        for relation in &relations {
            match model.get_relation_embedding(relation) {
                Ok(embedding) => {
                    let uri = self.generate_relation_uri(relation);
                    if let Err(e) = self
                        .relation_index
                        .insert(uri.clone(), embedding.into_inner())
                    {
                        warn!("Failed to index embedding for relation {}: {}", relation, e);
                        sync_stats
                            .errors
                            .push(format!("Relation {relation} (indexing): {e}"));
                        continue;
                    }
                    self.relation_mappings.insert(relation.clone(), uri);
                    sync_stats.relations_synced += 1;
                }
                Err(e) => {
                    warn!("Failed to get embedding for relation {}: {}", relation, e);
                    sync_stats.errors.push(format!("Relation {relation}: {e}"));
                }
            }
        }

        sync_stats.sync_duration = start_time.elapsed();
        info!(
            "Embedding sync completed: {} entities, {} relations, {} errors",
            sync_stats.entities_synced,
            sync_stats.relations_synced,
            sync_stats.errors.len()
        );

        Ok(sync_stats)
    }

    /// Find entities most similar to `entity` by cosine/L2 distance (per the
    /// index's configured metric) between their synced embeddings. `entity`
    /// itself is excluded from the results.
    pub fn find_similar_entities(&self, entity: &str, k: usize) -> Result<Vec<(String, f32)>> {
        let uri = self
            .entity_mappings
            .get(entity)
            .ok_or_else(|| anyhow!("Entity not found in mappings: {}", entity))?;
        let query = self
            .entity_index
            .get_vector(uri)
            .ok_or_else(|| anyhow!("Entity '{}' is mapped but has no indexed embedding", entity))?;

        debug!("Searching for entities similar to: {}", entity);
        let results = self.entity_index.search_knn(query, k + 1)?;
        Ok(results
            .into_iter()
            .filter(|(result_uri, _)| result_uri != uri)
            .take(k)
            .map(|(result_uri, distance)| (self.entity_name_from_uri(&result_uri), distance))
            .collect())
    }

    /// Find relations most similar to `relation`, analogous to
    /// [`find_similar_entities`](Self::find_similar_entities).
    pub fn find_similar_relations(&self, relation: &str, k: usize) -> Result<Vec<(String, f32)>> {
        let uri = self
            .relation_mappings
            .get(relation)
            .ok_or_else(|| anyhow!("Relation not found in mappings: {}", relation))?;
        let query = self.relation_index.get_vector(uri).ok_or_else(|| {
            anyhow!(
                "Relation '{}' is mapped but has no indexed embedding",
                relation
            )
        })?;

        debug!("Searching for relations similar to: {}", relation);
        let results = self.relation_index.search_knn(query, k + 1)?;
        Ok(results
            .into_iter()
            .filter(|(result_uri, _)| result_uri != uri)
            .take(k)
            .map(|(result_uri, distance)| (self.relation_name_from_uri(&result_uri), distance))
            .collect())
    }

    /// Recover the original entity name from a generated URI (inverse of
    /// [`generate_entity_uri`](Self::generate_entity_uri)).
    fn entity_name_from_uri(&self, uri: &str) -> String {
        uri.strip_prefix(&self.prefix_config.entity_prefix)
            .unwrap_or(uri)
            .to_string()
    }

    /// Recover the original relation name from a generated URI (inverse of
    /// [`generate_relation_uri`](Self::generate_relation_uri)).
    fn relation_name_from_uri(&self, uri: &str) -> String {
        uri.strip_prefix(&self.prefix_config.relation_prefix)
            .unwrap_or(uri)
            .to_string()
    }

    /// Generate URI for entity
    fn generate_entity_uri(&self, entity: &str) -> String {
        if self.prefix_config.use_namespaces {
            format!("{}{}", self.prefix_config.entity_prefix, entity)
        } else {
            entity.to_string()
        }
    }

    /// Generate URI for relation
    fn generate_relation_uri(&self, relation: &str) -> String {
        if self.prefix_config.use_namespaces {
            format!("{}{}", self.prefix_config.relation_prefix, relation)
        } else {
            relation.to_string()
        }
    }

    /// Get sync statistics
    pub fn get_sync_info(&self) -> SyncInfo {
        SyncInfo {
            entities_mapped: self.entity_mappings.len(),
            relations_mapped: self.relation_mappings.len(),
            vector_store_stats: None,
        }
    }

    /// Clear all mappings
    pub fn clear_mappings(&mut self) {
        self.entity_mappings.clear();
        self.relation_mappings.clear();
        info!("Cleared all entity and relation mappings");
    }
}

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

/// Statistics from synchronization operation
#[derive(Debug, Clone, Default)]
pub struct SyncStats {
    pub entities_synced: usize,
    pub relations_synced: usize,
    pub errors: Vec<String>,
    pub sync_duration: std::time::Duration,
}

/// Information about current sync state
#[derive(Debug, Clone)]
pub struct SyncInfo {
    pub entities_mapped: usize,
    pub relations_mapped: usize,
    pub vector_store_stats: Option<(usize, usize)>,
}

/// Integration with oxirs-chat for conversational AI
pub struct ChatIntegration {
    model: Box<dyn EmbeddingModel>,
    context_window: usize,
    similarity_threshold: f32,
    personalization: PersonalizationEngine,
    multilingual: MultilingualSupport,
}

impl ChatIntegration {
    /// Create new chat integration
    pub fn new(model: Box<dyn EmbeddingModel>) -> Self {
        Self {
            model,
            context_window: 10,
            similarity_threshold: 0.7,
            personalization: PersonalizationEngine::new(),
            multilingual: MultilingualSupport::new(),
        }
    }

    /// Configure context window size
    pub fn with_context_window(mut self, window_size: usize) -> Self {
        self.context_window = window_size;
        self
    }

    /// Configure similarity threshold for relevant entities
    pub fn with_similarity_threshold(mut self, threshold: f32) -> Self {
        self.similarity_threshold = threshold;
        self
    }

    /// Extract entities from the model's vocabulary that appear as a
    /// substring of `query` (case-insensitive).
    ///
    /// Rather than scanning the whole query once per known entity (`O(entities
    /// × query length)`), this builds a lowercase-name index once and scans
    /// the query a single time for bounded-length substring windows against
    /// that index (`O(entities + query length × longest entity name)`).
    pub fn extract_relevant_entities(&self, query: &str) -> Result<Vec<String>> {
        let entities = self.model.get_entities();
        if entities.is_empty() {
            return Ok(Vec::new());
        }

        let query_lower = query.to_lowercase();

        let mut entity_index: HashMap<String, String> = HashMap::new();
        let mut max_entity_chars = 0usize;
        for entity in entities {
            let lower = entity.to_lowercase();
            max_entity_chars = max_entity_chars.max(lower.chars().count());
            entity_index.insert(lower, entity);
        }
        if max_entity_chars == 0 {
            return Ok(Vec::new());
        }

        // Byte offset of every character boundary in the query (plus one past
        // the end) so substrings never split a multi-byte UTF-8 character.
        let boundaries: Vec<usize> = query_lower
            .char_indices()
            .map(|(byte_idx, _)| byte_idx)
            .chain(std::iter::once(query_lower.len()))
            .collect();
        let num_chars = boundaries.len() - 1;

        let mut relevant = Vec::new();
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();

        for start in 0..num_chars {
            let start_byte = boundaries[start];
            let max_len = max_entity_chars.min(num_chars - start);
            for len in 1..=max_len {
                let end_byte = boundaries[start + len];
                let window = &query_lower[start_byte..end_byte];
                if let Some(original) = entity_index.get(window) {
                    if seen.insert(original.clone()) {
                        relevant.push(original.clone());
                    }
                }
            }
        }

        Ok(relevant)
    }

    /// Generate a context embedding for a conversation by encoding the most
    /// recent messages (bounded by `context_window`) with the held model and
    /// averaging the resulting vectors component-wise.
    pub async fn generate_context_embedding(&self, messages: &[String]) -> Result<Vector> {
        if messages.is_empty() {
            return Err(anyhow!("No messages provided"));
        }

        // Take the last N messages based on context window
        let recent_messages: Vec<String> = messages
            .iter()
            .rev()
            .take(self.context_window)
            .cloned()
            .collect();

        let encoded = self.model.encode(&recent_messages).await?;
        let dim = encoded
            .iter()
            .map(|v| v.len())
            .find(|&len| len > 0)
            .ok_or_else(|| anyhow!("Model returned no non-empty encodings for these messages"))?;

        let mut combined = vec![0.0f32; dim];
        let mut count = 0usize;
        for vector in &encoded {
            if vector.len() != dim {
                // Defensively skip any encoding with a mismatched dimension
                // rather than corrupting the running average.
                continue;
            }
            for (acc, value) in combined.iter_mut().zip(vector.iter()) {
                *acc += value;
            }
            count += 1;
        }

        for value in combined.iter_mut() {
            *value /= count as f32;
        }

        Ok(Vector::new(combined))
    }

    /// Generate personalized embeddings for a user
    pub async fn generate_personalized_embedding(
        &mut self,
        user_id: &str,
        query: &str,
        conversation_history: &[String],
    ) -> Result<Vector> {
        // Get user profile and preferences
        let user_profile = self.personalization.get_user_profile(user_id)?.clone();

        // Apply user preferences to query embedding
        let embeddings = self.model.encode(&[query.to_string()]).await?;
        let base_embedding = Vector::new(embeddings[0].clone());
        let personalized_embedding = self.personalization.apply_user_preferences(
            &base_embedding,
            &user_profile,
            conversation_history,
        )?;

        Ok(personalized_embedding)
    }

    /// Update user profile based on interaction
    pub fn update_user_profile(
        &mut self,
        user_id: &str,
        query: &str,
        response_feedback: Option<f32>,
        interaction_type: InteractionType,
    ) -> Result<()> {
        self.personalization.update_user_profile(
            user_id,
            query,
            response_feedback,
            interaction_type,
        )
    }

    /// Translate query to target language
    pub async fn translate_query(
        &self,
        query: &str,
        source_lang: &str,
        target_lang: &str,
    ) -> Result<String> {
        self.multilingual
            .translate_text(query, source_lang, target_lang)
            .await
    }

    /// Detect language of input text
    pub async fn detect_language(&self, text: &str) -> Result<LanguageDetection> {
        self.multilingual.detect_language(text).await
    }

    /// Generate cross-lingual embeddings
    pub async fn generate_cross_lingual_embedding(
        &self,
        text: &str,
        source_lang: &str,
        target_lang: &str,
    ) -> Result<Vector> {
        self.multilingual
            .generate_cross_lingual_embedding(text, source_lang, target_lang, &*self.model)
            .await
    }

    /// Get multilingual entity alignment
    pub async fn align_entities_across_languages(
        &self,
        entity: &str,
        source_lang: &str,
        target_langs: &[String],
    ) -> Result<HashMap<String, String>> {
        self.multilingual
            .align_entities(entity, source_lang, target_langs)
            .await
    }
}

/// SPARQL integration for query enhancement
pub struct SparqlIntegration {
    #[allow(dead_code)]
    model: Box<dyn EmbeddingModel>,
    #[allow(dead_code)]
    similarity_boost: f32,
}

impl SparqlIntegration {
    /// Create new SPARQL integration
    pub fn new(model: Box<dyn EmbeddingModel>) -> Self {
        Self {
            model,
            similarity_boost: 0.1,
        }
    }

    /// Enhance SPARQL query with similarity-based suggestions
    pub fn enhance_query(&self, sparql_query: &str) -> Result<EnhancedQuery> {
        // Parse basic patterns from SPARQL (simplified)
        let entities = self.extract_entities_from_sparql(sparql_query)?;
        let relations = self.extract_relations_from_sparql(sparql_query)?;

        let mut suggestions = Vec::new();

        // Find similar entities
        for entity in &entities {
            // This would use actual similarity computation
            suggestions.push(QuerySuggestion {
                suggestion_type: SuggestionType::SimilarEntity,
                original: entity.clone(),
                suggested: format!("similar_to_{entity}"),
                confidence: 0.8,
            });
        }

        // Find similar relations
        for relation in &relations {
            suggestions.push(QuerySuggestion {
                suggestion_type: SuggestionType::SimilarRelation,
                original: relation.clone(),
                suggested: format!("similar_to_{relation}"),
                confidence: 0.7,
            });
        }

        Ok(EnhancedQuery {
            original_query: sparql_query.to_string(),
            entities_found: entities,
            relations_found: relations,
            suggestions,
        })
    }

    /// Extract entities from SPARQL query (simplified)
    fn extract_entities_from_sparql(&self, query: &str) -> Result<Vec<String>> {
        // This is a very simplified extraction
        // A real implementation would use a proper SPARQL parser
        let mut entities = Vec::new();

        for line in query.lines() {
            if line.contains("http://") {
                // Extract URIs that might be entities
                if let Some(start) = line.find("http://") {
                    if let Some(end) = line[start..].find(' ') {
                        let uri = &line[start..start + end];
                        entities.push(uri.to_string());
                    }
                }
            }
        }

        Ok(entities)
    }

    /// Extract relations from SPARQL query (simplified)
    fn extract_relations_from_sparql(&self, query: &str) -> Result<Vec<String>> {
        // Simplified relation extraction
        let mut relations = Vec::new();

        for line in query.lines() {
            if line.contains("?") && line.contains("http://") {
                // Look for patterns like "?s <relation> ?o"
                if let Some(start) = line.find('<') {
                    if let Some(end) = line.find('>') {
                        let relation = &line[start + 1..end];
                        relations.push(relation.to_string());
                    }
                }
            }
        }

        Ok(relations)
    }
}

/// Enhanced SPARQL query with suggestions
#[derive(Debug, Clone)]
pub struct EnhancedQuery {
    pub original_query: String,
    pub entities_found: Vec<String>,
    pub relations_found: Vec<String>,
    pub suggestions: Vec<QuerySuggestion>,
}

/// Query enhancement suggestion
#[derive(Debug, Clone)]
pub struct QuerySuggestion {
    pub suggestion_type: SuggestionType,
    pub original: String,
    pub suggested: String,
    pub confidence: f32,
}

/// Types of query suggestions
#[derive(Debug, Clone)]
pub enum SuggestionType {
    SimilarEntity,
    SimilarRelation,
    AlternativePattern,
    ExpansionSuggestion,
}

/// Personalization engine for user-specific embeddings
pub struct PersonalizationEngine {
    user_profiles: HashMap<String, UserProfile>,
    interaction_history: HashMap<String, Vec<UserInteraction>>,
    preference_weights: PreferenceWeights,
}

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

impl PersonalizationEngine {
    pub fn new() -> Self {
        Self {
            user_profiles: HashMap::new(),
            interaction_history: HashMap::new(),
            preference_weights: PreferenceWeights::default(),
        }
    }

    /// Get or create user profile
    pub fn get_user_profile(&mut self, user_id: &str) -> Result<&UserProfile> {
        if !self.user_profiles.contains_key(user_id) {
            let profile = UserProfile::new(user_id.to_string());
            self.user_profiles.insert(user_id.to_string(), profile);
        }

        self.user_profiles
            .get(user_id)
            .ok_or_else(|| anyhow!("Failed to get user profile for {}", user_id))
    }

    /// Apply user preferences to embedding
    pub fn apply_user_preferences(
        &self,
        base_embedding: &Vector,
        user_profile: &UserProfile,
        conversation_history: &[String],
    ) -> Result<Vector> {
        let mut personalized = base_embedding.clone();

        // Apply domain preferences
        for (domain, weight) in &user_profile.domain_preferences {
            if conversation_history.iter().any(|msg| msg.contains(domain)) {
                // Boost embedding components related to preferred domains
                for i in 0..personalized.values.len() {
                    personalized.values[i] *= 1.0 + (weight * self.preference_weights.domain_boost);
                }
            }
        }

        // Apply recent interaction patterns
        let recent_interactions = self.get_recent_interactions(&user_profile.user_id, 10);
        if !recent_interactions.is_empty() {
            let avg_sentiment = recent_interactions
                .iter()
                .map(|i| i.sentiment_score.unwrap_or(0.0))
                .sum::<f32>()
                / recent_interactions.len() as f32;

            // Adjust embedding based on user's typical sentiment
            for i in 0..personalized.values.len() {
                personalized.values[i] *=
                    1.0 + (avg_sentiment * self.preference_weights.sentiment_influence);
            }
        }

        Ok(personalized)
    }

    /// Update user profile based on interaction
    pub fn update_user_profile(
        &mut self,
        user_id: &str,
        query: &str,
        response_feedback: Option<f32>,
        interaction_type: InteractionType,
    ) -> Result<()> {
        let interaction = UserInteraction {
            timestamp: chrono::Utc::now(),
            query: query.to_string(),
            interaction_type,
            response_feedback,
            sentiment_score: self.analyze_query_sentiment(query),
        };

        // Add to interaction history
        self.interaction_history
            .entry(user_id.to_string())
            .or_default()
            .push(interaction.clone());

        // Update user profile
        if let Some(profile) = self.user_profiles.get_mut(user_id) {
            profile.update_from_interaction(&interaction);
        }

        Ok(())
    }

    /// Get recent interactions for a user
    fn get_recent_interactions(&self, user_id: &str, limit: usize) -> Vec<&UserInteraction> {
        self.interaction_history
            .get(user_id)
            .map(|history| history.iter().rev().take(limit).collect())
            .unwrap_or_default()
    }

    /// Simple sentiment analysis for query
    fn analyze_query_sentiment(&self, query: &str) -> Option<f32> {
        let positive_words = ["good", "great", "excellent", "amazing", "wonderful"];
        let negative_words = ["bad", "terrible", "awful", "horrible", "disappointing"];

        let query_lower = query.to_lowercase();
        let positive_count = positive_words
            .iter()
            .filter(|&&word| query_lower.contains(word))
            .count();
        let negative_count = negative_words
            .iter()
            .filter(|&&word| query_lower.contains(word))
            .count();

        if positive_count + negative_count == 0 {
            return None;
        }

        let sentiment = (positive_count as f32 - negative_count as f32)
            / (positive_count + negative_count) as f32;
        Some(sentiment)
    }
}

/// User profile for personalization
#[derive(Debug, Clone)]
pub struct UserProfile {
    pub user_id: String,
    pub domain_preferences: HashMap<String, f32>,
    pub entity_preferences: HashMap<String, f32>,
    pub interaction_patterns: InteractionPatterns,
    pub language_preferences: Vec<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub last_updated: chrono::DateTime<chrono::Utc>,
}

impl UserProfile {
    pub fn new(user_id: String) -> Self {
        let now = chrono::Utc::now();
        Self {
            user_id,
            domain_preferences: HashMap::new(),
            entity_preferences: HashMap::new(),
            interaction_patterns: InteractionPatterns::default(),
            language_preferences: vec!["en".to_string()],
            created_at: now,
            last_updated: now,
        }
    }

    /// Update profile based on user interaction
    pub fn update_from_interaction(&mut self, interaction: &UserInteraction) {
        self.last_updated = chrono::Utc::now();

        // Update interaction patterns
        self.interaction_patterns.total_interactions += 1;
        match interaction.interaction_type {
            InteractionType::Query => self.interaction_patterns.query_count += 1,
            InteractionType::Feedback => self.interaction_patterns.feedback_count += 1,
            InteractionType::EntityLookup => self.interaction_patterns.entity_lookup_count += 1,
        }

        // Update average sentiment
        if let Some(sentiment) = interaction.sentiment_score {
            let current_avg = self.interaction_patterns.average_sentiment;
            let total = self.interaction_patterns.total_interactions as f32;
            self.interaction_patterns.average_sentiment =
                (current_avg * (total - 1.0) + sentiment) / total;
        }

        // Extract and update domain preferences from query
        self.extract_domain_preferences(&interaction.query);
    }

    /// Extract domain preferences from query text
    fn extract_domain_preferences(&mut self, query: &str) {
        let domains = [
            "science",
            "technology",
            "medicine",
            "business",
            "education",
            "sports",
            "entertainment",
            "politics",
            "history",
            "art",
        ];

        for domain in &domains {
            if query.to_lowercase().contains(domain) {
                #[allow(clippy::unnecessary_to_owned)]
                let current = self.domain_preferences.get(*domain).copied().unwrap_or(0.0);
                self.domain_preferences
                    .insert(domain.to_string(), current + 0.1);
            }
        }
    }
}

/// User interaction patterns
#[derive(Debug, Clone, Default)]
pub struct InteractionPatterns {
    pub total_interactions: u32,
    pub query_count: u32,
    pub feedback_count: u32,
    pub entity_lookup_count: u32,
    pub average_sentiment: f32,
    pub preferred_response_length: Option<usize>,
}

/// Types of user interactions
#[derive(Debug, Clone)]
pub enum InteractionType {
    Query,
    Feedback,
    EntityLookup,
}

/// User interaction record
#[derive(Debug, Clone)]
pub struct UserInteraction {
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub query: String,
    pub interaction_type: InteractionType,
    pub response_feedback: Option<f32>,
    pub sentiment_score: Option<f32>,
}

/// Weights for preference application
#[derive(Debug, Clone)]
pub struct PreferenceWeights {
    pub domain_boost: f32,
    pub entity_boost: f32,
    pub sentiment_influence: f32,
    pub recency_decay: f32,
}

impl Default for PreferenceWeights {
    fn default() -> Self {
        Self {
            domain_boost: 0.1,
            entity_boost: 0.15,
            sentiment_influence: 0.05,
            recency_decay: 0.95,
        }
    }
}

/// Multilingual support for chat integration
pub struct MultilingualSupport {
    supported_languages: Vec<String>,
    translation_cache: HashMap<String, String>,
    language_models: HashMap<String, LanguageModel>,
}

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

impl MultilingualSupport {
    pub fn new() -> Self {
        Self {
            supported_languages: vec![
                "en".to_string(),
                "es".to_string(),
                "fr".to_string(),
                "de".to_string(),
                "it".to_string(),
                "pt".to_string(),
                "zh".to_string(),
                "ja".to_string(),
                "ko".to_string(),
                "ar".to_string(),
                "hi".to_string(),
                "ru".to_string(),
            ],
            translation_cache: HashMap::new(),
            language_models: HashMap::new(),
        }
    }

    /// Translate text between languages
    pub async fn translate_text(
        &self,
        text: &str,
        source_lang: &str,
        target_lang: &str,
    ) -> Result<String> {
        if source_lang == target_lang {
            return Ok(text.to_string());
        }

        let cache_key = format!("{source_lang}:{target_lang}:{text}");
        if let Some(cached) = self.translation_cache.get(&cache_key) {
            return Ok(cached.clone());
        }

        // Mock translation implementation
        // In practice, this would call a translation service
        let translated = match target_lang {
            "es" => format!("[ES] {text}"),
            "fr" => format!("[FR] {text}"),
            "de" => format!("[DE] {text}"),
            "zh" => format!("[ZH] {text}"),
            _ => format!("[{}] {}", target_lang.to_uppercase(), text),
        };

        Ok(translated)
    }

    /// Detect language of input text
    pub async fn detect_language(&self, text: &str) -> Result<LanguageDetection> {
        // Simple language detection based on common words
        let text_lower = text.to_lowercase();

        let mut scores = HashMap::new();

        // English indicators
        let en_words = ["the", "and", "is", "hello", "world", "of", "to", "in"];
        let en_score = en_words
            .iter()
            .filter(|&&word| text_lower.contains(word))
            .count();
        scores.insert("en", en_score);

        // Spanish indicators
        let es_words = ["el", "y", "es", "hola", "buenos", "dias", "de", "en", "la"];
        let es_score = es_words
            .iter()
            .filter(|&&word| text_lower.contains(word))
            .count();
        scores.insert("es", es_score);

        // French indicators
        let fr_words = ["le", "et", "est", "bonjour", "de", "la", "les"];
        let fr_score = fr_words
            .iter()
            .filter(|&&word| text_lower.contains(word))
            .count();
        scores.insert("fr", fr_score);

        // German indicators
        let de_words = ["der", "und", "ist", "hallo", "von", "die", "das"];
        let de_score = de_words
            .iter()
            .filter(|&&word| text_lower.contains(word))
            .count();
        scores.insert("de", de_score);

        // Find language with highest score
        let detected_lang = scores
            .iter()
            .max_by_key(|&(_, &score)| score)
            .map(|(lang, _)| *lang)
            .unwrap_or("en");

        Ok(LanguageDetection {
            language_code: detected_lang.to_string(),
            confidence: 0.85,
            alternatives: vec![
                ("en".to_string(), 0.7),
                ("es".to_string(), 0.2),
                ("fr".to_string(), 0.1),
            ],
        })
    }

    /// Generate cross-lingual embeddings
    pub async fn generate_cross_lingual_embedding(
        &self,
        text: &str,
        source_lang: &str,
        target_lang: &str,
        model: &dyn EmbeddingModel,
    ) -> Result<Vector> {
        // For cross-lingual embeddings, we would typically:
        // 1. Use a multilingual embedding model
        // 2. Or translate text and generate embedding
        // 3. Or use language-specific models with alignment

        let translated_text = self.translate_text(text, source_lang, target_lang).await?;
        let embeddings = model.encode(&[translated_text]).await?;
        Ok(Vector::new(embeddings[0].clone()))
    }

    /// Align entities across languages
    pub async fn align_entities(
        &self,
        entity: &str,
        source_lang: &str,
        target_langs: &[String],
    ) -> Result<HashMap<String, String>> {
        let mut alignments = HashMap::new();

        for target_lang in target_langs {
            if target_lang == source_lang {
                alignments.insert(target_lang.clone(), entity.to_string());
                continue;
            }

            // Mock entity alignment - in practice would use knowledge bases
            let aligned_entity = match target_lang.as_str() {
                "es" => format!("{entity}_es"),
                "fr" => format!("{entity}_fr"),
                "de" => format!("{entity}_de"),
                "zh" => format!("{entity}_zh"),
                _ => format!("{entity}_{target_lang}"),
            };

            alignments.insert(target_lang.clone(), aligned_entity);
        }

        Ok(alignments)
    }
}

/// Language detection result
#[derive(Debug, Clone)]
pub struct LanguageDetection {
    pub language_code: String,
    pub confidence: f32,
    pub alternatives: Vec<(String, f32)>,
}

/// Language model information
#[derive(Debug, Clone)]
pub struct LanguageModel {
    pub model_id: String,
    pub language_code: String,
    pub model_type: String,
    pub embedding_dimension: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::TransE;
    use crate::ModelConfig;

    #[test]
    fn test_vector_store_bridge() {
        let config = ModelConfig::default().with_dimensions(10);
        let _model = TransE::new(config);

        let bridge = VectorStoreBridge::new();

        // Test URI generation
        let entity_uri = bridge.generate_entity_uri("test_entity");
        assert!(entity_uri.starts_with("kg:entity:"));

        let relation_uri = bridge.generate_relation_uri("test_relation");
        assert!(relation_uri.starts_with("kg:relation:"));
    }

    /// Regression test: `find_similar_entities`/`find_similar_relations` must
    /// return real nearest-neighbor results from the synced embeddings
    /// instead of always an empty `Vec`.
    #[tokio::test]
    async fn test_vector_store_bridge_find_similar_returns_real_results() -> Result<()> {
        let config = ModelConfig::default().with_dimensions(8);
        let mut model = TransE::new(config);

        for (s, p, o) in [
            ("alice", "knows", "bob"),
            ("bob", "knows", "carol"),
            ("carol", "knows", "alice"),
        ] {
            model.add_triple(crate::Triple::new(
                crate::NamedNode::new(s)?,
                crate::NamedNode::new(p)?,
                crate::NamedNode::new(o)?,
            ))?;
        }
        model.train(Some(1)).await?;

        let mut bridge = VectorStoreBridge::new();
        let stats = bridge.sync_model_embeddings(&model)?;
        assert_eq!(stats.entities_synced, 3);
        assert_eq!(stats.relations_synced, 1);
        assert!(stats.errors.is_empty(), "errors = {:?}", stats.errors);

        // Every other entity should be a candidate neighbor for "alice".
        let similar = bridge.find_similar_entities("alice", 2)?;
        assert!(!similar.is_empty(), "expected at least one similar entity");
        assert!(
            similar.iter().all(|(name, _)| name != "alice"),
            "the query entity itself must not appear in its own results: {:?}",
            similar
        );

        // Unknown entity must error rather than silently return empty.
        assert!(bridge.find_similar_entities("nobody", 2).is_err());

        Ok(())
    }

    /// A minimal `EmbeddingModel` whose `encode` deterministically maps text
    /// length to vector values, used to exercise `ChatIntegration` methods
    /// that need real (if simple) text encoding — unlike the KGE models in
    /// `crate::models`, which all reject `encode` outright.
    struct MockTextModel {
        config: ModelConfig,
        model_id: uuid::Uuid,
        entities: Vec<String>,
    }

    impl MockTextModel {
        fn new(dimensions: usize, entities: Vec<String>) -> Self {
            Self {
                config: ModelConfig::default().with_dimensions(dimensions),
                model_id: uuid::Uuid::new_v4(),
                entities,
            }
        }
    }

    #[async_trait::async_trait]
    impl EmbeddingModel for MockTextModel {
        fn config(&self) -> &ModelConfig {
            &self.config
        }
        fn model_id(&self) -> &uuid::Uuid {
            &self.model_id
        }
        fn model_type(&self) -> &'static str {
            "MockText"
        }
        fn add_triple(&mut self, _triple: crate::Triple) -> Result<()> {
            Ok(())
        }
        async fn train(&mut self, _epochs: Option<usize>) -> Result<crate::TrainingStats> {
            Ok(crate::TrainingStats {
                epochs_completed: 1,
                final_loss: 0.0,
                training_time_seconds: 0.0,
                convergence_achieved: true,
                loss_history: vec![0.0],
            })
        }
        fn get_entity_embedding(&self, entity: &str) -> Result<Vector> {
            Ok(Vector::new(vec![
                entity.len() as f32;
                self.config.dimensions
            ]))
        }
        fn get_relation_embedding(&self, relation: &str) -> Result<Vector> {
            Ok(Vector::new(vec![
                relation.len() as f32;
                self.config.dimensions
            ]))
        }
        fn score_triple(&self, _subject: &str, _predicate: &str, _object: &str) -> Result<f64> {
            Ok(0.0)
        }
        fn predict_objects(
            &self,
            _subject: &str,
            _predicate: &str,
            _k: usize,
        ) -> Result<Vec<(String, f64)>> {
            Ok(vec![])
        }
        fn predict_subjects(
            &self,
            _predicate: &str,
            _object: &str,
            _k: usize,
        ) -> Result<Vec<(String, f64)>> {
            Ok(vec![])
        }
        fn predict_relations(
            &self,
            _subject: &str,
            _object: &str,
            _k: usize,
        ) -> Result<Vec<(String, f64)>> {
            Ok(vec![])
        }
        fn get_entities(&self) -> Vec<String> {
            self.entities.clone()
        }
        fn get_relations(&self) -> Vec<String> {
            vec![]
        }
        fn get_stats(&self) -> crate::ModelStats {
            crate::ModelStats {
                num_entities: self.entities.len(),
                dimensions: self.config.dimensions,
                is_trained: true,
                ..Default::default()
            }
        }
        fn save(&self, _path: &str) -> Result<()> {
            Ok(())
        }
        fn load(&mut self, _path: &str) -> Result<()> {
            Ok(())
        }
        fn clear(&mut self) {}
        fn is_trained(&self) -> bool {
            true
        }
        async fn encode(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
            Ok(texts
                .iter()
                .map(|t| vec![t.len() as f32; self.config.dimensions])
                .collect())
        }
    }

    /// Regression test: `extract_relevant_entities` must find entities that
    /// appear as a substring of the query using the windowed-index rewrite.
    #[test]
    fn test_extract_relevant_entities_finds_substring_matches() -> Result<()> {
        let model = MockTextModel::new(
            4,
            vec!["alice".to_string(), "bob".to_string(), "carol".to_string()],
        );
        let integration = ChatIntegration::new(Box::new(model));

        let relevant = integration.extract_relevant_entities("Alice met Bob yesterday.")?;
        assert!(relevant.contains(&"alice".to_string()));
        assert!(relevant.contains(&"bob".to_string()));
        assert!(!relevant.contains(&"carol".to_string()));

        Ok(())
    }

    /// Regression test: `generate_context_embedding` must actually encode and
    /// combine the recent messages via the model, instead of returning a
    /// fixed all-zero placeholder vector regardless of input.
    #[tokio::test]
    async fn test_generate_context_embedding_reflects_message_content() -> Result<()> {
        let model = MockTextModel::new(4, vec![]);
        let integration = ChatIntegration::new(Box::new(model));

        let short = integration
            .generate_context_embedding(&["hi".to_string()])
            .await?;
        let long = integration
            .generate_context_embedding(&["a much longer message here".to_string()])
            .await?;

        assert_eq!(short.values.len(), 4);
        assert_ne!(
            short.values, long.values,
            "different message content should produce different context embeddings"
        );

        assert!(integration.generate_context_embedding(&[]).await.is_err());

        Ok(())
    }

    #[test]
    fn test_sparql_integration() -> Result<()> {
        let config = ModelConfig::default().with_dimensions(10);
        let model = TransE::new(config);

        let integration = SparqlIntegration::new(Box::new(model));

        let test_query = "SELECT ?s ?o WHERE { ?s <http://example.org/knows> ?o }";
        let enhanced = integration.enhance_query(test_query)?;

        assert_eq!(enhanced.original_query, test_query);
        assert!(!enhanced.suggestions.is_empty());

        Ok(())
    }

    #[test]
    fn test_personalization_engine() {
        let mut engine = PersonalizationEngine::new();
        let user_id = "test_user";

        // Test user profile creation
        let profile = engine.get_user_profile(user_id).expect("should succeed");
        assert_eq!(profile.user_id, user_id);

        // Test interaction update
        engine
            .update_user_profile(
                user_id,
                "What is machine learning?",
                Some(0.9),
                InteractionType::Query,
            )
            .expect("should succeed");

        let history = engine.get_recent_interactions(user_id, 5);
        assert_eq!(history.len(), 1);
    }

    #[tokio::test]
    async fn test_multilingual_support() -> Result<()> {
        let multilingual = MultilingualSupport::new();

        // Test language detection with English text
        let detection_en = multilingual.detect_language("Hello world").await?;
        assert_eq!(detection_en.language_code, "en");

        // Test language detection with Spanish text
        let detection_es = multilingual.detect_language("Hola y buenos dias").await?;
        assert_eq!(detection_es.language_code, "es");

        // Test translation
        let translated = multilingual
            .translate_text("Hello world", "en", "es")
            .await?;
        assert!(translated.contains("[ES]"));

        // Test entity alignment
        let alignments = multilingual
            .align_entities("person", "en", &["es".to_string(), "fr".to_string()])
            .await?;
        assert_eq!(alignments.len(), 2);

        Ok(())
    }
}