redis-tower-modules 0.1.2

High-level ergonomic client interfaces for Redis Stack modules
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
//! # TimeSeries Client
//!
//! Ergonomic, typed client over [RedisTimeSeries](https://redis.io/docs/data-types/timeseries/).
//! Values are exchanged as [`TsSample`] pairs rather than raw [`Frame`] values.
//!
//! # Example
//!
//! ```no_run
//! use redis_tower::RedisClient;
//! use redis_tower_modules::timeseries::{TimeSeriesClient, TsKeyConfig, TsRangeQuery};
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let client = RedisClient::connect_url("redis://127.0.0.1:6379").await?;
//! let mut ts = TimeSeriesClient::new(client);
//!
//! // Create a key with a 1-hour retention window and a label.
//! ts.create(
//!     "sensors:temp",
//!     TsKeyConfig::new().retention(3_600_000).label("sensor", "temperature"),
//! )
//! .await?;
//!
//! // Append a sample with a server-assigned timestamp.
//! use redis_tower_modules::timeseries::TsTimestamp;
//! let ts_returned = ts.add("sensors:temp", TsTimestamp::Auto, 21.5).await?;
//!
//! // Query the last hour.
//! let samples = ts.range("sensors:temp", TsRangeQuery::all()).await?;
//! for s in samples {
//!     println!("{}: {}", s.timestamp, s.value);
//! }
//! # Ok(())
//! # }
//! ```

use redis_tower::RedisExecutor;
use redis_tower_core::{Frame, RedisError};

// Low-level command builders
use redis_tower::commands::{
    TsAdd, TsAlter, TsCreate, TsDecrBy, TsDel, TsGet, TsIncrBy, TsInfo, TsMAdd, TsMGet, TsMRange,
    TsMRevRange, TsQueryIndex, TsRange, TsRevRange,
};

// Re-export the enums from commands so callers don't need a second import.
pub use redis_tower::commands::{TsAggregation, TsDuplicatePolicy, TsEncoding, TsTimestamp};

// ---------------------------------------------------------------------------
// Domain types
// ---------------------------------------------------------------------------

/// A single time series sample: a timestamp (milliseconds since epoch) and
/// a floating-point value.
#[derive(Debug, Clone, PartialEq)]
pub struct TsSample {
    /// Sample timestamp in milliseconds since the Unix epoch.
    pub timestamp: i64,
    /// Sample value.
    pub value: f64,
}

/// A label key-value pair attached to a TimeSeries key.
#[derive(Debug, Clone, PartialEq)]
pub struct TsLabel {
    /// Label name.
    pub key: String,
    /// Label value.
    pub value: String,
}

/// Configuration for creating or altering a TimeSeries key.
///
/// All fields are optional; unset fields are omitted from the command.
#[derive(Debug, Clone, Default)]
pub struct TsKeyConfig {
    /// Optional retention period in milliseconds.
    pub retention_ms: Option<u64>,
    /// Optional sample encoding.
    pub encoding: Option<TsEncoding>,
    /// Optional storage chunk size in bytes.
    pub chunk_size: Option<u64>,
    /// Optional duplicate-sample policy.
    pub duplicate_policy: Option<TsDuplicatePolicy>,
    /// Labels attached to the time-series key.
    pub labels: Vec<TsLabel>,
}

impl TsKeyConfig {
    /// Create an empty configuration (all fields unset).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the retention period in milliseconds.
    pub fn retention(mut self, ms: u64) -> Self {
        self.retention_ms = Some(ms);
        self
    }

    /// Set the storage encoding.
    pub fn encoding(mut self, enc: TsEncoding) -> Self {
        self.encoding = Some(enc);
        self
    }

    /// Set the chunk size in bytes.
    pub fn chunk_size(mut self, bytes: u64) -> Self {
        self.chunk_size = Some(bytes);
        self
    }

    /// Set the duplicate-sample policy.
    pub fn duplicate_policy(mut self, policy: TsDuplicatePolicy) -> Self {
        self.duplicate_policy = Some(policy);
        self
    }

    /// Add a label key-value pair.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.labels.push(TsLabel {
            key: key.into(),
            value: value.into(),
        });
        self
    }
}

/// Options for [`TimeSeriesClient::incrby`] and [`TimeSeriesClient::decrby`].
#[derive(Debug, Clone, Default)]
pub struct TsIncrOptions {
    /// Optional explicit sample timestamp.
    pub timestamp: Option<TsTimestamp>,
    /// Optional retention period in milliseconds.
    pub retention_ms: Option<u64>,
    /// Labels to attach when Redis creates the key.
    pub labels: Vec<TsLabel>,
}

impl TsIncrOptions {
    /// Create empty options (all fields unset).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set an explicit timestamp.
    pub fn timestamp(mut self, ts: impl Into<TsTimestamp>) -> Self {
        self.timestamp = Some(ts.into());
        self
    }

    /// Set the retention period in milliseconds.
    pub fn retention(mut self, ms: u64) -> Self {
        self.retention_ms = Some(ms);
        self
    }

    /// Add a label key-value pair.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.labels.push(TsLabel {
            key: key.into(),
            value: value.into(),
        });
        self
    }
}

/// A single result entry returned by `TS.MRANGE`, `TS.MREVRANGE`, or
/// `TS.MGET` — one per matched key.
#[derive(Debug, Clone)]
pub struct TsKeyResult {
    /// Time-series key.
    pub key: String,
    /// Labels returned for the key.
    pub labels: Vec<TsLabel>,
    /// Samples returned for the key.
    pub samples: Vec<TsSample>,
}

/// Typed statistics from `TS.INFO`.
#[derive(Debug, Clone, Default)]
pub struct TsInfoResult {
    /// Total number of samples stored.
    pub total_samples: i64,
    /// Memory used by the time series in bytes.
    pub memory_usage: i64,
    /// Timestamp of the first sample.
    pub first_timestamp: i64,
    /// Timestamp of the last sample.
    pub last_timestamp: i64,
    /// Configured retention period in milliseconds.
    pub retention_time: i64,
    /// Number of storage chunks.
    pub chunk_count: i64,
    /// Configured chunk size in bytes.
    pub chunk_size: i64,
    /// Configured duplicate-sample policy, when reported.
    pub duplicate_policy: Option<String>,
    /// Labels attached to the time-series key.
    pub labels: Vec<TsLabel>,
}

// ---------------------------------------------------------------------------
// Query builders
// ---------------------------------------------------------------------------

/// Range query parameters for [`TimeSeriesClient::range`] and
/// [`TimeSeriesClient::revrange`].
///
/// `from` and `to` are either millisecond timestamps or the special strings
/// `"-"` (smallest possible timestamp) and `"+"` (largest possible timestamp).
#[derive(Debug, Clone)]
pub struct TsRangeQuery {
    pub(crate) from: String,
    pub(crate) to: String,
    pub(crate) latest: bool,
    pub(crate) filter_by_ts: Vec<i64>,
    pub(crate) filter_by_value: Option<(f64, f64)>,
    pub(crate) count: Option<i64>,
    pub(crate) aggregation: Option<(TsAggregation, i64)>,
}

impl TsRangeQuery {
    /// Build a query for the given time range.
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: from.into(),
            to: to.into(),
            latest: false,
            filter_by_ts: Vec::new(),
            filter_by_value: None,
            count: None,
            aggregation: None,
        }
    }

    /// Query the entire time range (`"-"` to `"+"`).
    pub fn all() -> Self {
        Self::new("-", "+")
    }

    /// Include the latest (possibly un-compacted) bucket.
    pub fn latest(mut self) -> Self {
        self.latest = true;
        self
    }

    /// Filter results to only these explicit timestamps.
    pub fn filter_by_ts(mut self, timestamps: impl IntoIterator<Item = i64>) -> Self {
        self.filter_by_ts = timestamps.into_iter().collect();
        self
    }

    /// Filter results to samples within the given value range.
    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
        self.filter_by_value = Some((min, max));
        self
    }

    /// Limit the number of returned samples.
    pub fn count(mut self, n: i64) -> Self {
        self.count = Some(n);
        self
    }

    /// Apply an aggregation with the given bucket size in milliseconds.
    pub fn aggregate(mut self, agg: TsAggregation, bucket_ms: i64) -> Self {
        self.aggregation = Some((agg, bucket_ms));
        self
    }
}

/// Multi-key range query parameters for [`TimeSeriesClient::mrange`] and
/// [`TimeSeriesClient::mrevrange`].
#[derive(Debug, Clone)]
pub struct TsMRangeQuery {
    pub(crate) range: TsRangeQuery,
    pub(crate) filters: Vec<String>,
    pub(crate) withlabels: bool,
}

impl TsMRangeQuery {
    /// Build a multi-key query. At least one `filter` expression is required.
    pub fn new(range: TsRangeQuery, filter: impl Into<String>) -> Self {
        Self {
            range,
            filters: vec![filter.into()],
            withlabels: false,
        }
    }

    /// Add another filter expression (all are ANDed by the server).
    pub fn filter(mut self, expr: impl Into<String>) -> Self {
        self.filters.push(expr.into());
        self
    }

    /// Include labels in the response.
    pub fn withlabels(mut self) -> Self {
        self.withlabels = true;
        self
    }
}

// ---------------------------------------------------------------------------
// Response-parsing helpers
// ---------------------------------------------------------------------------

fn frame_to_i64(frame: Frame) -> Result<i64, RedisError> {
    match frame {
        Frame::Integer(n) => Ok(n),
        Frame::BulkString(Some(b)) => {
            let s = std::str::from_utf8(&b).map_err(|_| RedisError::TypeMismatch {
                expected: "integer as UTF-8",
            })?;
            s.parse::<i64>().map_err(|_| RedisError::TypeMismatch {
                expected: "integer",
            })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "integer",
            actual: format!("{other:?}"),
        }),
    }
}

fn frame_to_f64(frame: Frame) -> Result<f64, RedisError> {
    match frame {
        Frame::Double(value) => Ok(value),
        Frame::BulkString(Some(b)) => {
            let s = std::str::from_utf8(&b).map_err(|_| RedisError::TypeMismatch {
                expected: "f64 as UTF-8",
            })?;
            s.parse::<f64>()
                .map_err(|_| RedisError::TypeMismatch { expected: "f64" })
        }
        Frame::Integer(n) => Ok(n as f64),
        other => Err(RedisError::UnexpectedResponse {
            expected: "double, integer, or bulk string (f64)",
            actual: format!("{other:?}"),
        }),
    }
}

fn frame_to_string(frame: Frame) -> Result<String, RedisError> {
    match frame {
        Frame::BulkString(Some(b)) => {
            String::from_utf8(b.into()).map_err(|_| RedisError::TypeMismatch {
                expected: "UTF-8 string",
            })
        }
        Frame::SimpleString(b) => {
            String::from_utf8(b.into()).map_err(|_| RedisError::TypeMismatch {
                expected: "UTF-8 string",
            })
        }
        Frame::BulkString(None) => Ok(String::new()),
        other => Err(RedisError::UnexpectedResponse {
            expected: "bulk/simple string",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse a 2-element `[timestamp, value]` array into a `TsSample`.
fn parse_sample(frame: Frame) -> Result<TsSample, RedisError> {
    match frame {
        Frame::Array(Some(mut elems)) if elems.len() == 2 => {
            let value = frame_to_f64(elems.pop().unwrap())?;
            let timestamp = frame_to_i64(elems.pop().unwrap())?;
            Ok(TsSample { timestamp, value })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[timestamp, value] array",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse an array-of-arrays into a `Vec<TsSample>`.
fn parse_samples(frame: Frame) -> Result<Vec<TsSample>, RedisError> {
    match frame {
        Frame::Array(Some(frames)) => frames.into_iter().map(parse_sample).collect(),
        Frame::Array(None) => Ok(Vec::new()),
        other => Err(RedisError::UnexpectedResponse {
            expected: "array of [timestamp, value] arrays",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse `TS.GET` response: `[ts, value]` (sample) or `[]` (empty).
fn parse_get(frame: Frame) -> Result<Option<TsSample>, RedisError> {
    match frame {
        Frame::Array(Some(elems)) if elems.is_empty() => Ok(None),
        Frame::Array(None) => Ok(None),
        Frame::Array(Some(mut elems)) if elems.len() == 2 => {
            let value = frame_to_f64(elems.pop().unwrap())?;
            let timestamp = frame_to_i64(elems.pop().unwrap())?;
            Ok(Some(TsSample { timestamp, value }))
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[] or [timestamp, value]",
            actual: format!("{other:?}"),
        }),
    }
}

fn parse_label(key: Frame, value: Frame) -> Result<TsLabel, RedisError> {
    Ok(TsLabel {
        key: frame_to_string(key)?,
        value: match value {
            Frame::Null => String::new(),
            value => frame_to_string(value)?,
        },
    })
}

/// Parse RESP2 label pairs or a RESP3 label map into `Vec<TsLabel>`.
fn parse_labels(frame: Frame) -> Result<Vec<TsLabel>, RedisError> {
    match frame {
        Frame::Array(Some(frames)) => frames
            .into_iter()
            .map(|f| match f {
                Frame::Array(Some(mut kv)) if kv.len() == 2 => {
                    let value = kv.pop().unwrap();
                    let key = kv.pop().unwrap();
                    parse_label(key, value)
                }
                other => Err(RedisError::UnexpectedResponse {
                    expected: "[label_key, label_value] pair",
                    actual: format!("{other:?}"),
                }),
            })
            .collect(),
        Frame::Array(None) => Ok(Vec::new()),
        Frame::Map(entries) | Frame::StreamedMap(entries) => entries
            .into_iter()
            .map(|(key, value)| parse_label(key, value))
            .collect(),
        other => Err(RedisError::UnexpectedResponse {
            expected: "labels array or map",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse one entry of TS.MRANGE / TS.MREVRANGE: `[key, labels_arr, samples_arr]`.
fn parse_mrange_entry(frame: Frame) -> Result<TsKeyResult, RedisError> {
    match frame {
        Frame::Array(Some(mut elems)) if elems.len() == 3 => {
            let samples_frame = elems.pop().unwrap();
            let labels_frame = elems.pop().unwrap();
            let key_frame = elems.pop().unwrap();

            let key = frame_to_string(key_frame)?;
            let labels = parse_labels(labels_frame)?;
            let samples = parse_samples(samples_frame)?;
            Ok(TsKeyResult {
                key,
                labels,
                samples,
            })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[key, labels, samples] entry",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse one RESP3 TS.MRANGE / TS.MREVRANGE map entry.
///
/// RESP3 returns `key => [labels, metadata, samples]`. The metadata currently
/// contains aggregation details that are not represented by [`TsKeyResult`].
fn parse_resp3_mrange_entry(key_frame: Frame, frame: Frame) -> Result<TsKeyResult, RedisError> {
    match frame {
        Frame::Array(Some(mut elems)) if elems.len() == 3 => {
            let samples_frame = elems.pop().unwrap();
            let _metadata_frame = elems.pop().unwrap();
            let labels_frame = elems.pop().unwrap();

            Ok(TsKeyResult {
                key: frame_to_string(key_frame)?,
                labels: parse_labels(labels_frame)?,
                samples: parse_samples(samples_frame)?,
            })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[labels, metadata, samples] map value",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse TS.MRANGE / TS.MREVRANGE response.
fn parse_mrange(frame: Frame) -> Result<Vec<TsKeyResult>, RedisError> {
    match frame {
        Frame::Array(Some(entries)) => entries.into_iter().map(parse_mrange_entry).collect(),
        Frame::Array(None) => Ok(Vec::new()),
        Frame::Map(entries) | Frame::StreamedMap(entries) => entries
            .into_iter()
            .map(|(key, value)| parse_resp3_mrange_entry(key, value))
            .collect(),
        other => Err(RedisError::UnexpectedResponse {
            expected: "array or map of mrange entries",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse one entry of TS.MGET: `[key, labels_arr, [ts, value]]`.
/// The last element is a *single* sample (or empty array), not an array of samples.
fn parse_mget_entry(frame: Frame) -> Result<TsKeyResult, RedisError> {
    match frame {
        Frame::Array(Some(mut elems)) if elems.len() == 3 => {
            let sample_frame = elems.pop().unwrap();
            let labels_frame = elems.pop().unwrap();
            let key_frame = elems.pop().unwrap();

            let key = frame_to_string(key_frame)?;
            let labels = parse_labels(labels_frame)?;
            let samples = match parse_get(sample_frame)? {
                Some(s) => vec![s],
                None => Vec::new(),
            };
            Ok(TsKeyResult {
                key,
                labels,
                samples,
            })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[key, labels, sample] entry",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse one RESP3 TS.MGET map entry: `key => [labels, sample]`.
fn parse_resp3_mget_entry(key_frame: Frame, frame: Frame) -> Result<TsKeyResult, RedisError> {
    match frame {
        Frame::Array(Some(mut elems)) if elems.len() == 2 => {
            let sample_frame = elems.pop().unwrap();
            let labels_frame = elems.pop().unwrap();
            let samples = parse_get(sample_frame)?.into_iter().collect();

            Ok(TsKeyResult {
                key: frame_to_string(key_frame)?,
                labels: parse_labels(labels_frame)?,
                samples,
            })
        }
        other => Err(RedisError::UnexpectedResponse {
            expected: "[labels, sample] map value",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse TS.MGET response.
fn parse_mget(frame: Frame) -> Result<Vec<TsKeyResult>, RedisError> {
    match frame {
        Frame::Array(Some(entries)) => entries.into_iter().map(parse_mget_entry).collect(),
        Frame::Array(None) => Ok(Vec::new()),
        Frame::Map(entries) | Frame::StreamedMap(entries) => entries
            .into_iter()
            .map(|(key, value)| parse_resp3_mget_entry(key, value))
            .collect(),
        other => Err(RedisError::UnexpectedResponse {
            expected: "array or map of mget entries",
            actual: format!("{other:?}"),
        }),
    }
}

/// Parse an RESP2 flat array or RESP3 map returned by TS.INFO.
fn parse_info(frame: Frame) -> Result<TsInfoResult, RedisError> {
    let entries = match frame {
        Frame::Array(Some(frames)) => {
            if frames.len() % 2 != 0 {
                return Err(RedisError::UnexpectedResponse {
                    expected: "even-length array from TS.INFO",
                    actual: format!("odd length: {}", frames.len()),
                });
            }
            let mut entries = Vec::with_capacity(frames.len() / 2);
            let mut frames = frames.into_iter();
            while let (Some(key), Some(value)) = (frames.next(), frames.next()) {
                entries.push((key, value));
            }
            entries
        }
        Frame::Map(entries) | Frame::StreamedMap(entries) => entries,
        other => {
            return Err(RedisError::UnexpectedResponse {
                expected: "flat key-value array or map from TS.INFO",
                actual: format!("{other:?}"),
            });
        }
    };

    let mut result = TsInfoResult::default();
    for (key_frame, val_frame) in entries {
        let key = frame_to_string(key_frame)?;
        match key.as_str() {
            "totalSamples" => result.total_samples = frame_to_i64(val_frame)?,
            "memoryUsage" => result.memory_usage = frame_to_i64(val_frame)?,
            "firstTimestamp" => result.first_timestamp = frame_to_i64(val_frame)?,
            "lastTimestamp" => result.last_timestamp = frame_to_i64(val_frame)?,
            "retentionTime" => result.retention_time = frame_to_i64(val_frame)?,
            "chunkCount" => result.chunk_count = frame_to_i64(val_frame)?,
            "chunkSize" => result.chunk_size = frame_to_i64(val_frame)?,
            "duplicatePolicy" => match val_frame {
                Frame::BulkString(None) | Frame::Null => result.duplicate_policy = None,
                f => result.duplicate_policy = Some(frame_to_string(f)?),
            },
            "labels" => {
                result.labels = parse_labels(val_frame)?;
            }
            // Unknown fields are silently ignored to allow forward compatibility.
            _ => {}
        }
    }

    Ok(result)
}

/// Parse TS.MADD response: an array of integers or errors.
fn parse_madd(frame: Frame) -> Result<Vec<Result<i64, RedisError>>, RedisError> {
    match frame {
        Frame::Array(Some(frames)) => Ok(frames
            .into_iter()
            .map(|f| match f {
                Frame::Integer(n) => Ok(n),
                Frame::Error(msg) => {
                    let s = String::from_utf8_lossy(&msg).into_owned();
                    Err(RedisError::Redis(s))
                }
                other => Err(RedisError::UnexpectedResponse {
                    expected: "integer or error",
                    actual: format!("{other:?}"),
                }),
            })
            .collect()),
        Frame::Array(None) => Ok(Vec::new()),
        other => Err(RedisError::UnexpectedResponse {
            expected: "array of integers/errors",
            actual: format!("{other:?}"),
        }),
    }
}

// ---------------------------------------------------------------------------
// TimeSeriesClient
// ---------------------------------------------------------------------------

/// High-level client for RedisTimeSeries operations.
///
/// Wraps any [`RedisExecutor`] and exposes typed sample-append, range-query,
/// and key-management operations. All response parsing is handled internally;
/// callers work with [`TsSample`], [`TsKeyResult`], and [`TsInfoResult`] rather
/// than raw [`Frame`] values.
///
/// Accepts both owned executors (e.g. `MultiplexedClient`, which is `Clone`) and
/// mutable references (e.g. `&mut RedisClient`), thanks to the blanket
/// `impl RedisExecutor for &mut C`.
pub struct TimeSeriesClient<C> {
    conn: C,
}

impl<C: RedisExecutor> TimeSeriesClient<C> {
    /// Create a new [`TimeSeriesClient`] wrapping the given executor.
    pub fn new(conn: C) -> Self {
        Self { conn }
    }

    // -----------------------------------------------------------------------
    // Key management
    // -----------------------------------------------------------------------

    /// Create a new TimeSeries key with the given configuration.
    pub async fn create(&mut self, key: &str, config: TsKeyConfig) -> Result<(), RedisError> {
        let mut cmd = TsCreate::new(key);
        if let Some(ms) = config.retention_ms {
            cmd = cmd.retention(ms);
        }
        if let Some(enc) = config.encoding {
            cmd = cmd.encoding(enc);
        }
        if let Some(cs) = config.chunk_size {
            cmd = cmd.chunk_size(cs);
        }
        if let Some(dp) = config.duplicate_policy {
            cmd = cmd.duplicate_policy(dp);
        }
        for lbl in &config.labels {
            cmd = cmd.label(lbl.key.clone(), lbl.value.clone());
        }
        self.conn.execute(cmd).await
    }

    /// Alter an existing TimeSeries key's configuration.
    pub async fn alter(&mut self, key: &str, config: TsKeyConfig) -> Result<(), RedisError> {
        let mut cmd = TsAlter::new(key);
        if let Some(ms) = config.retention_ms {
            cmd = cmd.retention(ms);
        }
        if let Some(cs) = config.chunk_size {
            cmd = cmd.chunk_size(cs);
        }
        if let Some(dp) = config.duplicate_policy {
            cmd = cmd.duplicate_policy(dp);
        }
        for lbl in &config.labels {
            cmd = cmd.label(lbl.key.clone(), lbl.value.clone());
        }
        self.conn.execute(cmd).await
    }

    /// Delete all samples in the time range `[from, to]` (inclusive).
    /// Returns the number of samples deleted.
    pub async fn del_range(&mut self, key: &str, from: i64, to: i64) -> Result<i64, RedisError> {
        self.conn.execute(TsDel::new(key, from, to)).await
    }

    // -----------------------------------------------------------------------
    // Writing samples
    // -----------------------------------------------------------------------

    /// Append a sample to a TimeSeries key. Returns the stored timestamp.
    ///
    /// Pass [`TsTimestamp::Auto`] to let the server assign the current time.
    pub async fn add(
        &mut self,
        key: &str,
        timestamp: impl Into<TsTimestamp>,
        value: f64,
    ) -> Result<i64, RedisError> {
        self.conn
            .execute(TsAdd::new(key, timestamp.into(), value))
            .await
    }

    /// Append a sample, also supplying creation-time configuration.
    ///
    /// If the key does not yet exist, it will be created with the given
    /// `config`. Useful for the "upsert" pattern.
    pub async fn add_with_config(
        &mut self,
        key: &str,
        timestamp: impl Into<TsTimestamp>,
        value: f64,
        config: TsKeyConfig,
    ) -> Result<i64, RedisError> {
        let mut cmd = TsAdd::new(key, timestamp.into(), value);
        if let Some(ms) = config.retention_ms {
            cmd = cmd.retention(ms);
        }
        if let Some(enc) = config.encoding {
            cmd = cmd.encoding(enc);
        }
        if let Some(cs) = config.chunk_size {
            cmd = cmd.chunk_size(cs);
        }
        if let Some(dp) = config.duplicate_policy {
            cmd = cmd.on_duplicate(dp);
        }
        for lbl in &config.labels {
            cmd = cmd.label(lbl.key.clone(), lbl.value.clone());
        }
        self.conn.execute(cmd).await
    }

    /// Append samples to multiple keys in a single round-trip.
    ///
    /// Returns one `Result<i64, RedisError>` per input sample. Per-sample
    /// errors (e.g. duplicate-policy violations) are returned as `Err` items
    /// rather than propagating the whole call.
    pub async fn madd(
        &mut self,
        samples: &[(&str, TsTimestamp, f64)],
    ) -> Result<Vec<Result<i64, RedisError>>, RedisError> {
        let mut cmd = TsMAdd::new();
        for &(key, ts, value) in samples {
            cmd = cmd.sample(key, ts, value);
        }
        let raw = self.conn.execute(cmd).await?;
        parse_madd(Frame::Array(Some(raw)))
    }

    /// Increment the value of the latest sample (or create the key).
    /// Returns the timestamp of the updated sample.
    pub async fn incrby(
        &mut self,
        key: &str,
        value: f64,
        options: TsIncrOptions,
    ) -> Result<i64, RedisError> {
        let mut cmd = TsIncrBy::new(key, value);
        if let Some(ts) = options.timestamp {
            cmd = cmd.timestamp(ts);
        }
        if let Some(ms) = options.retention_ms {
            cmd = cmd.retention(ms);
        }
        for lbl in &options.labels {
            cmd = cmd.label(lbl.key.clone(), lbl.value.clone());
        }
        self.conn.execute(cmd).await
    }

    /// Decrement the value of the latest sample (or create the key).
    /// Returns the timestamp of the updated sample.
    pub async fn decrby(
        &mut self,
        key: &str,
        value: f64,
        options: TsIncrOptions,
    ) -> Result<i64, RedisError> {
        let mut cmd = TsDecrBy::new(key, value);
        if let Some(ts) = options.timestamp {
            cmd = cmd.timestamp(ts);
        }
        if let Some(ms) = options.retention_ms {
            cmd = cmd.retention(ms);
        }
        for lbl in &options.labels {
            cmd = cmd.label(lbl.key.clone(), lbl.value.clone());
        }
        self.conn.execute(cmd).await
    }

    // -----------------------------------------------------------------------
    // Reading samples
    // -----------------------------------------------------------------------

    /// Return the last sample of a key, or `None` if the key has no samples.
    pub async fn get(&mut self, key: &str) -> Result<Option<TsSample>, RedisError> {
        let raw = self.conn.execute(TsGet::new(key)).await?;
        parse_get(raw)
    }

    /// Return the last sample, including the latest un-compacted bucket.
    pub async fn get_latest(&mut self, key: &str) -> Result<Option<TsSample>, RedisError> {
        let raw = self.conn.execute(TsGet::new(key).latest()).await?;
        parse_get(raw)
    }

    /// Query samples in chronological order.
    pub async fn range(
        &mut self,
        key: &str,
        query: TsRangeQuery,
    ) -> Result<Vec<TsSample>, RedisError> {
        let mut cmd = TsRange::new(key, query.from, query.to);
        if query.latest {
            cmd = cmd.latest();
        }
        if !query.filter_by_ts.is_empty() {
            cmd = cmd.filter_by_ts(query.filter_by_ts);
        }
        if let Some((min, max)) = query.filter_by_value {
            cmd = cmd.filter_by_value(min, max);
        }
        if let Some(n) = query.count {
            cmd = cmd.count(n);
        }
        if let Some((agg, bucket)) = query.aggregation {
            cmd = cmd.aggregation(agg, bucket);
        }
        let raw = self.conn.execute(cmd).await?;
        parse_samples(raw)
    }

    /// Query samples in reverse chronological order.
    pub async fn revrange(
        &mut self,
        key: &str,
        query: TsRangeQuery,
    ) -> Result<Vec<TsSample>, RedisError> {
        let mut cmd = TsRevRange::new(key, query.from, query.to);
        if query.latest {
            cmd = cmd.latest();
        }
        if !query.filter_by_ts.is_empty() {
            cmd = cmd.filter_by_ts(query.filter_by_ts);
        }
        if let Some((min, max)) = query.filter_by_value {
            cmd = cmd.filter_by_value(min, max);
        }
        if let Some(n) = query.count {
            cmd = cmd.count(n);
        }
        if let Some((agg, bucket)) = query.aggregation {
            cmd = cmd.aggregation(agg, bucket);
        }
        let raw = self.conn.execute(cmd).await?;
        parse_samples(raw)
    }

    /// Query samples across multiple keys in chronological order.
    pub async fn mrange(&mut self, query: TsMRangeQuery) -> Result<Vec<TsKeyResult>, RedisError> {
        let first_filter = query.filters.first().cloned().unwrap_or_default();
        let mut cmd = TsMRange::new(query.range.from, query.range.to, first_filter);
        for f in query.filters.iter().skip(1) {
            cmd = cmd.filter(f.clone());
        }
        if query.range.latest {
            cmd = cmd.latest();
        }
        if query.withlabels {
            cmd = cmd.withlabels();
        }
        if !query.range.filter_by_ts.is_empty() {
            cmd = cmd.filter_by_ts(query.range.filter_by_ts);
        }
        if let Some((min, max)) = query.range.filter_by_value {
            cmd = cmd.filter_by_value(min, max);
        }
        if let Some(n) = query.range.count {
            cmd = cmd.count(n);
        }
        if let Some((agg, bucket)) = query.range.aggregation {
            cmd = cmd.aggregation(agg, bucket);
        }
        let raw = self.conn.execute(cmd).await?;
        parse_mrange(raw)
    }

    /// Query samples across multiple keys in reverse chronological order.
    pub async fn mrevrange(
        &mut self,
        query: TsMRangeQuery,
    ) -> Result<Vec<TsKeyResult>, RedisError> {
        let first_filter = query.filters.first().cloned().unwrap_or_default();
        let mut cmd = TsMRevRange::new(query.range.from, query.range.to, first_filter);
        for f in query.filters.iter().skip(1) {
            cmd = cmd.filter(f.clone());
        }
        if query.range.latest {
            cmd = cmd.latest();
        }
        if query.withlabels {
            cmd = cmd.withlabels();
        }
        if !query.range.filter_by_ts.is_empty() {
            cmd = cmd.filter_by_ts(query.range.filter_by_ts);
        }
        if let Some((min, max)) = query.range.filter_by_value {
            cmd = cmd.filter_by_value(min, max);
        }
        if let Some(n) = query.range.count {
            cmd = cmd.count(n);
        }
        if let Some((agg, bucket)) = query.range.aggregation {
            cmd = cmd.aggregation(agg, bucket);
        }
        let raw = self.conn.execute(cmd).await?;
        parse_mrange(raw)
    }

    /// Return the last sample of every key matching `filter`.
    pub async fn mget(
        &mut self,
        filter: &str,
        withlabels: bool,
    ) -> Result<Vec<TsKeyResult>, RedisError> {
        let mut cmd = TsMGet::new(filter);
        if withlabels {
            cmd = cmd.withlabels();
        }
        let raw = self.conn.execute(cmd).await?;
        parse_mget(raw)
    }

    // -----------------------------------------------------------------------
    // Query and info
    // -----------------------------------------------------------------------

    /// Return all key names matching the given filter expression.
    pub async fn query_index(&mut self, filter: &str) -> Result<Vec<String>, RedisError> {
        let bytes = self.conn.execute(TsQueryIndex::new(filter)).await?;
        bytes
            .into_iter()
            .map(|b| {
                String::from_utf8(b.into()).map_err(|_| RedisError::TypeMismatch {
                    expected: "UTF-8 key name",
                })
            })
            .collect()
    }

    /// Return typed statistics for the given key.
    pub async fn info(&mut self, key: &str) -> Result<TsInfoResult, RedisError> {
        let raw = self.conn.execute(TsInfo::new(key)).await?;
        parse_info(raw)
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;
    use redis_tower_core::{Command, Frame};
    use std::collections::VecDeque;
    use std::future::Future;

    struct MockRedis {
        responses: VecDeque<Frame>,
    }

    impl MockRedis {
        fn new(responses: Vec<Frame>) -> Self {
            Self {
                responses: VecDeque::from(responses),
            }
        }
    }

    impl RedisExecutor for MockRedis {
        fn execute<Cmd: Command>(
            &mut self,
            cmd: Cmd,
        ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send {
            let frame = self.responses.pop_front().unwrap_or(Frame::Null);
            async move { cmd.parse_response(frame) }
        }
    }

    fn bulk(s: &str) -> Frame {
        Frame::BulkString(Some(Bytes::from(s.to_owned())))
    }

    fn int(n: i64) -> Frame {
        Frame::Integer(n)
    }

    // --- get ----------------------------------------------------------------

    #[tokio::test]
    async fn get_returns_none_for_empty_series() {
        // TS.GET on a key with no samples returns an empty array.
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let result = ts.get("sensors:temp").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn get_returns_sample() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            int(1_700_000_000_000),
            bulk("21.5"),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let result = ts.get("sensors:temp").await.unwrap();
        assert_eq!(
            result,
            Some(TsSample {
                timestamp: 1_700_000_000_000,
                value: 21.5,
            })
        );
    }

    #[tokio::test]
    async fn get_accepts_resp3_double_sample() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            int(1_700_000_000_000),
            Frame::Double(21.5),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);

        let result = ts.get("sensors:temp").await.unwrap();

        assert_eq!(
            result,
            Some(TsSample {
                timestamp: 1_700_000_000_000,
                value: 21.5,
            })
        );
    }

    // --- range --------------------------------------------------------------

    #[tokio::test]
    async fn range_returns_samples() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            Frame::Array(Some(vec![int(1_000), bulk("10.0")])),
            Frame::Array(Some(vec![int(2_000), bulk("20.0")])),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let samples = ts.range("key", TsRangeQuery::all()).await.unwrap();
        assert_eq!(samples.len(), 2);
        assert_eq!(
            samples[0],
            TsSample {
                timestamp: 1_000,
                value: 10.0
            }
        );
        assert_eq!(
            samples[1],
            TsSample {
                timestamp: 2_000,
                value: 20.0
            }
        );
    }

    #[tokio::test]
    async fn range_returns_empty_for_null_array() {
        let mut mock = MockRedis::new(vec![Frame::Array(None)]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let samples = ts.range("key", TsRangeQuery::all()).await.unwrap();
        assert!(samples.is_empty());
    }

    // --- mrange -------------------------------------------------------------

    #[tokio::test]
    async fn mrange_parses_multiple_keys() {
        // TS.MRANGE returns [[key, [[lk, lv], ...], [[ts, val], ...]], ...]
        let entry = Frame::Array(Some(vec![
            bulk("sensors:temp"),
            Frame::Array(Some(vec![Frame::Array(Some(vec![
                bulk("sensor"),
                bulk("temperature"),
            ]))])),
            Frame::Array(Some(vec![Frame::Array(Some(vec![
                int(1_700_000_000_000),
                bulk("22.0"),
            ]))])),
        ]));
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![entry]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let results = ts
            .mrange(TsMRangeQuery::new(TsRangeQuery::all(), "sensor=temperature").withlabels())
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].key, "sensors:temp");
        assert_eq!(results[0].labels.len(), 1);
        assert_eq!(results[0].labels[0].key, "sensor");
        assert_eq!(results[0].labels[0].value, "temperature");
        assert_eq!(results[0].samples.len(), 1);
        assert_eq!(results[0].samples[0].value, 22.0);
    }

    #[tokio::test]
    async fn mrange_accepts_resp3_map() {
        let mut mock = MockRedis::new(vec![Frame::Map(vec![(
            bulk("sensors:temp"),
            Frame::Array(Some(vec![
                Frame::Map(vec![(bulk("sensor"), bulk("temperature"))]),
                Frame::Map(vec![(bulk("aggregators"), Frame::Array(Some(vec![])))]),
                Frame::Array(Some(vec![Frame::Array(Some(vec![
                    int(1_700_000_000_000),
                    Frame::Double(22.0),
                ]))])),
            ])),
        )])]);
        let mut ts = TimeSeriesClient::new(&mut mock);

        let results = ts
            .mrange(TsMRangeQuery::new(TsRangeQuery::all(), "sensor=temperature").withlabels())
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].key, "sensors:temp");
        assert_eq!(results[0].labels[0].value, "temperature");
        assert_eq!(results[0].samples[0].value, 22.0);
    }

    #[tokio::test]
    async fn mget_accepts_resp3_map() {
        let mut mock = MockRedis::new(vec![Frame::StreamedMap(vec![(
            bulk("sensors:temp"),
            Frame::Array(Some(vec![
                Frame::StreamedMap(vec![(bulk("sensor"), Frame::Null)]),
                Frame::Array(Some(vec![int(1_700_000_000_000), Frame::Double(22.0)])),
            ])),
        )])]);
        let mut ts = TimeSeriesClient::new(&mut mock);

        let results = ts.mget("sensor=temperature", true).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].key, "sensors:temp");
        assert_eq!(results[0].labels[0].key, "sensor");
        assert_eq!(results[0].labels[0].value, "");
        assert_eq!(results[0].samples[0].value, 22.0);
    }

    // --- madd ---------------------------------------------------------------

    #[tokio::test]
    async fn madd_returns_timestamps() {
        // TS.MADD returns an array of integers.
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![int(1_000), int(2_000)]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let samples = vec![
            ("key1", TsTimestamp::Value(1_000), 1.0),
            ("key2", TsTimestamp::Value(2_000), 2.0),
        ];
        let results = ts.madd(&samples).await.unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].as_ref().unwrap(), &1_000i64);
        assert_eq!(results[1].as_ref().unwrap(), &2_000i64);
    }

    // --- info ---------------------------------------------------------------

    #[tokio::test]
    async fn info_parses_flat_kv_array() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            bulk("totalSamples"),
            int(42),
            bulk("memoryUsage"),
            int(4096),
            bulk("firstTimestamp"),
            int(1_000),
            bulk("lastTimestamp"),
            int(9_000),
            bulk("retentionTime"),
            int(3_600_000),
            bulk("chunkCount"),
            int(1),
            bulk("chunkSize"),
            int(4096),
            bulk("duplicatePolicy"),
            Frame::BulkString(Some(Bytes::from("LAST"))),
            bulk("labels"),
            Frame::Array(Some(vec![Frame::Array(Some(vec![
                bulk("sensor"),
                bulk("temperature"),
            ]))])),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let info = ts.info("sensors:temp").await.unwrap();
        assert_eq!(info.total_samples, 42);
        assert_eq!(info.memory_usage, 4096);
        assert_eq!(info.first_timestamp, 1_000);
        assert_eq!(info.last_timestamp, 9_000);
        assert_eq!(info.retention_time, 3_600_000);
        assert_eq!(info.chunk_count, 1);
        assert_eq!(info.chunk_size, 4096);
        assert_eq!(info.duplicate_policy, Some("LAST".to_string()));
        assert_eq!(info.labels.len(), 1);
        assert_eq!(info.labels[0].key, "sensor");
        assert_eq!(info.labels[0].value, "temperature");
    }

    #[tokio::test]
    async fn info_handles_null_duplicate_policy() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            bulk("totalSamples"),
            int(0),
            bulk("memoryUsage"),
            int(0),
            bulk("firstTimestamp"),
            int(0),
            bulk("lastTimestamp"),
            int(0),
            bulk("retentionTime"),
            int(0),
            bulk("chunkCount"),
            int(0),
            bulk("chunkSize"),
            int(0),
            bulk("duplicatePolicy"),
            Frame::Null,
            bulk("labels"),
            Frame::Array(None),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let info = ts.info("key").await.unwrap();
        assert_eq!(info.duplicate_policy, None);
        assert!(info.labels.is_empty());
    }

    #[tokio::test]
    async fn info_accepts_resp3_map() {
        let mut mock = MockRedis::new(vec![Frame::Map(vec![
            (bulk("totalSamples"), int(2)),
            (bulk("memoryUsage"), int(4096)),
            (bulk("firstTimestamp"), int(1_000)),
            (bulk("lastTimestamp"), int(2_000)),
            (bulk("retentionTime"), int(3_600_000)),
            (bulk("chunkCount"), int(1)),
            (bulk("chunkSize"), int(4096)),
            (bulk("duplicatePolicy"), Frame::Null),
            (
                bulk("labels"),
                Frame::Map(vec![(bulk("sensor"), bulk("temperature"))]),
            ),
        ])]);
        let mut ts = TimeSeriesClient::new(&mut mock);

        let info = ts.info("sensors:temp").await.unwrap();

        assert_eq!(info.total_samples, 2);
        assert_eq!(info.last_timestamp, 2_000);
        assert_eq!(info.labels.len(), 1);
        assert_eq!(info.labels[0].key, "sensor");
        assert_eq!(info.labels[0].value, "temperature");
    }

    // --- del_range ----------------------------------------------------------

    #[tokio::test]
    async fn del_range_returns_count() {
        let mut mock = MockRedis::new(vec![int(5)]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let n = ts.del_range("key", 0, 9_999).await.unwrap();
        assert_eq!(n, 5);
    }

    // --- create -------------------------------------------------------------

    #[tokio::test]
    async fn create_sends_ok() {
        let mut mock = MockRedis::new(vec![Frame::SimpleString(Bytes::from("OK"))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        ts.create(
            "sensors:temp",
            TsKeyConfig::new()
                .retention(3_600_000)
                .label("sensor", "temperature"),
        )
        .await
        .unwrap();
    }

    // --- query_index --------------------------------------------------------

    #[tokio::test]
    async fn query_index_returns_key_names() {
        let mut mock = MockRedis::new(vec![Frame::Array(Some(vec![
            Frame::BulkString(Some(Bytes::from("sensors:temp"))),
            Frame::BulkString(Some(Bytes::from("sensors:humidity"))),
        ]))]);
        let mut ts = TimeSeriesClient::new(&mut mock);
        let keys = ts.query_index("sensor!=").await.unwrap();
        assert_eq!(keys, vec!["sensors:temp", "sensors:humidity"]);
    }
}