dakera-engine 0.10.2

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

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Instant;
use thiserror::Error;

use common::VectorId;

/// A search result row: (vector ID, score, optional vector, optional metadata).
type SearchResultRow = (VectorId, f32, Option<Vec<f32>>, Option<serde_json::Value>);

// ============================================================================
// Errors
// ============================================================================

/// Errors that can occur during batch search operations
#[derive(Debug, Error)]
pub enum BatchSearchError {
    #[error("Query batch too large: {0} exceeds maximum {1}")]
    BatchTooLarge(usize, usize),

    #[error("Invalid cursor: {0}")]
    InvalidCursor(String),

    #[error("Invalid geo-coordinate: lat={0}, lon={1}")]
    InvalidGeoCoordinate(f64, f64),

    #[error("Unsupported aggregation type: {0}")]
    UnsupportedAggregation(String),

    #[error("Invalid scoring function: {0}")]
    InvalidScoringFunction(String),

    #[error("Query timeout exceeded: {0}ms")]
    Timeout(u64),

    #[error("Internal error: {0}")]
    Internal(String),
}

// ============================================================================
// Batch Query API
// ============================================================================

/// Configuration for batch query execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchQueryConfig {
    /// Maximum queries per batch
    pub max_batch_size: usize,
    /// Maximum concurrent queries
    pub max_concurrency: usize,
    /// Timeout per query in milliseconds
    pub query_timeout_ms: u64,
    /// Enable query deduplication
    pub deduplicate_queries: bool,
    /// Collect timing statistics
    pub collect_stats: bool,
}

impl Default for BatchQueryConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 100,
            max_concurrency: 16,
            query_timeout_ms: 5000,
            deduplicate_queries: true,
            collect_stats: true,
        }
    }
}

/// A single query in a batch
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchQueryItem {
    /// Unique identifier for this query (for correlation)
    pub query_id: String,
    /// Query vector
    pub vector: Vec<f32>,
    /// Number of results to return
    pub top_k: usize,
    /// Optional filter expression
    pub filter: Option<FilterExpression>,
    /// Optional pagination cursor
    pub cursor: Option<SearchCursor>,
    /// Custom scoring configuration
    pub scoring: Option<ScoringConfig>,
}

/// Batch query request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchQueryRequest {
    /// Namespace/collection to search
    pub namespace: String,
    /// List of queries to execute
    pub queries: Vec<BatchQueryItem>,
    /// Include vectors in response
    pub include_vectors: bool,
    /// Include metadata in response
    pub include_metadata: bool,
    /// Global facet aggregations
    pub facets: Option<Vec<FacetRequest>>,
}

/// Response for a single query in the batch
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchQueryItemResponse {
    /// Query ID (matches request)
    pub query_id: String,
    /// Search results
    pub results: Vec<SearchHit>,
    /// Pagination cursor for next page
    pub next_cursor: Option<SearchCursor>,
    /// Query execution time in milliseconds
    pub took_ms: u64,
    /// Total matches (may be estimate for large result sets)
    pub total_matches: usize,
    /// Query explanation (if requested)
    pub explanation: Option<QueryExplanation>,
}

/// Full batch query response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchQueryResponse {
    /// Responses for each query
    pub responses: Vec<BatchQueryItemResponse>,
    /// Global facet results
    pub facets: Option<HashMap<String, FacetResult>>,
    /// Batch execution statistics
    pub stats: BatchQueryStats,
}

/// Statistics for batch query execution
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BatchQueryStats {
    /// Total queries in batch
    pub total_queries: usize,
    /// Successful queries
    pub successful_queries: usize,
    /// Failed queries
    pub failed_queries: usize,
    /// Total batch execution time
    pub total_took_ms: u64,
    /// Average query time
    pub avg_query_ms: f64,
    /// Maximum query time
    pub max_query_ms: u64,
    /// Minimum query time
    pub min_query_ms: u64,
    /// Queries that were deduplicated
    pub deduplicated_count: usize,
}

/// A search hit result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchHit {
    /// Vector ID
    pub id: VectorId,
    /// Similarity/relevance score
    pub score: f32,
    /// Vector data (if requested)
    pub vector: Option<Vec<f32>>,
    /// Metadata (if requested)
    pub metadata: Option<serde_json::Value>,
    /// Sort values for search-after pagination
    pub sort_values: Vec<SortValue>,
}

// ============================================================================
// Pagination
// ============================================================================

/// Search cursor for pagination
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchCursor {
    /// Cursor type
    pub cursor_type: CursorType,
    /// Encoded cursor value
    pub value: String,
    /// Timestamp when cursor was created
    pub created_at: u64,
}

impl SearchCursor {
    /// Create a cursor-based pagination cursor
    pub fn cursor_based(offset: usize, total: usize) -> Self {
        let value = format!("{}:{}", offset, total);
        Self {
            cursor_type: CursorType::CursorBased,
            value: base64_encode(&value),
            created_at: current_timestamp_ms(),
        }
    }

    /// Create a search-after pagination cursor
    pub fn search_after(sort_values: &[SortValue]) -> Self {
        let json = serde_json::to_string(sort_values).unwrap_or_default();
        Self {
            cursor_type: CursorType::SearchAfter,
            value: base64_encode(&json),
            created_at: current_timestamp_ms(),
        }
    }

    /// Parse cursor offset for cursor-based pagination
    pub fn parse_offset(&self) -> Result<usize, BatchSearchError> {
        if self.cursor_type != CursorType::CursorBased {
            return Err(BatchSearchError::InvalidCursor(
                "Expected cursor-based cursor".into(),
            ));
        }
        let decoded = base64_decode(&self.value)
            .map_err(|_| BatchSearchError::InvalidCursor("Invalid base64".into()))?;
        let parts: Vec<&str> = decoded.split(':').collect();
        parts
            .first()
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| BatchSearchError::InvalidCursor("Invalid offset format".into()))
    }

    /// Parse sort values for search-after pagination
    pub fn parse_sort_values(&self) -> Result<Vec<SortValue>, BatchSearchError> {
        if self.cursor_type != CursorType::SearchAfter {
            return Err(BatchSearchError::InvalidCursor(
                "Expected search-after cursor".into(),
            ));
        }
        let decoded = base64_decode(&self.value)
            .map_err(|_| BatchSearchError::InvalidCursor("Invalid base64".into()))?;
        serde_json::from_str(&decoded)
            .map_err(|_| BatchSearchError::InvalidCursor("Invalid sort values".into()))
    }
}

/// Type of pagination cursor
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CursorType {
    /// Offset-based cursor (fast for small offsets)
    CursorBased,
    /// Search-after cursor (efficient for deep pagination)
    SearchAfter,
}

/// Sort value for search-after pagination
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SortValue {
    Score(f32),
    Integer(i64),
    Float(f64),
    String(String),
    Null,
}

impl SortValue {
    /// Compare two sort values
    pub fn compare(&self, other: &SortValue) -> std::cmp::Ordering {
        use std::cmp::Ordering;
        match (self, other) {
            (SortValue::Score(a), SortValue::Score(b)) => {
                b.partial_cmp(a).unwrap_or(Ordering::Equal)
            }
            (SortValue::Integer(a), SortValue::Integer(b)) => a.cmp(b),
            (SortValue::Float(a), SortValue::Float(b)) => {
                a.partial_cmp(b).unwrap_or(Ordering::Equal)
            }
            (SortValue::String(a), SortValue::String(b)) => a.cmp(b),
            (SortValue::Null, SortValue::Null) => Ordering::Equal,
            (SortValue::Null, _) => Ordering::Greater,
            (_, SortValue::Null) => Ordering::Less,
            _ => Ordering::Equal,
        }
    }
}

/// Pagination configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginationConfig {
    /// Page size (number of results per page)
    pub page_size: usize,
    /// Maximum allowed offset for cursor-based pagination
    pub max_offset: usize,
    /// Cursor expiration time in seconds
    pub cursor_ttl_secs: u64,
    /// Default sort order
    pub default_sort: Vec<SortField>,
}

impl Default for PaginationConfig {
    fn default() -> Self {
        Self {
            page_size: 20,
            max_offset: 10000,
            cursor_ttl_secs: 3600,
            default_sort: vec![SortField {
                field: "_score".into(),
                order: SortOrder::Descending,
            }],
        }
    }
}

/// Sort field specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortField {
    /// Field name to sort by
    pub field: String,
    /// Sort order
    pub order: SortOrder,
}

/// Sort order
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SortOrder {
    Ascending,
    Descending,
}

// ============================================================================
// Faceted Search / Aggregations
// ============================================================================

/// Request for a facet/aggregation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacetRequest {
    /// Name of this facet (for response)
    pub name: String,
    /// Field to aggregate on
    pub field: String,
    /// Type of aggregation
    pub agg_type: AggregationType,
    /// Maximum number of buckets (for terms aggregation)
    pub max_buckets: Option<usize>,
    /// Ranges for range aggregation
    pub ranges: Option<Vec<RangeBucket>>,
}

/// Type of aggregation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AggregationType {
    /// Count unique terms
    Terms,
    /// Numeric range buckets
    Range,
    /// Date histogram
    DateHistogram { interval: String },
    /// Numeric histogram
    Histogram { interval: f64 },
    /// Minimum value
    Min,
    /// Maximum value
    Max,
    /// Average value
    Avg,
    /// Sum of values
    Sum,
    /// Value count
    Count,
    /// Cardinality (unique count estimate)
    Cardinality,
}

/// Range bucket definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RangeBucket {
    /// Bucket key/name
    pub key: String,
    /// From value (inclusive)
    pub from: Option<f64>,
    /// To value (exclusive)
    pub to: Option<f64>,
}

/// Result of a facet aggregation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacetResult {
    /// Facet name
    pub name: String,
    /// Field that was aggregated
    pub field: String,
    /// Buckets (for terms, range, histogram)
    pub buckets: Option<Vec<FacetBucket>>,
    /// Metric value (for min, max, avg, sum, count)
    pub value: Option<f64>,
    /// Total document count
    pub doc_count: usize,
}

/// A bucket in a facet result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FacetBucket {
    /// Bucket key
    pub key: String,
    /// Document count in bucket
    pub doc_count: usize,
    /// Nested aggregations
    pub sub_aggregations: Option<HashMap<String, FacetResult>>,
}

/// Faceted search executor
pub struct FacetExecutor {
    max_buckets: usize,
}

impl FacetExecutor {
    /// Create a new facet executor
    pub fn new(max_buckets: usize) -> Self {
        Self { max_buckets }
    }

    /// Execute a terms aggregation
    pub fn terms_aggregation(
        &self,
        values: &[Option<serde_json::Value>],
        max_buckets: usize,
    ) -> Vec<FacetBucket> {
        let mut counts: HashMap<String, usize> = HashMap::new();

        for value in values.iter().flatten() {
            let key = match value {
                serde_json::Value::String(s) => s.clone(),
                serde_json::Value::Number(n) => n.to_string(),
                serde_json::Value::Bool(b) => b.to_string(),
                _ => continue,
            };
            *counts.entry(key).or_insert(0) += 1;
        }

        let mut buckets: Vec<_> = counts
            .into_iter()
            .map(|(key, count)| FacetBucket {
                key,
                doc_count: count,
                sub_aggregations: None,
            })
            .collect();

        // Sort by count descending
        buckets.sort_by(|a, b| b.doc_count.cmp(&a.doc_count));
        buckets.truncate(max_buckets.min(self.max_buckets));
        buckets
    }

    /// Execute a range aggregation
    pub fn range_aggregation(
        &self,
        values: &[Option<f64>],
        ranges: &[RangeBucket],
    ) -> Vec<FacetBucket> {
        ranges
            .iter()
            .map(|range| {
                let count = values
                    .iter()
                    .filter(|v| {
                        if let Some(val) = v {
                            let from_ok = range.from.is_none_or(|f| *val >= f);
                            let to_ok = range.to.is_none_or(|t| *val < t);
                            from_ok && to_ok
                        } else {
                            false
                        }
                    })
                    .count();

                FacetBucket {
                    key: range.key.clone(),
                    doc_count: count,
                    sub_aggregations: None,
                }
            })
            .collect()
    }

    /// Execute a numeric aggregation (min, max, avg, sum)
    pub fn numeric_aggregation(&self, values: &[Option<f64>], agg_type: &AggregationType) -> f64 {
        let valid_values: Vec<f64> = values.iter().filter_map(|v| *v).collect();

        if valid_values.is_empty() {
            return 0.0;
        }

        match agg_type {
            AggregationType::Min => valid_values.iter().copied().fold(f64::INFINITY, f64::min),
            AggregationType::Max => valid_values
                .iter()
                .copied()
                .fold(f64::NEG_INFINITY, f64::max),
            AggregationType::Avg => valid_values.iter().sum::<f64>() / valid_values.len() as f64,
            AggregationType::Sum => valid_values.iter().sum(),
            AggregationType::Count => valid_values.len() as f64,
            _ => 0.0,
        }
    }
}

// ============================================================================
// Geo-Spatial Filtering
// ============================================================================

/// Geographic point
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct GeoPoint {
    /// Latitude (-90 to 90)
    pub lat: f64,
    /// Longitude (-180 to 180)
    pub lon: f64,
}

impl GeoPoint {
    /// Create a new geo point with validation
    pub fn new(lat: f64, lon: f64) -> Result<Self, BatchSearchError> {
        if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
            return Err(BatchSearchError::InvalidGeoCoordinate(lat, lon));
        }
        Ok(Self { lat, lon })
    }

    /// Calculate haversine distance to another point in kilometers
    pub fn distance_km(&self, other: &GeoPoint) -> f64 {
        const EARTH_RADIUS_KM: f64 = 6371.0;

        let lat1 = self.lat.to_radians();
        let lat2 = other.lat.to_radians();
        let delta_lat = (other.lat - self.lat).to_radians();
        let delta_lon = (other.lon - self.lon).to_radians();

        let a = (delta_lat / 2.0).sin().powi(2)
            + lat1.cos() * lat2.cos() * (delta_lon / 2.0).sin().powi(2);
        let c = 2.0 * a.sqrt().asin();

        EARTH_RADIUS_KM * c
    }

    /// Calculate distance in meters
    pub fn distance_m(&self, other: &GeoPoint) -> f64 {
        self.distance_km(other) * 1000.0
    }

    /// Calculate distance in miles
    pub fn distance_miles(&self, other: &GeoPoint) -> f64 {
        self.distance_km(other) * 0.621371
    }
}

/// Geo-spatial filter types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GeoFilter {
    /// Filter by distance from a point
    Distance {
        /// Center point
        center: GeoPoint,
        /// Maximum distance
        distance: f64,
        /// Distance unit
        unit: DistanceUnit,
    },
    /// Filter by bounding box
    BoundingBox {
        /// Top-left corner
        top_left: GeoPoint,
        /// Bottom-right corner
        bottom_right: GeoPoint,
    },
    /// Filter by polygon
    Polygon {
        /// Polygon vertices (must be closed)
        points: Vec<GeoPoint>,
    },
}

/// Distance unit for geo queries
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum DistanceUnit {
    Meters,
    Kilometers,
    Miles,
    Feet,
}

impl DistanceUnit {
    /// Convert distance to meters
    pub fn to_meters(&self, distance: f64) -> f64 {
        match self {
            DistanceUnit::Meters => distance,
            DistanceUnit::Kilometers => distance * 1000.0,
            DistanceUnit::Miles => distance * 1609.34,
            DistanceUnit::Feet => distance * 0.3048,
        }
    }
}

/// Geo-spatial filter executor
pub struct GeoFilterExecutor;

impl GeoFilterExecutor {
    /// Check if a point passes the geo filter
    pub fn matches(filter: &GeoFilter, point: &GeoPoint) -> bool {
        match filter {
            GeoFilter::Distance {
                center,
                distance,
                unit,
            } => {
                let max_distance_m = unit.to_meters(*distance);
                center.distance_m(point) <= max_distance_m
            }
            GeoFilter::BoundingBox {
                top_left,
                bottom_right,
            } => {
                point.lat <= top_left.lat
                    && point.lat >= bottom_right.lat
                    && point.lon >= top_left.lon
                    && point.lon <= bottom_right.lon
            }
            GeoFilter::Polygon { points } => Self::point_in_polygon(point, points),
        }
    }

    /// Ray casting algorithm for point-in-polygon test
    fn point_in_polygon(point: &GeoPoint, polygon: &[GeoPoint]) -> bool {
        if polygon.len() < 3 {
            return false;
        }

        let mut inside = false;
        let n = polygon.len();

        let mut j = n - 1;
        for i in 0..n {
            let pi = &polygon[i];
            let pj = &polygon[j];

            if ((pi.lat > point.lat) != (pj.lat > point.lat))
                && (point.lon
                    < (pj.lon - pi.lon) * (point.lat - pi.lat) / (pj.lat - pi.lat) + pi.lon)
            {
                inside = !inside;
            }
            j = i;
        }

        inside
    }
}

// ============================================================================
// Custom Scoring / Boosting
// ============================================================================

/// Custom scoring configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoringConfig {
    /// Base score mode
    pub score_mode: ScoreMode,
    /// Boost functions to apply
    pub functions: Vec<ScoreFunction>,
    /// How to combine function scores
    pub boost_mode: BoostMode,
    /// Minimum score threshold
    pub min_score: Option<f32>,
}

impl Default for ScoringConfig {
    fn default() -> Self {
        Self {
            score_mode: ScoreMode::Multiply,
            functions: Vec::new(),
            boost_mode: BoostMode::Multiply,
            min_score: None,
        }
    }
}

/// How to combine multiple function scores
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ScoreMode {
    Multiply,
    Sum,
    Average,
    First,
    Max,
    Min,
}

/// How to combine function score with original score
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum BoostMode {
    Multiply,
    Replace,
    Sum,
    Average,
    Max,
    Min,
}

/// Score function definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ScoreFunction {
    /// Constant boost
    Weight { weight: f32 },
    /// Field value boost
    FieldValue {
        field: String,
        factor: f32,
        modifier: FieldValueModifier,
        missing: f32,
    },
    /// Decay function (gaussian, linear, exponential)
    Decay {
        field: String,
        origin: f64,
        scale: f64,
        offset: f64,
        decay: f64,
        decay_type: DecayType,
    },
    /// Random score for variety
    RandomScore { seed: u64, field: Option<String> },
    /// Script-based scoring
    Script {
        source: String,
        params: HashMap<String, f64>,
    },
    /// Geo distance decay
    GeoDecay {
        field: String,
        origin: GeoPoint,
        scale: f64,
        scale_unit: DistanceUnit,
        offset: f64,
        decay: f64,
    },
}

/// Modifier for field value scoring
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum FieldValueModifier {
    None,
    Log,
    Log1p,
    Log2p,
    Ln,
    Ln1p,
    Ln2p,
    Square,
    Sqrt,
    Reciprocal,
}

/// Type of decay function
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum DecayType {
    Gaussian,
    Linear,
    Exponential,
}

/// Score function executor
pub struct ScoreFunctionExecutor;

impl ScoreFunctionExecutor {
    /// Apply a score function
    pub fn apply(
        function: &ScoreFunction,
        original_score: f32,
        metadata: Option<&serde_json::Value>,
    ) -> f32 {
        match function {
            ScoreFunction::Weight { weight } => *weight,

            ScoreFunction::FieldValue {
                field,
                factor,
                modifier,
                missing,
            } => {
                let value = metadata
                    .and_then(|m| m.get(field))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(*missing as f64);

                let modified = Self::apply_modifier(value, *modifier);
                (modified * *factor as f64) as f32
            }

            ScoreFunction::Decay {
                origin,
                scale,
                offset,
                decay,
                decay_type,
                field,
            } => {
                let value = metadata
                    .and_then(|m| m.get(field))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(*origin);

                let distance = (value - origin).abs() - offset;
                if distance <= 0.0 {
                    return 1.0;
                }

                Self::compute_decay(distance, *scale, *decay, *decay_type) as f32
            }

            ScoreFunction::RandomScore { seed, .. } => {
                // Simple pseudo-random based on seed
                let hash = (*seed as u32).wrapping_mul(2654435769);
                hash as f32 / u32::MAX as f32
            }

            ScoreFunction::Script { source, params } => {
                // Simple expression evaluation for demo
                Self::evaluate_script(source, params, original_score, metadata)
            }

            ScoreFunction::GeoDecay {
                field,
                origin,
                scale,
                scale_unit,
                offset,
                decay,
            } => {
                let point = metadata.and_then(|m| m.get(field)).and_then(|v| {
                    let lat = v.get("lat")?.as_f64()?;
                    let lon = v.get("lon")?.as_f64()?;
                    Some(GeoPoint { lat, lon })
                });

                if let Some(point) = point {
                    let distance_m = origin.distance_m(&point);
                    let scale_m = scale_unit.to_meters(*scale);
                    let offset_m = scale_unit.to_meters(*offset);

                    let adjusted_distance = (distance_m - offset_m).max(0.0);
                    Self::compute_decay(adjusted_distance, scale_m, *decay, DecayType::Gaussian)
                        as f32
                } else {
                    0.0
                }
            }
        }
    }

    fn apply_modifier(value: f64, modifier: FieldValueModifier) -> f64 {
        match modifier {
            FieldValueModifier::None => value,
            FieldValueModifier::Log => value.log10(),
            FieldValueModifier::Log1p => (1.0 + value).log10(),
            FieldValueModifier::Log2p => (2.0 + value).log10(),
            FieldValueModifier::Ln => value.ln(),
            FieldValueModifier::Ln1p => (1.0 + value).ln(),
            FieldValueModifier::Ln2p => (2.0 + value).ln(),
            FieldValueModifier::Square => value * value,
            FieldValueModifier::Sqrt => value.sqrt(),
            FieldValueModifier::Reciprocal => 1.0 / value.max(0.001),
        }
    }

    fn compute_decay(distance: f64, scale: f64, decay: f64, decay_type: DecayType) -> f64 {
        let lambda = scale.ln().abs() / decay.ln().abs();

        match decay_type {
            DecayType::Gaussian => (-0.5 * (distance / lambda).powi(2)).exp(),
            DecayType::Linear => ((lambda - distance) / lambda).max(0.0),
            DecayType::Exponential => (-distance / lambda).exp(),
        }
    }

    fn evaluate_script(
        _source: &str,
        params: &HashMap<String, f64>,
        original_score: f32,
        _metadata: Option<&serde_json::Value>,
    ) -> f32 {
        // Simplified: just use params to boost score
        let boost = params.get("boost").copied().unwrap_or(1.0) as f32;
        original_score * boost
    }

    /// Combine multiple function scores
    pub fn combine_scores(scores: &[f32], mode: ScoreMode) -> f32 {
        if scores.is_empty() {
            return 1.0;
        }

        match mode {
            ScoreMode::Multiply => scores.iter().product(),
            ScoreMode::Sum => scores.iter().sum(),
            ScoreMode::Average => scores.iter().sum::<f32>() / scores.len() as f32,
            ScoreMode::First => scores[0],
            ScoreMode::Max => scores.iter().copied().fold(f32::NEG_INFINITY, f32::max),
            ScoreMode::Min => scores.iter().copied().fold(f32::INFINITY, f32::min),
        }
    }

    /// Combine function score with original score
    pub fn combine_with_original(original: f32, function_score: f32, mode: BoostMode) -> f32 {
        match mode {
            BoostMode::Multiply => original * function_score,
            BoostMode::Replace => function_score,
            BoostMode::Sum => original + function_score,
            BoostMode::Average => (original + function_score) / 2.0,
            BoostMode::Max => original.max(function_score),
            BoostMode::Min => original.min(function_score),
        }
    }
}

// ============================================================================
// Query Explain API
// ============================================================================

/// Query explanation for debugging scoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryExplanation {
    /// Final computed score
    pub score: f32,
    /// Description of scoring
    pub description: String,
    /// Component explanations
    pub details: Vec<ScoreDetail>,
}

/// Detail of a score component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoreDetail {
    /// Component name
    pub name: String,
    /// Component score value
    pub value: f32,
    /// How this component was computed
    pub description: String,
    /// Nested details
    pub details: Option<Vec<ScoreDetail>>,
}

/// Query explainer
pub struct QueryExplainer;

impl QueryExplainer {
    /// Generate explanation for a query result
    pub fn explain(
        id: &VectorId,
        original_score: f32,
        scoring_config: Option<&ScoringConfig>,
        metadata: Option<&serde_json::Value>,
    ) -> QueryExplanation {
        let mut details = vec![ScoreDetail {
            name: "vector_similarity".into(),
            value: original_score,
            description: "Base vector similarity score".into(),
            details: None,
        }];

        let mut final_score = original_score;

        if let Some(config) = scoring_config {
            let mut function_scores = Vec::new();

            for (i, func) in config.functions.iter().enumerate() {
                let func_score = ScoreFunctionExecutor::apply(func, original_score, metadata);
                function_scores.push(func_score);

                details.push(ScoreDetail {
                    name: format!("function_{}", i),
                    value: func_score,
                    description: Self::describe_function(func),
                    details: None,
                });
            }

            if !function_scores.is_empty() {
                let combined =
                    ScoreFunctionExecutor::combine_scores(&function_scores, config.score_mode);
                details.push(ScoreDetail {
                    name: "combined_functions".into(),
                    value: combined,
                    description: format!("Functions combined using {:?}", config.score_mode),
                    details: None,
                });

                final_score = ScoreFunctionExecutor::combine_with_original(
                    original_score,
                    combined,
                    config.boost_mode,
                );
            }
        }

        QueryExplanation {
            score: final_score,
            description: format!("Explanation for document {}", id),
            details,
        }
    }

    fn describe_function(func: &ScoreFunction) -> String {
        match func {
            ScoreFunction::Weight { weight } => format!("Constant weight: {}", weight),
            ScoreFunction::FieldValue { field, factor, .. } => {
                format!("Field value boost on '{}' with factor {}", field, factor)
            }
            ScoreFunction::Decay {
                field, decay_type, ..
            } => format!("{:?} decay on field '{}'", decay_type, field),
            ScoreFunction::RandomScore { seed, .. } => format!("Random score with seed {}", seed),
            ScoreFunction::Script { source, .. } => format!("Script: {}", source),
            ScoreFunction::GeoDecay { field, .. } => format!("Geo decay on field '{}'", field),
        }
    }
}

// ============================================================================
// Filter Expressions
// ============================================================================

/// Filter expression for queries
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FilterExpression {
    /// Match exact value
    Term {
        field: String,
        value: serde_json::Value,
    },
    /// Match any of the values
    Terms {
        field: String,
        values: Vec<serde_json::Value>,
    },
    /// Range filter
    Range {
        field: String,
        gte: Option<f64>,
        gt: Option<f64>,
        lte: Option<f64>,
        lt: Option<f64>,
    },
    /// Exists filter
    Exists { field: String },
    /// Prefix match
    Prefix { field: String, prefix: String },
    /// Geo filter
    Geo { field: String, filter: GeoFilter },
    /// Boolean AND
    And(Vec<FilterExpression>),
    /// Boolean OR
    Or(Vec<FilterExpression>),
    /// Boolean NOT
    Not(Box<FilterExpression>),
}

/// Filter executor
pub struct FilterExecutor;

impl FilterExecutor {
    /// Check if metadata matches filter
    pub fn matches(filter: &FilterExpression, metadata: Option<&serde_json::Value>) -> bool {
        let metadata = match metadata {
            Some(m) => m,
            None => return false,
        };

        match filter {
            FilterExpression::Term { field, value } => metadata.get(field) == Some(value),
            FilterExpression::Terms { field, values } => {
                metadata.get(field).is_some_and(|v| values.contains(v))
            }
            FilterExpression::Range {
                field,
                gte,
                gt,
                lte,
                lt,
            } => {
                let value = metadata.get(field).and_then(|v| v.as_f64());
                if let Some(v) = value {
                    gte.is_none_or(|x| v >= x)
                        && gt.is_none_or(|x| v > x)
                        && lte.is_none_or(|x| v <= x)
                        && lt.is_none_or(|x| v < x)
                } else {
                    false
                }
            }
            FilterExpression::Exists { field } => metadata.get(field).is_some(),
            FilterExpression::Prefix { field, prefix } => metadata
                .get(field)
                .and_then(|v| v.as_str())
                .is_some_and(|s| s.starts_with(prefix)),
            FilterExpression::Geo { field, filter } => {
                let point = metadata.get(field).and_then(|v| {
                    let lat = v.get("lat")?.as_f64()?;
                    let lon = v.get("lon")?.as_f64()?;
                    Some(GeoPoint { lat, lon })
                });
                point.is_some_and(|p| GeoFilterExecutor::matches(filter, &p))
            }
            FilterExpression::And(filters) => {
                filters.iter().all(|f| Self::matches(f, Some(metadata)))
            }
            FilterExpression::Or(filters) => {
                filters.iter().any(|f| Self::matches(f, Some(metadata)))
            }
            FilterExpression::Not(filter) => !Self::matches(filter, Some(metadata)),
        }
    }
}

// ============================================================================
// Batch Query Executor
// ============================================================================

/// Batch query executor for high-throughput search
pub struct BatchQueryExecutor {
    config: BatchQueryConfig,
}

impl BatchQueryExecutor {
    /// Create a new batch query executor
    pub fn new(config: BatchQueryConfig) -> Self {
        Self { config }
    }

    /// Execute a batch of queries
    pub fn execute(
        &self,
        request: &BatchQueryRequest,
        search_fn: impl Fn(
            &[f32],
            usize,
            Option<&FilterExpression>,
        ) -> Vec<(VectorId, f32, Option<Vec<f32>>, Option<serde_json::Value>)>,
    ) -> Result<BatchQueryResponse, BatchSearchError> {
        let start = Instant::now();

        // Validate batch size
        if request.queries.len() > self.config.max_batch_size {
            return Err(BatchSearchError::BatchTooLarge(
                request.queries.len(),
                self.config.max_batch_size,
            ));
        }

        let mut responses: Vec<BatchQueryItemResponse> = Vec::with_capacity(request.queries.len());
        let mut query_times: Vec<u64> = Vec::new();
        let mut deduplicated_count = 0;

        // Process queries (could be parallelized in production)
        let mut seen_queries: HashMap<Vec<u32>, usize> = HashMap::new();

        for query in &request.queries {
            let query_start = Instant::now();

            // Check for duplicate queries (deduplication)
            let query_hash: Vec<u32> = query.vector.iter().map(|f| f.to_bits()).collect();

            if self.config.deduplicate_queries {
                if let Some(&existing_idx) = seen_queries.get(&query_hash) {
                    // Reuse previous response
                    let mut response = responses[existing_idx].clone();
                    response.query_id = query.query_id.clone();
                    responses.push(response);
                    deduplicated_count += 1;
                    continue;
                }
                seen_queries.insert(query_hash, responses.len());
            }

            // Execute search
            let raw_results = search_fn(&query.vector, query.top_k * 2, query.filter.as_ref());

            // Apply pagination
            let (results, next_cursor) = self.apply_pagination(&raw_results, query)?;

            // Apply custom scoring
            let scored_results = self.apply_scoring(&results, query.scoring.as_ref());

            // Build hits
            let hits: Vec<SearchHit> = scored_results
                .into_iter()
                .take(query.top_k)
                .map(|(id, score, vec, meta)| SearchHit {
                    id,
                    score,
                    vector: if request.include_vectors { vec } else { None },
                    metadata: if request.include_metadata { meta } else { None },
                    sort_values: vec![SortValue::Score(score)],
                })
                .collect();

            let query_time = query_start.elapsed().as_millis() as u64;
            query_times.push(query_time);

            responses.push(BatchQueryItemResponse {
                query_id: query.query_id.clone(),
                results: hits,
                next_cursor,
                took_ms: query_time,
                total_matches: raw_results.len(),
                explanation: None,
            });
        }

        // Compute facets if requested
        let facets = request.facets.as_ref().map(|_| HashMap::new());

        // Compute statistics
        let total_took = start.elapsed().as_millis() as u64;
        let stats = BatchQueryStats {
            total_queries: request.queries.len(),
            successful_queries: responses.len(),
            failed_queries: 0,
            total_took_ms: total_took,
            avg_query_ms: if !query_times.is_empty() {
                query_times.iter().sum::<u64>() as f64 / query_times.len() as f64
            } else {
                0.0
            },
            max_query_ms: query_times.iter().copied().max().unwrap_or(0),
            min_query_ms: query_times.iter().copied().min().unwrap_or(0),
            deduplicated_count,
        };

        Ok(BatchQueryResponse {
            responses,
            facets,
            stats,
        })
    }

    fn apply_pagination(
        &self,
        results: &[SearchResultRow],
        query: &BatchQueryItem,
    ) -> Result<(Vec<SearchResultRow>, Option<SearchCursor>), BatchSearchError> {
        if let Some(cursor) = &query.cursor {
            match cursor.cursor_type {
                CursorType::CursorBased => {
                    let offset = cursor.parse_offset()?;
                    let paginated: Vec<_> = results.iter().skip(offset).cloned().collect();
                    let next_cursor = if offset + query.top_k < results.len() {
                        Some(SearchCursor::cursor_based(
                            offset + query.top_k,
                            results.len(),
                        ))
                    } else {
                        None
                    };
                    Ok((paginated, next_cursor))
                }
                CursorType::SearchAfter => {
                    let sort_values = cursor.parse_sort_values()?;
                    let start_idx = results
                        .iter()
                        .position(|(_, score, _, _)| {
                            let sv = SortValue::Score(*score);
                            sv.compare(&sort_values[0]) == std::cmp::Ordering::Greater
                        })
                        .unwrap_or(0);
                    let paginated: Vec<_> = results.iter().skip(start_idx).cloned().collect();
                    let next_cursor = if start_idx + query.top_k < results.len() {
                        paginated
                            .get(query.top_k - 1)
                            .map(|last| SearchCursor::search_after(&[SortValue::Score(last.1)]))
                    } else {
                        None
                    };
                    Ok((paginated, next_cursor))
                }
            }
        } else {
            let next_cursor = if results.len() > query.top_k {
                Some(SearchCursor::cursor_based(query.top_k, results.len()))
            } else {
                None
            };
            Ok((results.to_vec(), next_cursor))
        }
    }

    fn apply_scoring(
        &self,
        results: &[SearchResultRow],
        scoring: Option<&ScoringConfig>,
    ) -> Vec<SearchResultRow> {
        let config = match scoring {
            Some(c) if !c.functions.is_empty() => c,
            _ => return results.to_vec(),
        };
        let mut scored: Vec<_> = results
            .iter()
            .map(|(id, score, vec, meta)| {
                let function_scores: Vec<f32> = config
                    .functions
                    .iter()
                    .map(|f| ScoreFunctionExecutor::apply(f, *score, meta.as_ref()))
                    .collect();

                let combined =
                    ScoreFunctionExecutor::combine_scores(&function_scores, config.score_mode);
                let final_score = ScoreFunctionExecutor::combine_with_original(
                    *score,
                    combined,
                    config.boost_mode,
                );

                (id.clone(), final_score, vec.clone(), meta.clone())
            })
            .collect();

        // Apply min_score filter
        if let Some(min) = config.min_score {
            scored.retain(|(_, s, _, _)| *s >= min);
        }

        // Re-sort by new scores
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored
    }
}

// ============================================================================
// Utility Functions
// ============================================================================

fn base64_encode(input: &str) -> String {
    // Simple base64 encoding for cursor values
    let bytes = input.as_bytes();
    let mut result = String::new();
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    for chunk in bytes.chunks(3) {
        let mut n = (chunk[0] as u32) << 16;
        if chunk.len() > 1 {
            n |= (chunk[1] as u32) << 8;
        }
        if chunk.len() > 2 {
            n |= chunk[2] as u32;
        }

        result.push(CHARS[(n >> 18 & 0x3f) as usize] as char);
        result.push(CHARS[(n >> 12 & 0x3f) as usize] as char);
        if chunk.len() > 1 {
            result.push(CHARS[(n >> 6 & 0x3f) as usize] as char);
        } else {
            result.push('=');
        }
        if chunk.len() > 2 {
            result.push(CHARS[(n & 0x3f) as usize] as char);
        } else {
            result.push('=');
        }
    }
    result
}

fn base64_decode(input: &str) -> Result<String, &'static str> {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    let mut result = Vec::new();
    let input = input.trim_end_matches('=');
    let bytes: Vec<u8> = input.bytes().collect();

    for chunk in bytes.chunks(4) {
        let mut n = 0u32;
        for (i, &b) in chunk.iter().enumerate() {
            let pos = CHARS.iter().position(|&c| c == b).ok_or("Invalid base64")?;
            n |= (pos as u32) << (18 - i * 6);
        }

        result.push((n >> 16) as u8);
        if chunk.len() > 2 {
            result.push((n >> 8) as u8);
        }
        if chunk.len() > 3 {
            result.push(n as u8);
        }
    }

    String::from_utf8(result).map_err(|_| "Invalid UTF-8")
}

fn current_timestamp_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_batch_query_config_default() {
        let config = BatchQueryConfig::default();
        assert_eq!(config.max_batch_size, 100);
        assert_eq!(config.max_concurrency, 16);
        assert_eq!(config.query_timeout_ms, 5000);
    }

    #[test]
    fn test_cursor_based_pagination() {
        let cursor = SearchCursor::cursor_based(20, 100);
        assert_eq!(cursor.cursor_type, CursorType::CursorBased);

        let offset = cursor.parse_offset().unwrap();
        assert_eq!(offset, 20);
    }

    #[test]
    fn test_search_after_pagination() {
        let sort_values = vec![SortValue::Score(0.95), SortValue::String("doc123".into())];
        let cursor = SearchCursor::search_after(&sort_values);
        assert_eq!(cursor.cursor_type, CursorType::SearchAfter);

        let parsed = cursor.parse_sort_values().unwrap();
        assert_eq!(parsed.len(), 2);
    }

    #[test]
    fn test_sort_value_comparison() {
        assert_eq!(
            SortValue::Score(0.9).compare(&SortValue::Score(0.8)),
            std::cmp::Ordering::Less
        );
        assert_eq!(
            SortValue::Integer(10).compare(&SortValue::Integer(5)),
            std::cmp::Ordering::Greater
        );
    }

    #[test]
    fn test_geo_point_distance() {
        // New York to Los Angeles (approximately 3,940 km)
        let nyc = GeoPoint::new(40.7128, -74.0060).unwrap();
        let la = GeoPoint::new(34.0522, -118.2437).unwrap();

        let distance = nyc.distance_km(&la);
        assert!(distance > 3900.0 && distance < 4000.0);
    }

    #[test]
    fn test_geo_point_validation() {
        assert!(GeoPoint::new(45.0, 90.0).is_ok());
        assert!(GeoPoint::new(91.0, 0.0).is_err());
        assert!(GeoPoint::new(0.0, 181.0).is_err());
    }

    #[test]
    fn test_geo_distance_filter() {
        let center = GeoPoint::new(40.7128, -74.0060).unwrap();
        let filter = GeoFilter::Distance {
            center,
            distance: 100.0,
            unit: DistanceUnit::Kilometers,
        };

        // Point within 100km
        let nearby = GeoPoint::new(40.8, -74.1).unwrap();
        assert!(GeoFilterExecutor::matches(&filter, &nearby));

        // Point far away
        let far = GeoPoint::new(34.0522, -118.2437).unwrap();
        assert!(!GeoFilterExecutor::matches(&filter, &far));
    }

    #[test]
    fn test_geo_bounding_box() {
        let filter = GeoFilter::BoundingBox {
            top_left: GeoPoint::new(41.0, -75.0).unwrap(),
            bottom_right: GeoPoint::new(40.0, -73.0).unwrap(),
        };

        let inside = GeoPoint::new(40.5, -74.0).unwrap();
        assert!(GeoFilterExecutor::matches(&filter, &inside));

        let outside = GeoPoint::new(42.0, -74.0).unwrap();
        assert!(!GeoFilterExecutor::matches(&filter, &outside));
    }

    #[test]
    fn test_terms_aggregation() {
        let executor = FacetExecutor::new(100);

        let values: Vec<Option<serde_json::Value>> = vec![
            Some(serde_json::json!("cat")),
            Some(serde_json::json!("dog")),
            Some(serde_json::json!("cat")),
            Some(serde_json::json!("bird")),
            Some(serde_json::json!("cat")),
        ];

        let buckets = executor.terms_aggregation(&values, 10);

        assert_eq!(buckets.len(), 3);
        assert_eq!(buckets[0].key, "cat");
        assert_eq!(buckets[0].doc_count, 3);
    }

    #[test]
    fn test_range_aggregation() {
        let executor = FacetExecutor::new(100);

        let values: Vec<Option<f64>> =
            vec![Some(5.0), Some(15.0), Some(25.0), Some(35.0), Some(45.0)];
        let ranges = vec![
            RangeBucket {
                key: "low".into(),
                from: None,
                to: Some(20.0),
            },
            RangeBucket {
                key: "medium".into(),
                from: Some(20.0),
                to: Some(40.0),
            },
            RangeBucket {
                key: "high".into(),
                from: Some(40.0),
                to: None,
            },
        ];

        let buckets = executor.range_aggregation(&values, &ranges);

        assert_eq!(buckets.len(), 3);
        assert_eq!(buckets[0].doc_count, 2); // low: 5, 15
        assert_eq!(buckets[1].doc_count, 2); // medium: 25, 35
        assert_eq!(buckets[2].doc_count, 1); // high: 45
    }

    #[test]
    fn test_numeric_aggregations() {
        let executor = FacetExecutor::new(100);
        let values: Vec<Option<f64>> = vec![Some(10.0), Some(20.0), Some(30.0)];

        assert_eq!(
            executor.numeric_aggregation(&values, &AggregationType::Min),
            10.0
        );
        assert_eq!(
            executor.numeric_aggregation(&values, &AggregationType::Max),
            30.0
        );
        assert_eq!(
            executor.numeric_aggregation(&values, &AggregationType::Avg),
            20.0
        );
        assert_eq!(
            executor.numeric_aggregation(&values, &AggregationType::Sum),
            60.0
        );
    }

    #[test]
    fn test_score_function_weight() {
        let func = ScoreFunction::Weight { weight: 2.0 };
        let score = ScoreFunctionExecutor::apply(&func, 0.5, None);
        assert_eq!(score, 2.0);
    }

    #[test]
    fn test_score_function_field_value() {
        let func = ScoreFunction::FieldValue {
            field: "popularity".into(),
            factor: 0.1,
            modifier: FieldValueModifier::Log1p,
            missing: 1.0,
        };

        let metadata = serde_json::json!({"popularity": 100.0});
        let score = ScoreFunctionExecutor::apply(&func, 0.5, Some(&metadata));

        // log1p(100) * 0.1 ≈ 2.004 * 0.1 ≈ 0.2004
        assert!(score > 0.19 && score < 0.21);
    }

    #[test]
    fn test_combine_scores() {
        let scores = vec![2.0f32, 3.0, 4.0];

        assert_eq!(
            ScoreFunctionExecutor::combine_scores(&scores, ScoreMode::Multiply),
            24.0
        );
        assert_eq!(
            ScoreFunctionExecutor::combine_scores(&scores, ScoreMode::Sum),
            9.0
        );
        assert_eq!(
            ScoreFunctionExecutor::combine_scores(&scores, ScoreMode::Average),
            3.0
        );
        assert_eq!(
            ScoreFunctionExecutor::combine_scores(&scores, ScoreMode::Max),
            4.0
        );
        assert_eq!(
            ScoreFunctionExecutor::combine_scores(&scores, ScoreMode::Min),
            2.0
        );
    }

    #[test]
    fn test_filter_term() {
        let filter = FilterExpression::Term {
            field: "category".into(),
            value: serde_json::json!("tech"),
        };

        let metadata = serde_json::json!({"category": "tech"});
        assert!(FilterExecutor::matches(&filter, Some(&metadata)));

        let other = serde_json::json!({"category": "science"});
        assert!(!FilterExecutor::matches(&filter, Some(&other)));
    }

    #[test]
    fn test_filter_range() {
        let filter = FilterExpression::Range {
            field: "price".into(),
            gte: Some(10.0),
            gt: None,
            lte: Some(100.0),
            lt: None,
        };

        let match1 = serde_json::json!({"price": 50});
        assert!(FilterExecutor::matches(&filter, Some(&match1)));

        let nomatch = serde_json::json!({"price": 5});
        assert!(!FilterExecutor::matches(&filter, Some(&nomatch)));
    }

    #[test]
    fn test_filter_boolean_and() {
        let filter = FilterExpression::And(vec![
            FilterExpression::Term {
                field: "category".into(),
                value: serde_json::json!("tech"),
            },
            FilterExpression::Range {
                field: "price".into(),
                gte: Some(10.0),
                gt: None,
                lte: None,
                lt: None,
            },
        ]);

        let match1 = serde_json::json!({"category": "tech", "price": 50});
        assert!(FilterExecutor::matches(&filter, Some(&match1)));

        let nomatch = serde_json::json!({"category": "tech", "price": 5});
        assert!(!FilterExecutor::matches(&filter, Some(&nomatch)));
    }

    #[test]
    fn test_query_explanation() {
        let id = "doc123".to_string();
        let scoring = ScoringConfig {
            functions: vec![ScoreFunction::Weight { weight: 1.5 }],
            ..Default::default()
        };

        let explanation = QueryExplainer::explain(&id, 0.8, Some(&scoring), None);

        assert!(explanation.score > 0.0);
        assert!(!explanation.details.is_empty());
        assert!(explanation.description.contains("doc123"));
    }

    #[test]
    fn test_batch_query_executor() {
        let config = BatchQueryConfig::default();
        let executor = BatchQueryExecutor::new(config);

        let request = BatchQueryRequest {
            namespace: "test".into(),
            queries: vec![
                BatchQueryItem {
                    query_id: "q1".into(),
                    vector: vec![1.0, 0.0, 0.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
                BatchQueryItem {
                    query_id: "q2".into(),
                    vector: vec![0.0, 1.0, 0.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
            ],
            include_vectors: false,
            include_metadata: true,
            facets: None,
        };

        // Mock search function
        let search_fn = |_vector: &[f32], _top_k: usize, _filter: Option<&FilterExpression>| {
            vec![
                (
                    "doc1".into(),
                    0.9,
                    None,
                    Some(serde_json::json!({"cat": "a"})),
                ),
                (
                    "doc2".into(),
                    0.8,
                    None,
                    Some(serde_json::json!({"cat": "b"})),
                ),
            ]
        };

        let response = executor.execute(&request, search_fn).unwrap();

        assert_eq!(response.responses.len(), 2);
        assert_eq!(response.stats.total_queries, 2);
        assert_eq!(response.stats.successful_queries, 2);
    }

    #[test]
    fn test_batch_too_large_error() {
        let config = BatchQueryConfig {
            max_batch_size: 2,
            ..Default::default()
        };
        let executor = BatchQueryExecutor::new(config);

        let request = BatchQueryRequest {
            namespace: "test".into(),
            queries: vec![
                BatchQueryItem {
                    query_id: "q1".into(),
                    vector: vec![1.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
                BatchQueryItem {
                    query_id: "q2".into(),
                    vector: vec![1.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
                BatchQueryItem {
                    query_id: "q3".into(),
                    vector: vec![1.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
            ],
            include_vectors: false,
            include_metadata: false,
            facets: None,
        };

        let result = executor.execute(&request, |_, _, _| vec![]);
        assert!(matches!(result, Err(BatchSearchError::BatchTooLarge(3, 2))));
    }

    #[test]
    fn test_base64_roundtrip() {
        let original = "hello:world:123";
        let encoded = base64_encode(original);
        let decoded = base64_decode(&encoded).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_distance_unit_conversion() {
        assert_eq!(DistanceUnit::Meters.to_meters(100.0), 100.0);
        assert_eq!(DistanceUnit::Kilometers.to_meters(1.0), 1000.0);
        assert!((DistanceUnit::Miles.to_meters(1.0) - 1609.34).abs() < 0.01);
    }

    #[test]
    fn test_query_deduplication() {
        let config = BatchQueryConfig {
            deduplicate_queries: true,
            ..Default::default()
        };
        let executor = BatchQueryExecutor::new(config);

        // Same vector twice
        let request = BatchQueryRequest {
            namespace: "test".into(),
            queries: vec![
                BatchQueryItem {
                    query_id: "q1".into(),
                    vector: vec![1.0, 0.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
                BatchQueryItem {
                    query_id: "q2".into(),
                    vector: vec![1.0, 0.0],
                    top_k: 5,
                    filter: None,
                    cursor: None,
                    scoring: None,
                },
            ],
            include_vectors: false,
            include_metadata: false,
            facets: None,
        };

        let response = executor
            .execute(&request, |_, _, _| vec![("doc1".into(), 0.9, None, None)])
            .unwrap();

        assert_eq!(response.stats.deduplicated_count, 1);
    }
}