rag-module 0.6.7

Enterprise RAG module with chat context storage, vector search, session management, and model downloading. Rust implementation with Node.js compatibility.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
//! Embedded Qdrant Vector Store Implementation
//! Uses local file-based storage to simulate embedded Qdrant functionality

use async_trait::async_trait;
use anyhow::{Result, anyhow};
use serde::{Serialize, Deserialize};
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;
use chrono::Utc;
use tracing::{warn, info};
use std::time::Instant;

use crate::types::{Document, SearchOptions, SearchResult, SearchFilter};
use crate::services::EncryptionService;
use super::vector_store::{VectorStore, CollectionInfo, CollectionHealth};
use super::vector_store::utils::{cosine_similarity, generate_dummy_vector};

/// Collection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionConfig {
    pub name: String,
    pub dimensions: usize,
    pub distance_metric: String,
}

impl Default for CollectionConfig {
    fn default() -> Self {
        Self {
            name: "default".to_string(),
            dimensions: 1024,
            distance_metric: "Cosine".to_string(),
        }
    }
}

/// HNSW configuration for similarity search
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HnswConfig {
    pub m: usize,
    pub ef_construction: usize,
    pub ef_search: usize,
    pub max_connections: usize,
}

impl Default for HnswConfig {
    fn default() -> Self {
        Self {
            m: 16,
            ef_construction: 200,
            ef_search: 50,
            max_connections: 16,
        }
    }
}

/// Vector index entry matching Node.js format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorIndexEntry {
    #[serde(rename = "vectorId")]
    pub vector_id: String,
    #[serde(rename = "documentId")]
    pub document_id: String,
    pub position: usize,
}

/// Vector index structure matching Node.js format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorIndex {
    pub vectors: Vec<VectorIndexEntry>,
    pub dimensions: usize,
    pub count: usize,
    #[serde(rename = "lastUpdated")]
    pub last_updated: String,
}

/// Collection file paths (now under user directories)
#[derive(Debug, Clone)]
pub struct CollectionFiles {
    pub metadata_file: PathBuf,
    pub documents_file: PathBuf,
    pub vectors_file: PathBuf,
    pub vector_index_file: PathBuf,
    pub user_id: String,
}

/// LRU Cache entry with timestamp for eviction (like Node.js implementation)
#[derive(Debug, Clone)]
pub struct CacheEntry<T> {
    pub data: T,
    pub last_accessed: Instant,
}

/// Memory-efficient LRU cache with size limits (mirroring Node.js LocalFileVectorStore)
#[derive(Debug)]
pub struct LruCache<T> {
    entries: HashMap<String, CacheEntry<T>>,
    access_order: VecDeque<String>,
    max_size: usize,
}

impl<T> LruCache<T> {
    pub fn new(max_size: usize) -> Self {
        Self {
            entries: HashMap::new(),
            access_order: VecDeque::new(),
            max_size,
        }
    }

    pub fn get(&mut self, key: &str) -> Option<&T> {
        if let Some(entry) = self.entries.get_mut(key) {
            entry.last_accessed = Instant::now();
            // Move to end of access order (most recently used)
            self.access_order.retain(|k| k != key);
            self.access_order.push_back(key.to_string());
            Some(&entry.data)
        } else {
            None
        }
    }

    pub fn insert(&mut self, key: String, data: T) {
        // Simple LRU cache implementation like Node.js
        if self.entries.len() >= self.max_size {
            if let Some(oldest_key) = self.access_order.pop_front() {
                self.entries.remove(&oldest_key);
            }
        }

        let entry = CacheEntry {
            data,
            last_accessed: Instant::now(),
        };

        // Remove existing entry if present
        if self.entries.contains_key(&key) {
            self.access_order.retain(|k| k != &key);
        }

        self.entries.insert(key.clone(), entry);
        self.access_order.push_back(key);
    }

    pub fn remove(&mut self, key: &str) -> Option<T> {
        if let Some(entry) = self.entries.remove(key) {
            self.access_order.retain(|k| k != key);
            Some(entry.data)
        } else {
            None
        }
    }

    pub fn clear(&mut self) {
        self.entries.clear();
        self.access_order.clear();
    }

    pub fn len(&self) -> usize {
        self.entries.len()
    }
}

/// Embedded Qdrant Vector Store
pub struct EmbeddedQdrantVectorStore {
    base_path: PathBuf,
    data_path: PathBuf,
    // segments_path: PathBuf,
    encryption_service: Arc<EncryptionService>,
    
    // Collections configuration
    collections: Arc<RwLock<HashMap<String, CollectionConfig>>>,
    collection_files: Arc<RwLock<HashMap<String, CollectionFiles>>>,
    
    // HNSW configuration
    hnsw_config: HnswConfig,
    
    // Memory-optimized LRU caches (like Node.js LocalFileVectorStore)
    document_cache: Arc<RwLock<LruCache<HashMap<String, Document>>>>, // collection -> documents (max 100 collections)
    vector_cache: Arc<RwLock<LruCache<Vec<Vec<f32>>>>>,              // collection -> vectors (max 50 collections)
    index_cache: Arc<RwLock<LruCache<VectorIndex>>>,                 // collection -> vector index (max 100 collections)

    // File-level locks to prevent concurrent write race conditions
    // Maps "userId_collectionName" -> Mutex for atomic batch operations
    // CRITICAL: Prevents lost updates when multiple threads write to same files (documents, vectors, index, metadata)
    file_locks: Arc<std::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>>,

    dimensions: Arc<RwLock<Option<usize>>>,
    initialized: Arc<RwLock<bool>>,
    current_user_context: Arc<RwLock<Option<String>>>,
}

impl EmbeddedQdrantVectorStore {
    /// Create a new embedded Qdrant vector store
    pub async fn new(
        base_path: impl AsRef<Path>,
        encryption_service: Arc<EncryptionService>,
    ) -> Result<Self> {
        let base_path = base_path.as_ref().to_path_buf();
        let data_path = base_path.join("qdrant-data");
        // let segments_path = data_path.join("segments");

        // Initialize default collections
        let mut collections = HashMap::new();
        collections.insert(
            "chat_history".to_string(),
            CollectionConfig {
                name: "chat_history".to_string(),
                dimensions: 1, // 1D dummy vectors for chat
                distance_metric: "Cosine".to_string(),
            },
        );
        collections.insert(
            "aws_estate".to_string(),
            CollectionConfig {
                name: "aws_estate".to_string(),
                dimensions: 1024, // 1024D BGE-M3 vectors for estate
                distance_metric: "Cosine".to_string(),
            },
        );

        // Auto-discover existing collections from filesystem
        if data_path.exists() {
            if let Ok(entries) = tokio::fs::read_dir(&data_path).await {
                let mut dir_entries = entries;
                while let Ok(Some(entry)) = dir_entries.next_entry().await {
                    if let Ok(path) = entry.path().canonicalize() {
                        if path.is_dir() {
                            // Check for user-specific directories
                            if let Ok(user_entries) = tokio::fs::read_dir(&path).await {
                                let mut user_dir = user_entries;
                                while let Ok(Some(user_entry)) = user_dir.next_entry().await {
                                    let file_name = user_entry.file_name();
                                    let file_name_str = file_name.to_string_lossy();

                                    // Look for collection files pattern: {collection}-documents.json
                                    if file_name_str.ends_with("-documents.json") {
                                        let collection_name = file_name_str
                                            .strip_suffix("-documents.json")
                                            .unwrap()
                                            .to_string();

                                        // Don't overwrite existing registrations
                                        if !collections.contains_key(&collection_name) {
                                            info!("📁 Auto-discovered collection: {}", collection_name);
                                            collections.insert(
                                                collection_name.clone(),
                                                CollectionConfig {
                                                    name: collection_name.clone(),
                                                    dimensions: 1024, // Default to BGE-M3 dimensions
                                                    distance_metric: "Cosine".to_string(),
                                                },
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(Self {
            base_path,
            data_path,
            // segments_path,
            encryption_service,
            collections: Arc::new(RwLock::new(collections)),
            collection_files: Arc::new(RwLock::new(HashMap::new())),
            hnsw_config: HnswConfig::default(),
            document_cache: Arc::new(RwLock::new(LruCache::new(100))), // Max 100 collections in cache
            vector_cache: Arc::new(RwLock::new(LruCache::new(50))),    // Max 50 vector collections in cache
            index_cache: Arc::new(RwLock::new(LruCache::new(100))),    // Max 100 index collections in cache
            file_locks: Arc::new(std::sync::Mutex::new(HashMap::new())), // File-level locks for atomic batch operations
            dimensions: Arc::new(RwLock::new(None)),
            initialized: Arc::new(RwLock::new(false)),
            current_user_context: Arc::new(RwLock::new(None)),
        })
    }
    
    /// Ensure the vector store is initialized
    async fn ensure_initialized(&self) -> Result<()> {
        if !*self.initialized.read().await {
            return Err(anyhow!("Vector store not initialized"));
        }
        Ok(())
    }

    /// Set the current user context for file organization
    pub async fn set_user_context(&self, user_id: &str) {
        let mut context = self.current_user_context.write().await;
        *context = Some(user_id.to_string());
    }
    
    /// Initialize collection file paths for a specific user (like Node.js)
    async fn initialize_user_collection_files(&self, user_id: &str) -> Result<()> {
        let collections = self.collections.read().await;
        let mut collection_files = self.collection_files.write().await;

        // Create user directory under qdrant-data
        let user_dir = self.data_path.join(user_id);
        tokio::fs::create_dir_all(&user_dir).await?;

        for (name, _) in collections.iter() {
            let collection_key = format!("{}-{}", user_id, name);
            let files = CollectionFiles {
                metadata_file: user_dir.join(format!("{}-metadata.json", name)),
                documents_file: user_dir.join(format!("{}-documents.json", name)),
                vectors_file: user_dir.join(format!("{}-vectors.bin", name)),
                vector_index_file: user_dir.join(format!("{}-vector-index.json", name)),
                user_id: user_id.to_string(),
            };
            collection_files.insert(collection_key, files);
        }

        Ok(())
    }
    
    /// Lazy loading - only load data on first access (like Node.js implementation)
    async fn load_existing_data(&self) -> Result<()> {
        // Don't preload all collections - use lazy loading instead
        // This prevents memory issues by only loading data when accessed
        info!("Initialized with lazy loading - collections will load on first access");
        Ok(())
    }

    /// Load documents for a collection on-demand with caching
    async fn get_collection_documents(&self, collection_name: &str) -> Result<HashMap<String, Document>> {
        // For chat_history collection, always load from disk to ensure we get all persisted documents
        if collection_name == "chat_history" {
            // Clear cache first to force fresh load from disk
            {
                let mut cache = self.document_cache.write().await;
                cache.remove(collection_name);
            }

            // Load from disk
            let documents = self.load_documents(collection_name).await?;
            let mut doc_map = HashMap::new();
            for doc in documents {
                doc_map.insert(doc.id.clone(), doc);
            }

            // Cache the loaded documents
            {
                let mut cache = self.document_cache.write().await;
                cache.insert(collection_name.to_string(), doc_map.clone());
            }

            return Ok(doc_map);
        }

        // For other collections, use normal caching behavior
        // Check cache first
        {
            let mut cache = self.document_cache.write().await;
            if let Some(docs) = cache.get(collection_name) {
                return Ok(docs.clone());
            }
        }

        // Load from disk if not in cache
        let documents = self.load_documents(collection_name).await?;
        let mut doc_map = HashMap::new();
        for doc in documents {
            doc_map.insert(doc.id.clone(), doc);
        }

        // Cache the loaded documents
        {
            let mut cache = self.document_cache.write().await;
            cache.insert(collection_name.to_string(), doc_map.clone());
        }

        Ok(doc_map)
    }

    /// Load vector index for a user collection on-demand with caching
    // async fn get_user_collection_index(&self, user_id: &str, collection_name: &str) -> Result<VectorIndex> {
    //     let collection_key = format!("{}-{}", user_id, collection_name);
    //
    //     // Check cache first
    //     {
    //         let mut cache = self.index_cache.write().await;
    //         if let Some(index) = cache.get(&collection_key) {
    //             return Ok(index.clone());
    //         }
    //     }
    //
    //     // Load from disk if not in cache
    //     let index = self.load_user_vector_index(user_id, collection_name).await?;
    //
    //     // Cache the loaded index
    //     {
    //         let mut cache = self.index_cache.write().await;
    //         cache.insert(collection_key, index.clone());
    //     }
    //
    //     Ok(index)
    // }

    /// Load vectors for a collection on-demand with caching
    // async fn get_collection_vectors(&self, collection_name: &str) -> Result<Vec<Vec<f32>>> {
    //     // Check cache first
    //     {
    //         let mut cache = self.vector_cache.write().await;
    //         if let Some(vectors) = cache.get(collection_name) {
    //             return Ok(vectors.clone());
    //         }
    //     }
    //
    //     // Load from disk if not in cache
    //     let vectors = self.load_vectors_binary(collection_name).await?;
    //
    //     // Cache the loaded vectors
    //     {
    //         let mut cache = self.vector_cache.write().await;
    //         cache.insert(collection_name.to_string(), vectors.clone());
    //     }
    //
    //     Ok(vectors)
    // }
    
    /// Load documents from file
    async fn load_documents(&self, collection_name: &str) -> Result<Vec<Document>> {
        // All collections use user-specific files now (uniform handling)
        if let Some(user_id) = self.current_user_context.read().await.as_ref() {
            return self.load_user_collection_documents(user_id, collection_name).await;
        }

        // No user context set - return empty
        // (In server mode, collections are per-server; in embedded mode, collections are per-user)
        Ok(Vec::new())
    }
    
    /// Save documents to file
    async fn save_documents(&self, collection_name: &str, documents: &[Document]) -> Result<()> {
        // All collections now use user-specific encrypted files
        // This method is deprecated - individual collections should use save_user_collection_document instead
        warn!("save_documents is deprecated - collections should use user-specific encrypted storage");
        Ok(())
    }

    /// Save document to user-specific collection file with encryption and wrapper format
    async fn save_user_collection_document(&self, collection_name: &str, user_id: &str, document: &Document) -> Result<()> {
        // Create user directory path under qdrant-data
        let user_dir = self.data_path.join(user_id);
        tokio::fs::create_dir_all(&user_dir).await?;

        // Create user-specific collection file path
        let collection_file = user_dir.join(format!("{}-documents.json", collection_name));

        // Load existing documents
        let mut existing_docs: Vec<Document> = if collection_file.exists() {
            let content = tokio::fs::read_to_string(&collection_file).await?;
            if !content.trim().is_empty() {
                // Try to parse as wrapper format first
                if let Ok(wrapper) = serde_json::from_str::<serde_json::Value>(&content) {
                    if let Some(documents) = wrapper.get("documents") {
                        serde_json::from_value(documents.clone()).unwrap_or_default()
                    } else {
                        // Fallback: try to parse as old array format
                        serde_json::from_str(&content).unwrap_or_default()
                    }
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        // Remove any existing document with the same ID to prevent duplicates
        existing_docs.retain(|d| d.id != document.id);
        // Then add the new document
        existing_docs.push(document.clone());

        // Create wrapper struct with specific field ordering (same as chat history)
        #[derive(serde::Serialize)]
        struct DocumentsWrapper<'a> {
            documents: &'a Vec<Document>,
            count: usize,
            #[serde(rename = "lastModified")]
            last_modified: String,
        }

        let wrapper = DocumentsWrapper {
            documents: &existing_docs,
            count: existing_docs.len(),
            last_modified: chrono::Utc::now().to_rfc3339(),
        };

        // Save with wrapper format
        let content = serde_json::to_string_pretty(&wrapper)?;
        tokio::fs::write(&collection_file, content).await?;

        Ok(())
    }

    /// BATCH SAVE - Save multiple documents to user-specific collection file in ONE operation (PERMANENT FIX)
    /// This replaces the loop-based save that was causing 89% data loss
    async fn save_user_collection_documents_batch(&self, collection_name: &str, user_id: &str, documents: &[Document]) -> Result<()> {
        if documents.is_empty() {
            return Ok(());
        }

        let batch_start = std::time::Instant::now();
        let user_dir = self.data_path.join(user_id);
        tokio::fs::create_dir_all(&user_dir).await?;

        let collection_file = user_dir.join(format!("{}-documents.json", collection_name));

        // Load existing documents
        let mut existing_docs: Vec<Document> = if collection_file.exists() {
            let content = tokio::fs::read_to_string(&collection_file).await?;
            if !content.trim().is_empty() {
                if let Ok(wrapper) = serde_json::from_str::<serde_json::Value>(&content) {
                    if let Some(docs) = wrapper.get("documents") {
                        serde_json::from_value(docs.clone()).unwrap_or_default()
                    } else {
                        serde_json::from_str(&content).unwrap_or_default()
                    }
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        let original_count = existing_docs.len();

        // Create set of new document IDs for efficient lookup
        let new_ids: std::collections::HashSet<String> = documents.iter().map(|d| d.id.clone()).collect();

        // Remove documents that will be replaced (same ID)
        existing_docs.retain(|d| !new_ids.contains(&d.id));

        // Add all new documents at once
        existing_docs.extend_from_slice(documents);

        // Create wrapper
        #[derive(serde::Serialize)]
        struct DocumentsWrapper<'a> {
            documents: &'a Vec<Document>,
            count: usize,
            #[serde(rename = "lastModified")]
            last_modified: String,
        }

        let wrapper = DocumentsWrapper {
            documents: &existing_docs,
            count: existing_docs.len(),
            last_modified: chrono::Utc::now().to_rfc3339(),
        };

        let content = serde_json::to_string_pretty(&wrapper)?;
        tokio::fs::write(&collection_file, content).await?;

        let duration = batch_start.elapsed();
        info!("✅ EMBEDDED BATCH SAVE SUCCESS: Saved {} documents to local file in {:?} (was: {}, now: {})",
            documents.len(), duration, original_count, existing_docs.len());

        Ok(())
    }

    /// Load documents from user-specific collection file
    async fn load_user_collection_documents(&self, user_id: &str, collection_name: &str) -> Result<Vec<Document>> {
        let user_dir = self.data_path.join(user_id);
        let collection_file = user_dir.join(format!("{}-documents.json", collection_name));

        if !collection_file.exists() {
            return Ok(Vec::new());
        }

        let content = tokio::fs::read_to_string(&collection_file).await?;
        if content.trim().is_empty() {
            return Ok(Vec::new());
        }

        // Try to parse as wrapper format first
        if let Ok(wrapper) = serde_json::from_str::<serde_json::Value>(&content) {
            if let Some(documents) = wrapper.get("documents") {
                Ok(serde_json::from_value(documents.clone()).unwrap_or_default())
            } else {
                // Fallback: try to parse as old array format
                Ok(serde_json::from_str(&content).unwrap_or_default())
            }
        } else {
            Ok(Vec::new())
        }
    }

    // Load user-specific vector index from file (Node.js format)
    async fn load_user_vector_index(&self, user_id: &str, collection_name: &str) -> Result<VectorIndex> {
        let collection_key = format!("{}-{}", user_id, collection_name);
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(&collection_key)
            .ok_or_else(|| anyhow!("Collection {} for user {} not found", collection_name, user_id))?;
    
        if !files.vector_index_file.exists() {
            // Return empty index with proper structure
            return Ok(VectorIndex {
                vectors: Vec::new(),
                dimensions: 1024, // Default to BGE-M3 dimensions
                count: 0,
                last_updated: Utc::now().to_rfc3339(),
            });
        }
    
        let content = tokio::fs::read_to_string(&files.vector_index_file).await?;
        let index: VectorIndex = serde_json::from_str(&content)?;
    
        Ok(index)
    }
    
    // Load user-specific vector index from file (Node.js format)
    

    /// Save user-specific vector index to file (Node.js format)
    async fn save_user_vector_index(&self, user_id: &str, collection_name: &str, index: &VectorIndex) -> Result<()> {
        let collection_key = format!("{}-{}", user_id, collection_name);
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(&collection_key)
            .ok_or_else(|| anyhow!("Collection {} for user {} not found", collection_name, user_id))?;

        let content = serde_json::to_string_pretty(index)?;
        tokio::fs::write(&files.vector_index_file, content).await?;

        Ok(())
    }

    /// Save vectors to binary file (like Node.js implementation)
    async fn save_vectors_binary(&self, collection_name: &str, vectors: &[Vec<f32>]) -> Result<()> {
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(collection_name)
            .ok_or_else(|| anyhow!("Collection {} not found", collection_name))?;

        // Create binary vector data
        let mut binary_data = Vec::new();

        // Write number of vectors (4 bytes)
        binary_data.extend_from_slice(&(vectors.len() as u32).to_le_bytes());

        // Write dimension count (4 bytes)
        if !vectors.is_empty() {
            binary_data.extend_from_slice(&(vectors[0].len() as u32).to_le_bytes());
        } else {
            binary_data.extend_from_slice(&0u32.to_le_bytes());
        }

        // Write all vectors
        for vector in vectors {
            for &value in vector {
                binary_data.extend_from_slice(&value.to_le_bytes());
            }
        }

        tokio::fs::write(&files.vectors_file, binary_data).await?;
        Ok(())
    }

    /// Load vectors from binary file
    async fn load_vectors_binary(&self, collection_name: &str) -> Result<Vec<Vec<f32>>> {
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(collection_name)
            .ok_or_else(|| anyhow!("Collection {} not found", collection_name))?;

        if !files.vectors_file.exists() {
            return Ok(Vec::new());
        }

        let binary_data = tokio::fs::read(&files.vectors_file).await?;

        if binary_data.len() < 8 {
            return Ok(Vec::new());
        }

        let mut offset = 0;

        // Read number of vectors
        let vector_count = u32::from_le_bytes([
            binary_data[offset], binary_data[offset + 1],
            binary_data[offset + 2], binary_data[offset + 3]
        ]) as usize;
        offset += 4;

        // Read dimensions
        let dimensions = u32::from_le_bytes([
            binary_data[offset], binary_data[offset + 1],
            binary_data[offset + 2], binary_data[offset + 3]
        ]) as usize;
        offset += 4;

        let mut vectors = Vec::new();

        // Read all vectors
        for _ in 0..vector_count {
            let mut vector = Vec::new();
            for _ in 0..dimensions {
                if offset + 4 <= binary_data.len() {
                    let value = f32::from_le_bytes([
                        binary_data[offset], binary_data[offset + 1],
                        binary_data[offset + 2], binary_data[offset + 3]
                    ]);
                    vector.push(value);
                    offset += 4;
                }
            }
            if vector.len() == dimensions {
                vectors.push(vector);
            }
        }

        Ok(vectors)
    }

    /// Memory monitoring method (like Node.js implementation)
    pub async fn get_memory_usage(&self) -> (usize, usize, usize) {
        let doc_cache = self.document_cache.read().await;
        let vec_cache = self.vector_cache.read().await;
        let idx_cache = self.index_cache.read().await;

        let doc_count = doc_cache.len();
        let vec_count = vec_cache.len();
        let idx_count = idx_cache.len();

        (doc_count, vec_count, idx_count)
    }

    /// Clear caches to free memory (like Node.js cache management)
    pub async fn clear_caches(&self) {
        {
            let mut doc_cache = self.document_cache.write().await;
            doc_cache.clear();
        }
        {
            let mut vec_cache = self.vector_cache.write().await;
            vec_cache.clear();
        }
        {
            let mut idx_cache = self.index_cache.write().await;
            idx_cache.clear();
        }
        info!("All caches cleared to free memory");
    }


    /// Save user-specific vectors to binary file
    async fn save_user_vectors_binary(&self, user_id: &str, collection_name: &str, vectors: &[Vec<f32>]) -> Result<()> {
        let collection_key = format!("{}-{}", user_id, collection_name);
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(&collection_key)
            .ok_or_else(|| anyhow!("Collection {} for user {} not found", collection_name, user_id))?;

        // Create binary vector data
        let mut binary_data = Vec::new();

        // Write number of vectors (4 bytes)
        binary_data.extend_from_slice(&(vectors.len() as u32).to_le_bytes());

        // Write dimension count (4 bytes)
        if !vectors.is_empty() {
            binary_data.extend_from_slice(&(vectors[0].len() as u32).to_le_bytes());
        } else {
            binary_data.extend_from_slice(&0u32.to_le_bytes());
        }

        // Write all vectors
        for vector in vectors {
            for &value in vector {
                binary_data.extend_from_slice(&value.to_le_bytes());
            }
        }

        tokio::fs::write(&files.vectors_file, binary_data).await?;
        Ok(())
    }

    /// Save user-specific collection metadata
    async fn save_user_collection_metadata(&self, user_id: &str, collection_name: &str) -> Result<()> {
        let collection_key = format!("{}-{}", user_id, collection_name);
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(&collection_key)
            .ok_or_else(|| anyhow!("Collection {} for user {} not found", collection_name, user_id))?;

        let collections = self.collections.read().await;
        let config = collections.get(collection_name)
            .ok_or_else(|| anyhow!("Collection config {} not found", collection_name))?;

        // Use lazy loading to get document count
        let collection_docs = self.get_collection_documents(collection_name).await?;

        let metadata = serde_json::json!({
            "collection_name": collection_name,
            "user_id": user_id,
            "dimensions": config.dimensions,
            "distance_metric": config.distance_metric,
            "document_count": collection_docs.len(),
            "created_at": Utc::now().to_rfc3339(),
            "hnsw_config": {
                "m": self.hnsw_config.m,
                "ef_construction": self.hnsw_config.ef_construction,
                "ef_search": self.hnsw_config.ef_search,
                "max_connections": self.hnsw_config.max_connections
            }
        });

        let content = serde_json::to_string_pretty(&metadata)?;
        tokio::fs::write(&files.metadata_file, content).await?;

        Ok(())
    }

    /// Save collection metadata (like Node.js implementation)
    async fn save_collection_metadata(&self, collection_name: &str) -> Result<()> {
        let collection_files = self.collection_files.read().await;
        let files = collection_files.get(collection_name)
            .ok_or_else(|| anyhow!("Collection {} not found", collection_name))?;

        let collections = self.collections.read().await;
        let config = collections.get(collection_name)
            .ok_or_else(|| anyhow!("Collection config {} not found", collection_name))?;

        // Use lazy loading to get document count
        let collection_docs = self.get_collection_documents(collection_name).await?;

        let metadata = serde_json::json!({
            "collection_name": collection_name,
            "dimensions": config.dimensions,
            "distance_metric": config.distance_metric,
            "document_count": collection_docs.len(),
            "created_at": Utc::now().to_rfc3339(),
            "hnsw_config": {
                "m": self.hnsw_config.m,
                "ef_construction": self.hnsw_config.ef_construction,
                "ef_search": self.hnsw_config.ef_search,
                "max_connections": self.hnsw_config.max_connections
            }
        });

        let content = serde_json::to_string_pretty(&metadata)?;
        tokio::fs::write(&files.metadata_file, content).await?;

        Ok(())
    }

    /// Generate and save all vector files for a user collection (Node.js format)
    async fn generate_user_vector_files(&self, user_id: &str, collection_name: &str) -> Result<()> {
        // Use lazy loading to get documents
        let collection_docs = self.get_collection_documents(collection_name).await?;
        let collection_key = format!("{}-{}", user_id, collection_name);

        // Get collection config for dimensions
        let collections = self.collections.read().await;
        let collection_config = collections.get(collection_name)
            .ok_or_else(|| anyhow!("Collection config {} not found", collection_name))?;
        let dimensions = collection_config.dimensions;

        // Extract vectors and build index entries with vectorId (Node.js format)
        let mut vectors = Vec::new();
        let mut vector_entries = Vec::new();

        for (position, (doc_id, document)) in collection_docs.iter().enumerate() {
            if let Some(embedding) = &document.embedding {
                let vector_id = Uuid::new_v4().to_string(); // Generate unique vectorId

                vectors.push(embedding.clone());
                vector_entries.push(VectorIndexEntry {
                    vector_id,
                    document_id: doc_id.clone(),
                    position,
                });
            }
        }

        // Create vector index in Node.js format
        let vector_index = VectorIndex {
            vectors: vector_entries,
            dimensions,
            count: vectors.len(),
            last_updated: Utc::now().to_rfc3339(),
        };

        // Update caches
        {
            let mut vec_cache = self.vector_cache.write().await;
            vec_cache.insert(collection_key.clone(), vectors.clone());
        }
        {
            let mut idx_cache = self.index_cache.write().await;
            idx_cache.insert(collection_key, vector_index.clone());
        }

        // Save all vector files under user directory
        self.save_user_vectors_binary(user_id, collection_name, &vectors).await?;
        self.save_user_vector_index(user_id, collection_name, &vector_index).await?;
        self.save_user_collection_metadata(user_id, collection_name).await?;

        info!(
            "Generated vector files for user '{}' collection '{}': {} vectors saved",
            user_id, collection_name, vectors.len()
        );

        Ok(())
    }
    
    /// Perform HNSW-like search with lazy loading
    async fn hnsw_search(
        &self,
        collection_name: &str,
        query_embedding: &[f32],
        limit: usize,
    ) -> Result<Vec<(String, f32)>> {
        // Get current user context for user-specific document loading
        let user_id = if let Some(context) = self.current_user_context.read().await.as_ref() {
            context.clone()
        } else {
            return Err(anyhow!("No user context set for vector search"));
        };
        
        // Load user-specific documents instead of global documents
        let documents = self.load_user_collection_documents(&user_id, collection_name).await?;
        let mut collection_docs = HashMap::new();
        for doc in documents {
            collection_docs.insert(doc.id.clone(), doc);
        }

        let mut candidates: Vec<(String, f32)> = Vec::new();

        // Calculate similarities for all documents
        for (doc_id, document) in collection_docs.iter() {
            if let Some(doc_embedding) = &document.embedding {
                let similarity = cosine_similarity(query_embedding, doc_embedding)?;
                candidates.push((doc_id.clone(), similarity));
            }
        }

        // Sort by similarity (descending) and take top results
        candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
        candidates.truncate(limit);

        Ok(candidates)
    }
    
    /// Check if filter matches document metadata
    async fn matches_filter(&self, document: &Document, filter: &SearchFilter) -> Result<bool> {
        if let Some(must_conditions) = &filter.must {
            for condition in must_conditions {
                let metadata_value = document.metadata.get(&condition.key);
                
                match &condition.r#match {
                    crate::types::MatchCondition::Value { value } => {
                        if metadata_value != Some(value) {
                            return Ok(false);
                        }
                    }
                    crate::types::MatchCondition::Any { any } => {
                        if let Some(meta_value) = metadata_value {
                            if !any.contains(meta_value) {
                                return Ok(false);
                            }
                        } else {
                            return Ok(false);
                        }
                    }
                    crate::types::MatchCondition::Range { gte, lte } => {
                        if let Some(meta_value) = metadata_value {
                            if let Some(num_value) = meta_value.as_f64() {
                                if let Some(gte_val) = gte {
                                    if num_value < *gte_val {
                                        return Ok(false);
                                    }
                                }
                                if let Some(lte_val) = lte {
                                    if num_value > *lte_val {
                                        return Ok(false);
                                    }
                                }
                            } else {
                                return Ok(false);
                            }
                        } else {
                            return Ok(false);
                        }
                    }
                }
            }
        }
        
        Ok(true)
    }
}

#[async_trait]
impl VectorStore for EmbeddedQdrantVectorStore {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    async fn initialize(&self) -> Result<()> {
        // Create base directory structure (user directories will be created on demand)
        tokio::fs::create_dir_all(&self.base_path).await?;

        // Load existing data with lazy loading
        self.load_existing_data().await?;

        let mut initialized = self.initialized.write().await;
        *initialized = true;

        info!("EmbeddedQdrantVectorStore initialized with user-specific directories");
        Ok(())
    }
    
    async fn is_initialized(&self) -> bool {
        *self.initialized.read().await
    }
    
    async fn set_dimensions(&self, dimensions: usize) -> Result<()> {
        let mut dims = self.dimensions.write().await;
        *dims = Some(dimensions);
        Ok(())
    }
    
    async fn add_document(&self, collection_name: &str, document: Document) -> Result<String> {
        // Use current user context if set, otherwise return error
        let user_id = if let Some(context) = self.current_user_context.read().await.as_ref() {
            context.clone()
        } else {
            return Err(anyhow!("No user context set. Call set_user_context() before adding documents."));
        };

        // Initialize user collection files for vector data
        self.initialize_user_collection_files(&user_id).await?;

        // Add document and generate vector files (don't skip save for single documents)
        let (id, _) = self.add_document_internal(collection_name, document, false, false).await?;

        // Generate vector files using user_id
        if let Err(e) = self.generate_user_vector_files(&user_id, collection_name).await {
            warn!("Failed to generate vector files for user {} collection {}: {}", user_id, collection_name, e);
        }

        Ok(id)
    }
    
    async fn add_documents(&self, collection_name: &str, documents: Vec<Document>) -> Result<Vec<String>> {
        let mut ids = Vec::new();
        let mut processed_docs = Vec::new();

        // Use current user context if set, otherwise return error
        let user_id = if let Some(context) = self.current_user_context.read().await.as_ref() {
            context.clone()
        } else {
            return Err(anyhow!("No user context set. Call set_user_context() before adding documents."));
        };

        // Initialize context collection files for vector data
        self.initialize_user_collection_files(&user_id).await?;

        // GET FILE LOCK - Prevents concurrent writes to same files
        // Lock is per (user_id, collection_name) for fine-grained concurrency
        let file_key = format!("{}_{}", user_id, collection_name);
        let file_lock = {
            let mut locks = self.file_locks.lock().unwrap();
            locks.entry(file_key.clone())
                .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
                .clone()
        };

        info!("🔒 Acquiring file lock for batch operation: {}", file_key);
        let _guard = file_lock.lock().await;
        info!("✅ File lock acquired: {}", file_key);

        // Process all documents without saving individually (BATCH FIX)
        info!("📦 Processing {} documents for batch save...", documents.len());
        for document in documents {
            // Skip individual saves (false=no vector files, true=skip save)
            let (id, processed_doc) = self.add_document_internal(collection_name, document, false, true).await?;
            ids.push(id);
            processed_docs.push(processed_doc);
        }

        // BATCH SAVE - Save all documents in ONE operation (UNDER LOCK)
        info!("💾 Batch saving {} documents to local file...", processed_docs.len());
        self.save_user_collection_documents_batch(collection_name, &user_id, &processed_docs).await?;

        // INVALIDATE CACHE - Critical! Ensures fresh data for vector file generation
        info!("🗑️ Invalidating document cache for collection: {}", collection_name);
        {
            let mut cache = self.document_cache.write().await;
            cache.remove(collection_name);
        }

        // Generate vector files once for all documents (UNDER LOCK, with fresh data)
        info!("🔢 Generating vector files for {} documents...", processed_docs.len());
        if let Err(e) = self.generate_user_vector_files(&user_id, collection_name).await {
            warn!("Failed to generate vector files for user {} collection {}: {}", user_id, collection_name, e);
        }

        info!("🔓 Releasing file lock: {}", file_key);
        Ok(ids)
        // Lock is automatically released here - all 4 files (documents, vectors, index, metadata) written atomically
    }

    
    async fn search(
        &self,
        collection_name: &str,
        query_vector: Vec<f32>,
        options: SearchOptions,
    ) -> Result<Vec<SearchResult>> {
        self.ensure_initialized().await?;

        let limit = options.limit.unwrap_or(10);
        let score_threshold = options.score_threshold.unwrap_or(0.0);

        info!("🔍 ========== SEARCH FLOW START ==========");
        info!("   Collection: {}", collection_name);
        info!("   Limit: {}, Score Threshold: {}", limit, score_threshold);

        // Load all documents
        let collection_docs = self.get_collection_documents(collection_name).await?;
        let total_docs = collection_docs.len();
        info!("   📚 Total documents in collection: {}", total_docs);

        // STEP 1: PRE-FILTERING - Filter documents BEFORE semantic search
        let filtered_doc_ids: Vec<String> = if let Some(filter) = &options.filter {
            info!("   🎯 STEP 1: PRE-FILTERING");

            // Log filter conditions
            if let Some(must_conditions) = &filter.must {
                info!("      Filter conditions ({} conditions):", must_conditions.len());
                for condition in must_conditions {
                    match &condition.r#match {
                        crate::types::MatchCondition::Value { value } => {
                            info!("         - {} = {:?}", condition.key, value);
                        }
                        _ => {
                            info!("         - {} (complex condition)", condition.key);
                        }
                    }
                }
            }

            let mut filtered_ids = Vec::new();
            let filter_start = std::time::Instant::now();

            for (doc_id, document) in collection_docs.iter() {
                if self.matches_filter(document, filter).await? {
                    filtered_ids.push(doc_id.clone());
                }
            }

            let filter_duration = filter_start.elapsed();
            info!("      ✅ PRE-FILTER complete: {} → {} documents (filtered out: {}) in {:?}",
                  total_docs, filtered_ids.len(), total_docs - filtered_ids.len(), filter_duration);

            if filtered_ids.is_empty() {
                warn!("      ⚠️ No documents match the filter criteria!");
            }

            filtered_ids
        } else {
            info!("   ⏭️ STEP 1: No filter provided, using all {} documents", total_docs);
            collection_docs.keys().cloned().collect()
        };

        // STEP 2: SEMANTIC SEARCH - Compute similarity ONLY for filtered documents
        info!("   🧠 STEP 2: SEMANTIC SEARCH on {} filtered documents", filtered_doc_ids.len());
        let mut candidates: Vec<(String, f32)> = Vec::new();
        let search_start = std::time::Instant::now();

        for doc_id in filtered_doc_ids {
            if let Some(document) = collection_docs.get(&doc_id) {
                if let Some(doc_embedding) = &document.embedding {
                    let similarity = cosine_similarity(&query_vector, doc_embedding)?;
                    if similarity >= score_threshold {
                        candidates.push((doc_id, similarity));
                    }
                }
            }
        }

        let search_duration = search_start.elapsed();
        info!("      ✅ SEMANTIC SEARCH complete: {} candidates above threshold in {:?}",
              candidates.len(), search_duration);

        // STEP 3: Sort by similarity and take top results
        candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
        let results_before_limit = candidates.len();
        candidates.truncate(limit);

        info!("   📊 STEP 3: RANKING & LIMITING");
        info!("      Sorted by similarity, limited to top {} (from {} candidates)",
              candidates.len(), results_before_limit);

        // Log top results
        if !candidates.is_empty() {
            info!("      Top results:");
            for (idx, (doc_id, score)) in candidates.iter().enumerate().take(3) {
                info!("         {}. {} (score: {:.4})", idx + 1, doc_id, score);
            }
            if candidates.len() > 3 {
                info!("         ... and {} more", candidates.len() - 3);
            }
        }

        // STEP 4: Build final results with payload
        let mut results = Vec::new();
        for (doc_id, score) in candidates {
            if let Some(document) = collection_docs.get(&doc_id) {
                // Create payload with both metadata and content for search processing
                let mut payload: HashMap<String, serde_json::Value> = document.metadata.clone().into_iter().collect();
                // Add the encrypted content to payload so it can be decrypted during processing
                payload.insert("content".to_string(), serde_json::Value::String(document.content.clone()));

                let result = SearchResult {
                    id: doc_id,
                    score,
                    document: Some(document.clone()),
                    payload: Some(payload),
                };
                results.push(result);
            }
        }

        info!("✅ ========== SEARCH FLOW COMPLETE: {} results returned ==========\n", results.len());
        Ok(results)
    }
    
    async fn get_document(&self, collection_name: &str, id: &str) -> Result<Option<Document>> {
        self.ensure_initialized().await?;

        // Use lazy loading
        let collection_docs = self.get_collection_documents(collection_name).await?;

        Ok(collection_docs.get(id).cloned())
    }
    
    async fn update_document(&self, collection_name: &str, id: &str, mut document: Document) -> Result<()> {
        self.ensure_initialized().await?;

        document.id = id.to_string();
        document.updated_at = Utc::now();

        // Load current documents and update
        let mut collection_docs = self.get_collection_documents(collection_name).await?;
        collection_docs.insert(id.to_string(), document);

        // Update cache
        {
            let mut cache = self.document_cache.write().await;
            cache.insert(collection_name.to_string(), collection_docs.clone());
        }

        // Save to file
        let docs: Vec<Document> = collection_docs.values().cloned().collect();
        self.save_documents(collection_name, &docs).await?;

        Ok(())
    }
    
    async fn delete_document(&self, collection_name: &str, id: &str) -> Result<bool> {
        self.ensure_initialized().await?;

        // Load current documents and remove
        let mut collection_docs = self.get_collection_documents(collection_name).await?;
        let existed = collection_docs.remove(id).is_some();

        if existed {
            // Update cache
            {
                let mut cache = self.document_cache.write().await;
                cache.insert(collection_name.to_string(), collection_docs.clone());
            }

            // Save to file
            let docs: Vec<Document> = collection_docs.values().cloned().collect();
            self.save_documents(collection_name, &docs).await?;
        }

        Ok(existed)
    }
    
    async fn list_documents(
        &self,
        collection_name: &str,
        limit: Option<usize>,
        filter: Option<SearchFilter>,
    ) -> Result<Vec<Document>> {
        self.ensure_initialized().await?;

        // Use lazy loading
        let collection_docs = self.get_collection_documents(collection_name).await?;

        let mut results = Vec::new();
        let limit = limit.unwrap_or(50);

        for document in collection_docs.values() {
            if let Some(filter) = &filter {
                if !self.matches_filter(document, filter).await? {
                    continue;
                }
            }

            results.push(document.clone());

            if results.len() >= limit {
                break;
            }
        }

        Ok(results)
    }
    
    async fn create_collection(&self, name: &str, vector_size: usize) -> Result<()> {
        let mut collections = self.collections.write().await;

        let config = CollectionConfig {
            name: name.to_string(),
            dimensions: vector_size,
            distance_metric: "Cosine".to_string(),
        };

        collections.insert(name.to_string(), config);

        // Also initialize collection files tracking for the collection
        // This is needed for operations like add_documents that reference collection_files
        let mut collection_files = self.collection_files.write().await;
        let base_dir = &self.base_path;
        let collection_dir = base_dir.join("qdrant-data");
        
        let files = CollectionFiles {
            metadata_file: collection_dir.join(format!("{}-metadata.json", name)),
            documents_file: collection_dir.join(format!("{}-documents.json", name)),
            vectors_file: collection_dir.join(format!("{}-vectors.bin", name)),
            vector_index_file: collection_dir.join(format!("{}-vector-index.json", name)),
            user_id: "global".to_string(), // Default user for global collections
        };
        collection_files.insert(name.to_string(), files);

        info!("Created collection '{}' with user-specific directories and lazy loading", name);

        Ok(())
    }
    
    async fn delete_collection(&self, name: &str) -> Result<bool> {
        let mut collections = self.collections.write().await;
        let existed = collections.remove(name).is_some();

        if existed {
            // Clean up caches
            {
                let mut doc_cache = self.document_cache.write().await;
                doc_cache.remove(name);
            }
            {
                let mut vec_cache = self.vector_cache.write().await;
                vec_cache.remove(name);
            }
            {
                let mut idx_cache = self.index_cache.write().await;
                idx_cache.remove(name);
            }

            // Remove files
            let collection_files = self.collection_files.read().await;
            if let Some(files) = collection_files.get(name) {
                let _ = tokio::fs::remove_file(&files.metadata_file).await;
                let _ = tokio::fs::remove_file(&files.documents_file).await;
                let _ = tokio::fs::remove_file(&files.vectors_file).await;
                let _ = tokio::fs::remove_file(&files.vector_index_file).await;
            }
        }

        Ok(existed)
    }
    
    async fn list_collections(&self) -> Result<Vec<String>> {
        let collections = self.collections.read().await;
        Ok(collections.keys().cloned().collect())
    }
    
    async fn get_collection_info(&self, name: &str) -> Result<Option<CollectionInfo>> {
        let collections = self.collections.read().await;

        if let Some(config) = collections.get(name) {
            // Load documents on-demand to get count
            let collection_docs = self.get_collection_documents(name).await?;
            let points_count = collection_docs.len();

            let info = CollectionInfo {
                name: name.to_string(),
                vector_size: config.dimensions,
                distance: config.distance_metric.clone(),
                points_count,
                segments_count: Some(1),
                disk_data_size: None, // Could calculate actual file sizes
                ram_data_size: None,
            };

            Ok(Some(info))
        } else {
            Ok(None)
        }
    }
    
    async fn scroll_collection(
        &self,
        collection_name: &str,
        filter: Option<SearchFilter>,
        limit: Option<usize>,
    ) -> Result<Vec<SearchResult>> {
        let documents = self.list_documents(collection_name, limit, filter).await?;
        
        let results = documents
            .into_iter()
            .map(|doc| SearchResult {
                id: doc.id.clone(),
                score: 1.0, // Dummy score for scroll
                document: Some(doc.clone()),
                payload: Some(doc.metadata.into_iter().collect()),
            })
            .collect();
        
        Ok(results)
    }
    
    async fn get_collections_health(&self) -> Result<HashMap<String, CollectionHealth>> {
        let collections = self.collections.read().await;
        let mut health_info = HashMap::new();

        for (name, _config) in collections.iter() {
            // Use lazy loading to get document count
            let collection_docs = self.get_collection_documents(name).await?;
            let points_count = collection_docs.len();

            let health = CollectionHealth {
                name: name.clone(),
                status: "green".to_string(),
                points_count,
                segments_count: 1,
                disk_size: 0, // Could calculate actual sizes
                ram_size: 0,
                last_updated: Utc::now(),
            };

            health_info.insert(name.clone(), health);
        }

        Ok(health_info)
    }
    
    async fn shutdown(&self) -> Result<()> {
        // Clear caches to free memory
        {
            let mut doc_cache = self.document_cache.write().await;
            doc_cache.clear();
        }
        {
            let mut vec_cache = self.vector_cache.write().await;
            vec_cache.clear();
        }
        {
            let mut idx_cache = self.index_cache.write().await;
            idx_cache.clear();
        }

        let mut initialized = self.initialized.write().await;
        *initialized = false;

        info!("Embedded Qdrant vector store shut down, caches cleared");
        Ok(())
    }

    async fn clear_document_cache(&self) -> Result<()> {
        info!("🗑️  Clearing document cache to force reload from disk");
        {
            let mut doc_cache = self.document_cache.write().await;
            let cache_size = doc_cache.len();
            doc_cache.clear();
            info!("✅ Cleared {} collection(s) from document cache", cache_size);
        }
        {
            let mut vec_cache = self.vector_cache.write().await;
            vec_cache.clear();
            info!("✅ Cleared vector cache");
        }
        {
            let mut idx_cache = self.index_cache.write().await;
            idx_cache.clear();
            info!("✅ Cleared index cache");
        }
        Ok(())
    }

    async fn disable_optimizer(&self, _collection_name: &str) -> Result<()> {
        // Embedded mode uses local file storage, no Qdrant optimizer to disable
        // This is a no-op for embedded mode
        info!("📝 Embedded mode: optimizer control not applicable (using local file storage)");
        Ok(())
    }

    async fn enable_optimizer(&self, _collection_name: &str) -> Result<()> {
        // Embedded mode uses local file storage, no Qdrant optimizer to enable
        // This is a no-op for embedded mode
        info!("📝 Embedded mode: optimizer control not applicable (using local file storage)");
        Ok(())
    }

}

// Separate impl block for internal methods
impl EmbeddedQdrantVectorStore {
    /// Add document without generating vector files (for batch operations)
    /// skip_save: if true, don't save to file (for batch operations that save all at once)
    async fn add_document_internal(&self, collection_name: &str, document: Document, generate_files: bool, skip_save: bool) -> Result<(String, Document)> {
        self.ensure_initialized().await?;

        // Load current documents using lazy loading
        let mut collection_docs = self.get_collection_documents(collection_name).await?;

        let doc_id = if document.id.is_empty() {
            Uuid::new_v4().to_string()
        } else {
            document.id.clone()
        };

        let mut doc_to_insert = document;
        doc_to_insert.id = doc_id.clone();
        doc_to_insert.updated_at = Utc::now();

        // Generate embedding if not provided
        if doc_to_insert.embedding.is_none() {
            let collections = self.collections.read().await;
            if let Some(collection_config) = collections.get(collection_name) {
                if collection_config.dimensions == 1 {
                    // Chat history collection - use dummy vector
                    doc_to_insert.embedding = Some(generate_dummy_vector());
                }
            }
        }

        // Apply encryption like the main add_document method
        let mut stored_content = doc_to_insert.content.clone();
        let mut stored_metadata = doc_to_insert.metadata.clone();

        // Check if content is already encrypted
        let already_encrypted = stored_metadata.get("_encrypted_content")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // Encrypt content if enabled and not already encrypted
        if !stored_content.is_empty() && !already_encrypted {
            match self.encryption_service.encrypt_content(&stored_content).await {
                Ok(encrypted_content) => {
                    stored_content = encrypted_content;
                    stored_metadata.insert("_encrypted_content".to_string(), serde_json::Value::Bool(true));
                }
                Err(e) => {
                    warn!("Failed to encrypt content: {}", e);
                }
            }
        }

        // Check if metadata is already encrypted
        let metadata_already_encrypted = stored_metadata.contains_key("_encrypted_metadata");

        // Encrypt metadata if enabled and not already encrypted
        if !stored_metadata.is_empty() && !metadata_already_encrypted {
            let mut metadata_to_encrypt = stored_metadata.clone();
            metadata_to_encrypt.shift_remove("_encrypted_content");

            match serde_json::to_string(&metadata_to_encrypt) {
                Ok(metadata_json) => {
                    match self.encryption_service.encrypt_content(&metadata_json).await {
                        Ok(encrypted_metadata) => {
                            stored_metadata.clear();
                            stored_metadata.insert("_encrypted_metadata".to_string(), serde_json::Value::String(encrypted_metadata));
                            stored_metadata.insert("_encrypted_content".to_string(), serde_json::Value::Bool(true));
                            stored_metadata.insert("created_at".to_string(), serde_json::Value::String(Utc::now().to_rfc3339()));
                            stored_metadata.insert("updated_at".to_string(), serde_json::Value::String(Utc::now().to_rfc3339()));
                        }
                        Err(e) => {
                            warn!("Failed to encrypt metadata: {}", e);
                        }
                    }
                }
                Err(e) => {
                    warn!("Failed to serialize metadata for encryption: {}", e);
                }
            }
        }

        // Update document with encrypted content and metadata
        doc_to_insert.content = stored_content;
        doc_to_insert.metadata = stored_metadata;

        collection_docs.insert(doc_id.clone(), doc_to_insert.clone());

        // Update cache
        {
            let mut cache = self.document_cache.write().await;
            cache.insert(collection_name.to_string(), collection_docs.clone());
        }

        // Save to file using user-specific storage - use current user context (UNLESS skip_save is true for batch)
        let user_id = if let Some(context) = self.current_user_context.read().await.as_ref() {
            context.clone()
        } else {
            return Err(anyhow!("No user context set. Call set_user_context() before adding documents."));
        };

        // Only save individually if not skipping (batch operations skip and save all at once)
        if !skip_save {
            self.save_user_collection_document(collection_name, &user_id, &doc_to_insert).await?;
        }

        // Generate vector files if requested using user_id (not context_id)
        if generate_files {
            // Initialize user collection files if needed
            if let Err(e) = self.initialize_user_collection_files(&user_id).await {
                warn!("Failed to initialize user collection files: {}", e);
            }

            if let Err(e) = self.generate_user_vector_files(&user_id, collection_name).await {
                warn!("Failed to generate vector files for user {} collection {}: {}", user_id, collection_name, e);
            }
        }

        Ok((doc_id, doc_to_insert))
    }
}