vectorizer-sdk 3.3.0

Rust SDK for Vectorizer — RPC-first (vectorizer://) with HTTP fallback
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
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
//! Data models for the Vectorizer SDK

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

// Re-export hybrid search models
pub mod hybrid_search;
pub use hybrid_search::*;

// Re-export graph models
pub mod graph;
pub use graph::*;

// Re-export file upload models
pub mod file_upload;
pub use file_upload::*;

// Typed Qdrant-compatible filter builder (phase23).
// Exposed as `vectorizer_sdk::models::filter` so callers do not need
// to depend on the server crate directly.
pub mod filter;
pub use filter::{
    QdrantCondition, QdrantFilter, QdrantGeoBoundingBox, QdrantGeoPoint, QdrantGeoRadius,
    QdrantMatchValue, QdrantRange, QdrantValuesCount,
};

// ===== TIER-CONTROL REPORTS (phase13) =====

/// Aggregate outcome of a `delete_by_filter` call against
/// `POST /collections/{name}/vectors/delete_by_filter`.
///
/// Server contract: `{scanned, matched, deleted, results}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DeleteByFilterReport {
    /// Total vectors scanned by the filter pass.
    pub scanned: usize,
    /// Vectors that matched the filter predicate.
    pub matched: usize,
    /// Vectors successfully deleted.
    pub deleted: usize,
    /// Per-id outcomes for matched vectors.
    #[serde(default)]
    pub results: Vec<serde_json::Value>,
}

/// Aggregate outcome of a `bulk_update_metadata` call against
/// `POST /collections/{name}/vectors/bulk_update_metadata`.
///
/// Server contract: `{scanned, matched, updated, results}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BulkUpdateReport {
    /// Total vectors scanned by the filter pass.
    pub scanned: usize,
    /// Vectors that matched the filter predicate.
    pub matched: usize,
    /// Vectors whose metadata was successfully updated.
    pub updated: usize,
    /// Per-id outcomes for matched vectors.
    #[serde(default)]
    pub results: Vec<serde_json::Value>,
}

/// Aggregate outcome of a `copy_vectors` call against
/// `POST /collections/{src}/vectors/copy`.
///
/// Server contract: `{src, dst, requested, copied, failed, results}`.
/// Per-id status: `ok | missing_in_src | dst_insert_failed`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CopyReport {
    /// Source collection name, echoed by the server.
    pub src: String,
    /// Destination collection name, echoed by the server.
    pub dst: String,
    /// Total ids the request asked to copy.
    pub requested: usize,
    /// Successfully copied ids.
    pub copied: usize,
    /// Ids that failed at any step.
    pub failed: usize,
    /// Per-id outcomes, in request order.
    pub results: Vec<VectorOpResult>,
}

/// Job descriptor returned by `reencode_collection` against
/// `POST /collections/{name}/reencode`.
///
/// Server contract: `{job_id, collection, state, target_encoding, progress}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReencodeJob {
    /// Opaque job id generated by the server.
    pub job_id: String,
    /// Collection being re-encoded.
    pub collection: String,
    /// Job state string (e.g. `"completed"`).
    pub state: String,
    /// Target encoding requested (e.g. `"sq8"`, `"binary"`, `"fp32"`).
    pub target_encoding: String,
    /// Progress fraction in `[0.0, 1.0]`.
    pub progress: f64,
}

// ===== TIER-DEMOTION REPORTS (issue #265) =====

/// Per-vector outcome for a `delete_vectors` or `move_to_collection`
/// call. The `status` string is one of:
///
/// - `ok` — vector was deleted (delete) or moved (move) successfully.
/// - `missing_in_src` — id was not present in the source collection.
/// - `dst_insert_failed` — destination rejected the insert (move only;
///   typically a dim/encoding mismatch).
/// - `src_delete_failed` — destination accepted the insert but the
///   source delete failed (move only; the vector now exists in BOTH
///   collections — recoverable on retry).
/// - `error` — generic per-id failure (delete only).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct VectorOpResult {
    /// Vector id this row refers to. May be missing when the request
    /// payload contained a non-string entry that the server rejected.
    #[serde(default)]
    pub id: Option<String>,

    /// One of `ok | missing_in_src | dst_insert_failed |
    /// src_delete_failed | error` — see [`VectorOpResult`] doc.
    pub status: String,

    /// Server-side error message, populated when `status != "ok"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,

    /// Index of this entry in the request's `ids` array (delete only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
}

/// Aggregate outcome of a `delete_vectors` call against
/// `POST /batch_delete`. Mirrors the server contract:
/// `{collection, count, deleted, failed, results}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DeleteReport {
    /// Source collection name, echoed by the server.
    pub collection: String,
    /// Total ids the request asked to delete.
    #[serde(default)]
    pub count: usize,
    /// Successfully deleted ids.
    pub deleted: usize,
    /// Ids that failed (missing or backend error).
    pub failed: usize,
    /// Per-id outcomes, in request order.
    pub results: Vec<VectorOpResult>,
}

/// Aggregate outcome of a `move_to_collection` call against
/// `POST /collections/{src}/vectors/move` (issue #265).
///
/// Server invariant: vectors are inserted into `dst` BEFORE being
/// deleted from `src`, so a mid-batch failure leaves a recoverable
/// duplicate (never data loss). Per-id failures populate `results`
/// without aborting the batch — operators chasing tier-demotion sweeps
/// want partial progress, not an abort-on-first-error contract.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MoveReport {
    /// Source collection name, echoed by the server.
    pub src: String,
    /// Destination collection name, echoed by the server.
    pub dst: String,
    /// Total ids the request asked to move.
    pub requested: usize,
    /// Successfully moved ids (insert + delete both succeeded).
    pub moved: usize,
    /// Ids that failed at any step.
    pub failed: usize,
    /// Per-id outcomes, in request order.
    pub results: Vec<VectorOpResult>,
}

// ===== CLIENT-SIDE REPLICATION CONFIGURATION =====

/// Read preference for routing read operations.
/// Similar to MongoDB's read preferences.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ReadPreference {
    /// Route all reads to master
    Master,
    /// Route reads to replicas (round-robin)
    #[default]
    Replica,
    /// Route to the node with lowest latency
    Nearest,
}

/// Host configuration for master/replica topology.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostConfig {
    /// Master node URL (receives all write operations)
    pub master: String,
    /// Replica node URLs (receive read operations based on read_preference)
    pub replicas: Vec<String>,
}

/// Options that can be passed to read operations for per-operation override.
#[derive(Debug, Clone, Default)]
pub struct ReadOptions {
    /// Override the default read preference for this operation
    pub read_preference: Option<ReadPreference>,
}

/// Vector similarity metrics
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SimilarityMetric {
    /// Cosine similarity
    #[default]
    Cosine,
    /// Euclidean distance
    Euclidean,
    /// Dot product
    DotProduct,
}

/// Vector representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Vector {
    /// Unique identifier for the vector
    pub id: String,
    /// Vector data as an array of numbers
    pub data: Vec<f32>,
    /// Optional metadata associated with the vector
    pub metadata: Option<HashMap<String, serde_json::Value>>,
    /// Optional ECC public key for payload encryption (PEM, base64, or hex format)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_key: Option<String>,
}

/// Collection representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Collection {
    /// Collection name
    pub name: String,
    /// Vector dimension
    pub dimension: usize,
    /// Similarity metric used for search (API may return as 'metric')
    #[serde(alias = "similarity_metric")]
    pub metric: Option<String>,
    /// Optional description
    #[serde(default)]
    pub description: Option<String>,
    /// Creation timestamp
    #[serde(default)]
    pub created_at: Option<String>,
    /// Last update timestamp
    #[serde(default)]
    pub updated_at: Option<String>,
    /// Vector count
    #[serde(default)]
    pub vector_count: usize,
    /// Document count
    #[serde(default)]
    pub document_count: usize,
    /// Embedding provider
    #[serde(default)]
    pub embedding_provider: Option<String>,
    /// Indexing status
    #[serde(default)]
    pub indexing_status: Option<serde_json::Value>,
    /// Normalization config
    #[serde(default)]
    pub normalization: Option<serde_json::Value>,
    /// Quantization config
    #[serde(default)]
    pub quantization: Option<serde_json::Value>,
    /// Size info
    #[serde(default)]
    pub size: Option<serde_json::Value>,
    /// Per-collection vector-count ring buffer (phase25 §6). At most
    /// 60 samples, one per minute, sampled lazily on
    /// `GET /collections/{name}` requests. Empty array on older
    /// servers or for collections that have never been read.
    #[serde(default)]
    pub vector_count_history: Vec<VectorCountSample>,
}

/// One sample in the per-collection vector-count history (phase25 §6).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct VectorCountSample {
    /// Sample timestamp in unix seconds.
    pub at: u64,
    /// Vector count at the time of the sample.
    pub count: usize,
}

/// Collection information.
///
/// The v3.0.0 REST surface returns `metric` in Rust-Debug form
/// (e.g. `"Cosine"`), plus new top-level blocks (`size`, `quantization`,
/// `normalization`, `status`). Every field beyond `name` + `dimension`
/// carries `#[serde(default)]` so the model tolerates pre-v3 servers
/// and future additions (request models keep the strict posture; this
/// is a response-only struct).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionInfo {
    /// Collection name
    pub name: String,
    /// Vector dimension
    pub dimension: usize,
    /// Similarity metric used for search. The v3 server emits this in
    /// Rust-Debug form (`"Cosine"` / `"Euclidean"` / `"DotProduct"`);
    /// callers that compare against `"cosine"` etc. should go through
    /// `.to_lowercase()`.
    #[serde(default, alias = "similarity_metric")]
    pub metric: String,
    /// Number of vectors in the collection
    #[serde(default)]
    pub vector_count: usize,
    /// Number of documents in the collection
    #[serde(default)]
    pub document_count: usize,
    /// Creation timestamp (RFC3339). Optional — pre-v3 servers may omit.
    #[serde(default)]
    pub created_at: String,
    /// Last update timestamp (RFC3339). Optional — pre-v3 servers may omit.
    #[serde(default)]
    pub updated_at: String,
    /// Indexing status. Absent on the v3 server; some legacy servers send it.
    #[serde(default)]
    pub indexing_status: Option<IndexingStatus>,
    /// Size block emitted by v3 (`{total, total_bytes, index, index_bytes,
    /// payload, payload_bytes}`).
    #[serde(default)]
    pub size: Option<serde_json::Value>,
    /// Quantization block emitted by v3 (`{enabled, type, bits}`).
    #[serde(default)]
    pub quantization: Option<serde_json::Value>,
    /// Normalization block emitted by v3.
    #[serde(default)]
    pub normalization: Option<serde_json::Value>,
    /// Ready/indexing/error state emitted by v3.
    #[serde(default)]
    pub status: Option<String>,
}

/// Indexing status.
///
/// Every field carries `#[serde(default)]` to match the tolerant
/// posture of the parent [`CollectionInfo`] — the v3 server emits a
/// subset of this shape (`status`/`progress`/`total_documents`/
/// `processed_documents` plus some extra keys this struct doesn't
/// model) and omits `vector_count` and `last_updated`, which used to
/// make `serde_json::from_str::<CollectionInfo>` fail on a
/// `Collection → JSON → CollectionInfo` round-trip through
/// `Collection::indexing_status: Option<serde_json::Value>` that
/// preserves the server's partial shape.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexingStatus {
    /// Status
    #[serde(default)]
    pub status: String,
    /// Progress percentage
    #[serde(default)]
    pub progress: f32,
    /// Total documents
    #[serde(default)]
    pub total_documents: usize,
    /// Processed documents
    #[serde(default)]
    pub processed_documents: usize,
    /// Vector count
    #[serde(default)]
    pub vector_count: usize,
    /// Estimated time remaining
    #[serde(default)]
    pub estimated_time_remaining: Option<String>,
    /// Last updated timestamp
    #[serde(default)]
    pub last_updated: String,
}

/// Search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Vector ID
    pub id: String,
    /// Similarity score
    pub score: f32,
    /// Vector content (if available)
    pub content: Option<String>,
    /// Optional metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

/// Search response.
///
/// `query_time_ms` defaults to `0.0` because the v3.0.x server's text
/// search handler doesn't emit it — callers that need elapsed timing
/// should measure client-side. Same tolerance applies to the
/// additional diagnostic fields the server may add in later versions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResponse {
    /// Search results.
    #[serde(default)]
    pub results: Vec<SearchResult>,
    /// Query time in milliseconds (server-reported; 0.0 when the
    /// server omits it).
    #[serde(default)]
    pub query_time_ms: f64,
    /// Echo of the original query string, if the server returned one.
    #[serde(default)]
    pub query: Option<String>,
    /// Echo of the requested result limit, if the server returned one.
    #[serde(default)]
    pub limit: Option<usize>,
    /// Echo of the collection name, if the server returned one.
    #[serde(default)]
    pub collection: Option<String>,
}

/// Embedding request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingRequest {
    /// Text to embed
    pub text: String,
    /// Optional model to use for embedding
    pub model: Option<String>,
    /// Optional parameters for embedding generation
    pub parameters: Option<EmbeddingParameters>,
}

/// Embedding parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingParameters {
    /// Maximum sequence length
    pub max_length: Option<usize>,
    /// Whether to normalize the embedding
    pub normalize: Option<bool>,
    /// Optional prefix for the text
    pub prefix: Option<String>,
}

/// Embedding response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingResponse {
    /// Generated embedding vector
    pub embedding: Vec<f32>,
    /// Model used for embedding
    pub model: String,
    /// Text that was embedded
    pub text: String,
    /// Embedding dimension
    pub dimension: usize,
    /// Provider used
    pub provider: String,
}

/// Health status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
    /// Service status
    pub status: String,
    /// Service version
    pub version: String,
    /// Timestamp
    pub timestamp: String,
    /// Uptime in seconds
    pub uptime: Option<u64>,
    /// Number of collections
    pub collections: Option<usize>,
    /// Total number of vectors
    pub total_vectors: Option<usize>,
}

/// Collections list response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionsResponse {
    /// List of collections
    pub collections: Vec<Collection>,
}

/// Create collection response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateCollectionResponse {
    /// Success message
    pub message: String,
    /// Collection name
    pub collection: String,
}

/// Database statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseStats {
    /// Total number of collections
    pub total_collections: usize,
    /// Total number of vectors
    pub total_vectors: usize,
    /// Total memory estimate in bytes
    pub total_memory_estimate_bytes: usize,
    /// Collections information
    pub collections: Vec<CollectionStats>,
}

/// Collection statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionStats {
    /// Collection name
    pub name: String,
    /// Number of vectors
    pub vector_count: usize,
    /// Vector dimension
    pub dimension: usize,
    /// Memory estimate in bytes
    pub memory_estimate_bytes: usize,
}

/// Batch text request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchTextRequest {
    /// Text ID
    pub id: String,
    /// Text content
    pub text: String,
    /// Optional metadata
    pub metadata: Option<HashMap<String, String>>,
}

/// Batch configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchConfig {
    /// Maximum batch size
    pub max_batch_size: Option<usize>,
    /// Number of parallel workers
    pub parallel_workers: Option<usize>,
    /// Whether operations should be atomic
    pub atomic: Option<bool>,
}

/// Batch insert request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchInsertRequest {
    /// Texts to insert
    pub texts: Vec<BatchTextRequest>,
    /// Batch configuration
    pub config: Option<BatchConfig>,
}

/// Batch response.
///
/// Tolerant of both the old (pre-v3) `{success, operation, total_operations,
/// successful_operations, failed_operations, duration_ms, errors}` shape
/// and the v3.0.x server's `/insert_texts` response
/// `{collection, count, inserted, failed, results}`. All fields default to
/// empty/zero/false when absent so callers can match on whichever pair the
/// running server emits without branching on version.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchResponse {
    /// Whether the operation was successful (pre-v3 shape; v3 emits
    /// `inserted`/`failed` instead — left `false` and the caller
    /// should inspect `successful_operations > 0 && failed_operations == 0`).
    #[serde(default)]
    pub success: bool,
    /// Collection name (both shapes emit this).
    #[serde(default)]
    pub collection: String,
    /// Operation type (pre-v3 only; v3 omits).
    #[serde(default)]
    pub operation: String,
    /// Total number of operations (pre-v3 shape). v3 emits `count` —
    /// normalised into this field via the alias.
    #[serde(default, alias = "count")]
    pub total_operations: usize,
    /// Number of successful operations (pre-v3 shape). v3 emits
    /// `inserted` — aliased so either maps onto this field.
    #[serde(default, alias = "inserted")]
    pub successful_operations: usize,
    /// Number of failed operations. Same field name in both shapes.
    #[serde(default, alias = "failed")]
    pub failed_operations: usize,
    /// Duration in milliseconds (pre-v3 only).
    #[serde(default)]
    pub duration_ms: u64,
    /// Error messages (pre-v3 shape).
    #[serde(default)]
    pub errors: Vec<String>,
    /// Per-entry result records emitted by v3 `/insert_texts`. Each
    /// record carries the client-sent id (`client_id`) and the
    /// server-assigned UUIDs under `vector_ids`; use this when the
    /// server reassigns ids on insert.
    #[serde(default)]
    pub results: Vec<BatchResultEntry>,
}

/// One entry in `BatchResponse::results` as emitted by the v3
/// `/insert_texts` handler. Carries the client-provided id alongside
/// the server-assigned vector UUID(s) so callers can round-trip the
/// mapping when they need idempotency by client id.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchResultEntry {
    /// Original `id` the caller sent in `BatchTextRequest`.
    #[serde(default)]
    pub client_id: String,
    /// Zero-based index of the entry in the original batch.
    #[serde(default)]
    pub index: usize,
    /// `"ok"` or `"error"`.
    #[serde(default)]
    pub status: String,
    /// Whether the server chunked the input (long text → multiple
    /// vectors).
    #[serde(default)]
    pub chunked: bool,
    /// Server-assigned UUID(s) — one element unless `chunked` is true.
    #[serde(default)]
    pub vector_ids: Vec<String>,
    /// Count of vectors created for this entry (≥1 if `chunked`).
    #[serde(default)]
    pub vectors_created: usize,
    /// Populated only on `status == "error"`.
    #[serde(default)]
    pub error: Option<String>,
}

/// Batch search request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchSearchRequest {
    /// Search queries
    pub queries: Vec<BatchSearchQuery>,
    /// Batch configuration
    pub config: Option<BatchConfig>,
}

/// Batch search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchSearchResponse {
    /// Whether the operation was successful
    pub success: bool,
    /// Collection name
    pub collection: String,
    /// Total number of queries
    pub total_queries: usize,
    /// Number of successful queries
    pub successful_queries: usize,
    /// Number of failed queries
    pub failed_queries: usize,
    /// Duration in milliseconds
    pub duration_ms: u64,
    /// Search results
    pub results: Vec<Vec<SearchResult>>,
    /// Error messages
    pub errors: Vec<String>,
}

/// Batch vector update
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchVectorUpdate {
    /// Vector ID
    pub id: String,
    /// New vector data (optional)
    pub data: Option<Vec<f32>>,
    /// New metadata (optional)
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

/// Batch update request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchUpdateRequest {
    /// Vector updates
    pub updates: Vec<BatchVectorUpdate>,
    /// Batch configuration
    pub config: Option<BatchConfig>,
}

/// Batch delete request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchDeleteRequest {
    /// Vector IDs to delete
    pub vector_ids: Vec<String>,
    /// Batch configuration
    pub config: Option<BatchConfig>,
}

/// Summarization methods
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SummarizationMethod {
    /// Extractive summarization
    #[default]
    Extractive,
    /// Keyword summarization
    Keyword,
    /// Sentence summarization
    Sentence,
    /// Abstractive summarization
    Abstractive,
}

/// Summarize text request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummarizeTextRequest {
    /// Text to summarize
    pub text: String,
    /// Summarization method
    pub method: Option<SummarizationMethod>,
    /// Maximum summary length
    pub max_length: Option<usize>,
    /// Compression ratio
    pub compression_ratio: Option<f32>,
    /// Language code
    pub language: Option<String>,
}

/// Summarize text response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummarizeTextResponse {
    /// Summary ID
    pub summary_id: String,
    /// Original text
    pub original_text: String,
    /// Generated summary
    pub summary: String,
    /// Method used
    pub method: String,
    /// Original text length
    pub original_length: usize,
    /// Summary length
    pub summary_length: usize,
    /// Compression ratio
    pub compression_ratio: f32,
    /// Language
    pub language: String,
    /// Status
    pub status: String,
    /// Message
    pub message: String,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// Summarize context request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummarizeContextRequest {
    /// Context to summarize
    pub context: String,
    /// Summarization method
    pub method: Option<SummarizationMethod>,
    /// Maximum summary length
    pub max_length: Option<usize>,
    /// Compression ratio
    pub compression_ratio: Option<f32>,
    /// Language code
    pub language: Option<String>,
}

/// Summarize context response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummarizeContextResponse {
    /// Summary ID
    pub summary_id: String,
    /// Original context
    pub original_context: String,
    /// Generated summary
    pub summary: String,
    /// Method used
    pub method: String,
    /// Original context length
    pub original_length: usize,
    /// Summary length
    pub summary_length: usize,
    /// Compression ratio
    pub compression_ratio: f32,
    /// Language
    pub language: String,
    /// Status
    pub status: String,
    /// Message
    pub message: String,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// Get summary response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetSummaryResponse {
    /// Summary ID
    pub summary_id: String,
    /// Original text
    pub original_text: String,
    /// Generated summary
    pub summary: String,
    /// Method used
    pub method: String,
    /// Original text length
    pub original_length: usize,
    /// Summary length
    pub summary_length: usize,
    /// Compression ratio
    pub compression_ratio: f32,
    /// Language
    pub language: String,
    /// Creation timestamp
    pub created_at: String,
    /// Metadata
    pub metadata: HashMap<String, String>,
    /// Status
    pub status: String,
}

/// Summary info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummaryInfo {
    /// Summary ID
    pub summary_id: String,
    /// Method used
    pub method: String,
    /// Language
    pub language: String,
    /// Original text length
    pub original_length: usize,
    /// Summary length
    pub summary_length: usize,
    /// Compression ratio
    pub compression_ratio: f32,
    /// Creation timestamp
    pub created_at: String,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// List summaries response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListSummariesResponse {
    /// List of summaries
    pub summaries: Vec<SummaryInfo>,
    /// Total count
    pub total_count: usize,
    /// Status
    pub status: String,
}

/// Indexing progress
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexingProgress {
    /// Whether indexing is in progress
    pub is_indexing: bool,
    /// Overall status
    pub overall_status: String,
    /// Collections being indexed
    pub collections: Vec<CollectionProgress>,
}

/// Collection progress
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CollectionProgress {
    /// Collection name
    pub collection_name: String,
    /// Status
    pub status: String,
    /// Progress percentage
    pub progress: f32,
    /// Vector count
    pub vector_count: usize,
    /// Error message if any
    pub error_message: Option<String>,
    /// Last updated timestamp
    pub last_updated: String,
}

// ===== INTELLIGENT SEARCH MODELS =====

/// Intelligent search request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntelligentSearchRequest {
    /// Search query
    pub query: String,
    /// Collections to search (optional - searches all if not specified)
    pub collections: Option<Vec<String>>,
    /// Maximum number of results
    pub max_results: Option<usize>,
    /// Enable domain expansion
    pub domain_expansion: Option<bool>,
    /// Enable technical focus
    pub technical_focus: Option<bool>,
    /// Enable MMR diversification
    pub mmr_enabled: Option<bool>,
    /// MMR balance parameter (0.0-1.0)
    pub mmr_lambda: Option<f32>,
}

/// Semantic search request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticSearchRequest {
    /// Search query
    pub query: String,
    /// Collection to search
    pub collection: String,
    /// Maximum number of results
    pub max_results: Option<usize>,
    /// Enable semantic reranking
    pub semantic_reranking: Option<bool>,
    /// Enable cross-encoder reranking
    pub cross_encoder_reranking: Option<bool>,
    /// Minimum similarity threshold
    pub similarity_threshold: Option<f32>,
}

/// Contextual search request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextualSearchRequest {
    /// Search query
    pub query: String,
    /// Collection to search
    pub collection: String,
    /// Metadata-based context filters
    pub context_filters: Option<HashMap<String, serde_json::Value>>,
    /// Maximum number of results
    pub max_results: Option<usize>,
    /// Enable context-aware reranking
    pub context_reranking: Option<bool>,
    /// Weight of context factors (0.0-1.0)
    pub context_weight: Option<f32>,
}

/// Multi-collection search request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiCollectionSearchRequest {
    /// Search query
    pub query: String,
    /// Collections to search
    pub collections: Vec<String>,
    /// Maximum results per collection
    pub max_per_collection: Option<usize>,
    /// Maximum total results
    pub max_total_results: Option<usize>,
    /// Enable cross-collection reranking
    pub cross_collection_reranking: Option<bool>,
}

/// Intelligent search result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntelligentSearchResult {
    /// Result ID
    pub id: String,
    /// Similarity score
    pub score: f32,
    /// Result content
    pub content: String,
    /// Metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
    /// Collection name
    pub collection: Option<String>,
    /// Query used for this result
    pub query_used: Option<String>,
}

/// Intelligent search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntelligentSearchResponse {
    /// Search results
    pub results: Vec<IntelligentSearchResult>,
    /// Total number of results found
    pub total_results: usize,
    /// Search duration in milliseconds
    pub duration_ms: u64,
    /// Queries generated
    pub queries_generated: Option<Vec<String>>,
    /// Collections searched
    pub collections_searched: Option<Vec<String>>,
    /// Search metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

/// Semantic search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticSearchResponse {
    /// Search results
    pub results: Vec<IntelligentSearchResult>,
    /// Total number of results found
    pub total_results: usize,
    /// Search duration in milliseconds
    pub duration_ms: u64,
    /// Collection searched
    pub collection: String,
    /// Search metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

/// Contextual search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextualSearchResponse {
    /// Search results
    pub results: Vec<IntelligentSearchResult>,
    /// Total number of results found
    pub total_results: usize,
    /// Search duration in milliseconds
    pub duration_ms: u64,
    /// Collection searched
    pub collection: String,
    /// Context filters applied
    pub context_filters: Option<HashMap<String, serde_json::Value>>,
    /// Search metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

/// Multi-collection search response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiCollectionSearchResponse {
    /// Search results
    pub results: Vec<IntelligentSearchResult>,
    /// Total number of results found
    pub total_results: usize,
    /// Search duration in milliseconds
    pub duration_ms: u64,
    /// Collections searched
    pub collections_searched: Vec<String>,
    /// Results per collection
    pub results_per_collection: Option<HashMap<String, usize>>,
    /// Search metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

// ==================== REPLICATION MODELS ====================

/// Status of a replica node
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ReplicaStatus {
    /// Replica is connected and healthy
    Connected,
    /// Replica is syncing data
    Syncing,
    /// Replica is lagging behind master
    Lagging,
    /// Replica is disconnected
    Disconnected,
}

/// Information about a replica node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicaInfo {
    /// Unique identifier for the replica
    pub replica_id: String,
    /// Hostname or IP address of the replica
    pub host: String,
    /// Port number of the replica
    pub port: u16,
    /// Current status of the replica
    pub status: String,
    /// Timestamp of last heartbeat
    pub last_heartbeat: DateTime<Utc>,
    /// Number of operations successfully synced
    pub operations_synced: u64,

    // Legacy fields (backwards compatible)
    /// Legacy: Current offset on replica (deprecated, use operations_synced)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u64>,
    /// Legacy: Lag in operations (deprecated, use status)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lag: Option<u64>,
}

/// Statistics for replication status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationStats {
    // New fields (v1.2.0+)
    /// Role of the node: Master or Replica
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    /// Total bytes sent to replicas (Master only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bytes_sent: Option<u64>,
    /// Total bytes received from master (Replica only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bytes_received: Option<u64>,
    /// Timestamp of last synchronization
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_sync: Option<DateTime<Utc>>,
    /// Number of operations pending replication
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations_pending: Option<usize>,
    /// Size of snapshot data in bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_size: Option<usize>,
    /// Number of connected replicas (Master only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connected_replicas: Option<usize>,

    // Legacy fields (backwards compatible - always present)
    /// Current offset on master node
    pub master_offset: u64,
    /// Current offset on replica node
    pub replica_offset: u64,
    /// Number of operations behind
    pub lag_operations: u64,
    /// Total operations replicated
    pub total_replicated: u64,
}

/// Response for replication status endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationStatusResponse {
    /// Overall status message
    pub status: String,
    /// Detailed replication statistics
    pub stats: ReplicationStats,
    /// Optional message with additional information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Response for listing replicas
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicaListResponse {
    /// List of replica nodes
    pub replicas: Vec<ReplicaInfo>,
    /// Total count of replicas
    pub count: usize,
    /// Status message
    pub message: String,
}

// ===== VECTOR OPERATIONS — NEW METHODS (phase12) =====

/// Paginated vector listing returned by `GET /collections/{name}/vectors`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorPage {
    /// Vectors on this page — each entry carries `id`, `vector`, and `payload`.
    #[serde(default)]
    pub vectors: Vec<serde_json::Value>,
    /// Total vector count in the collection (unfiltered).
    #[serde(default)]
    pub total: usize,
    /// The effective `limit` applied by the server.
    #[serde(default)]
    pub limit: usize,
    /// The byte-offset applied by the server.
    ///
    /// Note: the task spec calls this `page` but the server handler
    /// (`GET /collections/{name}/vectors`) uses an `offset` query
    /// parameter internally and echoes it back as `offset`.
    #[serde(default)]
    pub offset: usize,
    /// Optional human-readable pagination hint from the server.
    #[serde(default)]
    pub message: Option<String>,
}

/// Request body for `update_vector` (`POST /update`).
///
/// Server reads `id` and `collection` from the top-level body.
/// All other keys are treated as payload updates.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateVectorRequest {
    /// Vector id to update.
    pub id: String,
    /// New metadata / payload to merge (free-form JSON).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// One item in a `batch_insert_texts` call (`POST /batch_insert`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchInsertItem {
    /// Optional client-supplied id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Text content to embed and insert.
    pub text: String,
    /// Optional metadata to attach.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// Aggregate outcome of a `batch_insert_texts` or `insert_vectors` call.
/// Server response shape: `{collection, inserted, failed, count, results}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchInsertReport {
    /// Collection the vectors were inserted into.
    pub collection: String,
    /// Vectors successfully inserted.
    #[serde(alias = "inserted")]
    pub successful: usize,
    /// Vectors that failed.
    pub failed: usize,
    /// Total entries submitted.
    #[serde(default, alias = "count")]
    pub total: usize,
    /// Per-entry results.
    #[serde(default)]
    pub results: Vec<BatchResultEntry>,
}

/// One entry in a `batch_update_vectors` call (`POST /batch_update`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorUpdate {
    /// Vector id to update.
    pub id: String,
    /// Optional new dense vector data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vector: Option<Vec<f32>>,
    /// Optional new payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Value>,
}

/// Aggregate outcome of a `batch_update_vectors` call.
/// Server response: `{collection, count, updated, failed, results}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchUpdateReport {
    /// Collection the update ran against.
    pub collection: String,
    /// Total entries submitted.
    #[serde(default, alias = "count")]
    pub total: usize,
    /// Successfully updated entries.
    #[serde(alias = "updated")]
    pub successful: usize,
    /// Failed entries.
    pub failed: usize,
    /// Per-entry results.
    #[serde(default)]
    pub results: Vec<serde_json::Value>,
}

/// One vector entry in an `insert_vectors` call (`POST /insert_vectors`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawVectorInsert {
    /// Optional client-supplied id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Pre-computed embedding (length must match collection dimension).
    pub embedding: Vec<f32>,
    /// Optional payload (takes precedence over `metadata`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Value>,
    /// Optional metadata (string–string map; used when `payload` absent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, String>>,
}

/// One query in a `batch_search` call (`POST /batch_search`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchSearchQuery {
    /// Text query (embedded server-side) or raw vector (send via `vector`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    /// Raw vector query (skips embedding).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vector: Option<Vec<f32>>,
    /// Max results for this query.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    /// Score threshold.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
}

/// Request for `search_by_file` (`POST /collections/{name}/search/file`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchByFileRequest {
    /// File path to search within.
    pub file_path: String,
    /// Max results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

// ===== DISCOVERY PIPELINE TYPES (phase12) =====

/// Request for `broad_discovery` (`POST /discovery/broad_discovery`).
///
/// Server reads `queries` (array of strings) and optional `k`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BroadDiscoveryRequest {
    /// Expanded query strings to search across all collections.
    pub queries: Vec<String>,
    /// Number of top chunks to retrieve per query (default 50).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub k: Option<usize>,
}

/// Response from `broad_discovery`.
/// Server: `{chunks: [{collection, score, content_preview}], count}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BroadDiscoveryResponse {
    /// Retrieved chunk summaries.
    #[serde(default)]
    pub chunks: Vec<serde_json::Value>,
    /// Total chunks returned.
    #[serde(default)]
    pub count: usize,
}

/// Request for `semantic_focus` (`POST /discovery/semantic_focus`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticFocusRequest {
    /// Target collection name.
    pub collection: String,
    /// Queries to focus within the collection.
    pub queries: Vec<String>,
    /// Number of top results per query (default 15).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub k: Option<usize>,
}

/// Response from `semantic_focus`.
/// Server: `{chunks: [...], count}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticFocusResponse {
    /// Retrieved chunk summaries.
    #[serde(default)]
    pub chunks: Vec<serde_json::Value>,
    /// Total chunks returned.
    #[serde(default)]
    pub count: usize,
}

/// Request for `promote_readme` (`POST /discovery/promote_readme`).
/// `chunks` is an array of `ScoredChunk`-compatible objects.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromoteReadmeRequest {
    /// Chunks to evaluate for README promotion.
    pub chunks: Vec<serde_json::Value>,
}

/// Response from `promote_readme`.
/// Server: `{promoted_chunks: [...], count}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromoteReadmeResponse {
    /// Chunks identified as README-quality.
    #[serde(default)]
    pub promoted_chunks: Vec<serde_json::Value>,
    /// Count of promoted chunks.
    #[serde(default)]
    pub count: usize,
}

/// Request for `compress_evidence` (`POST /discovery/compress_evidence`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressEvidenceRequest {
    /// Input chunks to compress into bullets.
    pub chunks: Vec<serde_json::Value>,
    /// Maximum number of bullets to emit (default 20).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_bullets: Option<usize>,
    /// Maximum bullets per source document (default 3).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_per_doc: Option<usize>,
}

/// Response from `compress_evidence`.
/// Server: `{bullets: [{text, source_id, category, score}], count}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressEvidenceResponse {
    /// Compressed bullet points.
    #[serde(default)]
    pub bullets: Vec<serde_json::Value>,
    /// Count of bullets.
    #[serde(default)]
    pub count: usize,
}

/// Request for `build_answer_plan` (`POST /discovery/build_answer_plan`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnswerPlanRequest {
    /// Bullets to organize into a plan.
    pub bullets: Vec<serde_json::Value>,
}

/// Response from `build_answer_plan`.
/// Server: `{sections: [...], total_bullets, sources}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnswerPlan {
    /// Organized sections.
    #[serde(default)]
    pub sections: Vec<serde_json::Value>,
    /// Total bullet count across all sections.
    #[serde(default)]
    pub total_bullets: usize,
    /// Source collection names referenced.
    #[serde(default)]
    pub sources: Vec<String>,
}

/// Request for `render_llm_prompt` (`POST /discovery/render_llm_prompt`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenderPromptRequest {
    /// The answer plan to render.
    pub plan: AnswerPlan,
}

/// Response from `render_llm_prompt`.
/// Server: `{prompt, length, estimated_tokens}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmPrompt {
    /// The rendered prompt string.
    pub prompt: String,
    /// Byte length of the prompt.
    #[serde(default)]
    pub length: usize,
    /// Rough token estimate (length / 4).
    #[serde(default)]
    pub estimated_tokens: usize,
}

// ===== ADMIN / OBSERVABILITY TYPES (phase12) =====

/// Server statistics returned by `GET /stats`.
///
/// Server: `{collections, total_vectors, uptime_seconds, version,
/// default_quantization, compression_ratio}`. The last two are
/// phase25 §5 additions and default to `("none", 1.0)` on older
/// servers that do not emit them.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Stats {
    /// Number of collections.
    #[serde(default)]
    pub collections: usize,
    /// Total vectors across all collections.
    #[serde(default)]
    pub total_vectors: usize,
    /// Server uptime in seconds.
    #[serde(default)]
    pub uptime_seconds: u64,
    /// Server version string.
    #[serde(default)]
    pub version: String,
    /// Most-common quantization label across active collections
    /// (`none`, `binary`, `sq-4bit`, `sq-8bit`, `sq-16bit`, `sq`, or
    /// `pq`). `none` when the store is empty or the server is older
    /// than phase25 §5.
    #[serde(default = "default_quantization_label")]
    pub default_quantization: String,
    /// Mean compression ratio (uncompressed_bytes / compressed_bytes)
    /// across the collections sharing `default_quantization`. `1.0`
    /// when no collections are present or on older servers.
    #[serde(default = "default_compression_ratio")]
    pub compression_ratio: f32,
}

fn default_quantization_label() -> String {
    "none".to_string()
}

fn default_compression_ratio() -> f32 {
    1.0
}

/// Runtime metrics snapshot returned by `GET /metrics/runtime`
/// (phase25). Single JSON object refreshed once per second on the
/// server. Every field defaults so the SDK tolerates older servers
/// that do not emit the route.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RuntimeMetrics {
    /// CPU usage of the server process, 0–100 %.
    #[serde(default)]
    pub cpu_percent: f64,
    /// Resident-set size of the server process in bytes.
    #[serde(default)]
    pub memory_rss_bytes: u64,
    /// Total physical memory of the host in bytes.
    #[serde(default)]
    pub memory_total_bytes: u64,
    /// RSS as a fraction of total memory, 0–100 %.
    #[serde(default)]
    pub memory_percent: f64,
    /// Active HTTP connections at the moment of sampling.
    #[serde(default)]
    pub active_connections: usize,
    /// Seconds since the server process started.
    #[serde(default)]
    pub uptime_seconds: u64,
    /// Rolling 60-second queries-per-second across all routes.
    #[serde(default)]
    pub qps_window_60s: f64,
    /// Fraction of requests in the last 60 s with HTTP 5xx status,
    /// 0–1.
    #[serde(default)]
    pub error_rate_5xx_60s: f64,
    /// Per-route latency / throughput. Sorted descending by QPS.
    #[serde(default)]
    pub throughput_by_route: Vec<RouteStats>,
    /// WAL state. Zero-initialised on standalone servers without
    /// replication.
    #[serde(default)]
    pub wal: WalSnapshot,
}

/// Per-route latency + QPS line in `RuntimeMetrics.throughput_by_route`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RouteStats {
    /// Route path (raw URI; templated routes are normalised by the server).
    #[serde(default)]
    pub route: String,
    /// Queries per second for this route over the last 60 s.
    #[serde(default)]
    pub qps: f64,
    /// 50th-percentile latency in milliseconds.
    #[serde(default)]
    pub p50_ms: f64,
    /// 99th-percentile latency in milliseconds.
    #[serde(default)]
    pub p99_ms: f64,
}

/// WAL state surfaced inside `RuntimeMetrics.wal` (phase25 §3).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WalSnapshot {
    /// Latest offset appended to the WAL.
    #[serde(default)]
    pub current_seq: u64,
    /// On-disk WAL file size in bytes (0 in memory-only mode).
    #[serde(default)]
    pub size_bytes: u64,
    /// Unix timestamp (seconds) at which `last_checkpoint_seq` last
    /// advanced. 0 when no replica has confirmed an offset.
    #[serde(default)]
    pub last_checkpoint_at: u64,
    /// Lowest offset that has been confirmed by all replicas.
    #[serde(default)]
    pub last_checkpoint_seq: u64,
}

/// Server status returned by `GET /status`.
/// Server: `{online, version, uptime_seconds, collections_count}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerStatus {
    /// Whether the server is online.
    #[serde(default)]
    pub online: bool,
    /// Version string.
    #[serde(default)]
    pub version: String,
    /// Uptime in seconds.
    #[serde(default)]
    pub uptime_seconds: u64,
    /// Number of collections.
    #[serde(default)]
    pub collections_count: usize,
}

/// Query parameters for `get_logs` (`GET /logs`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LogsQuery {
    /// Number of log lines to return (default 100).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lines: Option<usize>,
    /// Optional level filter (`INFO`, `WARN`, `ERROR`, `DEBUG`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub level: Option<String>,
}

/// One log entry returned by `GET /logs`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    /// ISO-8601 timestamp.
    #[serde(default)]
    pub timestamp: String,
    /// Log level.
    #[serde(default)]
    pub level: String,
    /// Log message.
    #[serde(default)]
    pub message: String,
    /// Source component.
    #[serde(default)]
    pub source: String,
}

/// Report returned by `cleanup_empty_collections` (`DELETE /collections/cleanup`).
///
/// The server shape is inferred; the handler returns a free-form JSON
/// `Value` so we use `serde_json::Value` fields with defaults.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CleanupReport {
    /// Whether the cleanup succeeded.
    #[serde(default)]
    pub success: bool,
    /// Number of collections removed.
    #[serde(default)]
    pub removed: usize,
    /// Names of the removed collections.
    #[serde(default)]
    pub collections: Vec<String>,
    /// Any message from the server.
    #[serde(default)]
    pub message: Option<String>,
}

/// Server configuration snapshot returned by `GET /config` and `POST /config`.
///
/// The config is a free-form YAML object loaded from `config.yml`; the
/// SDK surfaces it as `serde_json::Value` to avoid coupling to the
/// server's internal `Config` struct. Wrap in a newtype for ergonomics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigSnapshot(pub serde_json::Value);

/// Patch applied to the server configuration by `POST /config`.
/// The server accepts the full config as a JSON object and writes it to
/// `config.yml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigPatch(pub serde_json::Value);

/// Metadata for one server-side backup file returned by `GET /backups`.
/// Server shape: `{id, name, date, size, collections}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupInfo {
    /// UUID of the backup.
    pub id: String,
    /// Human-readable name.
    pub name: String,
    /// Creation timestamp (RFC3339).
    pub date: String,
    /// File size in bytes (estimate).
    #[serde(default)]
    pub size: u64,
    /// Collection names included in the backup.
    #[serde(default)]
    pub collections: Vec<String>,
}

/// Request body for `create_backup` (`POST /backups/create`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateBackupRequest {
    /// Backup name.
    pub name: String,
    /// Collection names to include (empty = all).
    #[serde(default)]
    pub collections: Vec<String>,
}

/// Request body for `restore_backup` (`POST /backups/restore`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestoreBackupRequest {
    /// ID of the backup to restore.
    pub backup_id: String,
}

/// Workspace config entry returned by `GET /workspace/config` and
/// `GET /workspace/list`.
///
/// The config is a free-form YAML object; surfaced as `serde_json::Value`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceConfig(pub serde_json::Value);

/// Request body for `add_workspace` (`POST /workspace/add`).
/// Server reads `path` and `collection_name`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddWorkspaceRequest {
    /// File-system path to watch.
    pub path: String,
    /// Collection name to index files into.
    pub collection_name: String,
}

// ===== AUTH TYPES (phase12) =====

/// User record returned by auth endpoints.
/// Server shape: `{user_id, username, roles}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    /// Opaque user identifier.
    pub user_id: String,
    /// Username string.
    pub username: String,
    /// Role names.
    #[serde(default)]
    pub roles: Vec<String>,
}

/// JWT token returned by `POST /auth/refresh`.
/// Server shape: `{access_token, token_type, expires_in}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtToken {
    /// Bearer access token.
    pub access_token: String,
    /// Token type (always `"Bearer"`).
    pub token_type: String,
    /// Lifetime in seconds.
    pub expires_in: u64,
}

/// Password policy report returned by `POST /auth/validate-password`.
/// Server shape: `{valid, errors, strength, strength_label}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasswordPolicyReport {
    /// Whether the password satisfies all policy rules.
    pub valid: bool,
    /// Validation errors (empty when valid).
    #[serde(default)]
    pub errors: Vec<String>,
    /// Strength score 0–100.
    #[serde(default)]
    pub strength: u8,
    /// Human-readable strength label.
    #[serde(default)]
    pub strength_label: String,
}

/// Request body for `create_api_key` (`POST /auth/keys`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateApiKeyRequest {
    /// Key name / description.
    pub name: String,
    /// Permissions (optional; defaults to Read).
    #[serde(default)]
    pub permissions: Vec<String>,
    /// TTL in seconds from now (None = never expires).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in: Option<u64>,
}

/// API key returned by `POST /auth/keys`.
///
/// The actual key string is only returned once at creation time.
/// `GET /auth/keys` returns entries with `api_key` omitted.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKey {
    /// Key UUID.
    pub id: String,
    /// Key name.
    pub name: String,
    /// Permissions.
    #[serde(default)]
    pub permissions: Vec<String>,
    /// The raw API key value (only present at creation time).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Creation timestamp (Unix epoch seconds).
    #[serde(default)]
    pub created_at: u64,
    /// Last-used timestamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_used: Option<u64>,
    /// Expiry timestamp (None = never expires).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
    /// Whether the key is currently active.
    #[serde(default)]
    pub active: bool,
    /// One-time warning message (present at creation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
    /// Total successful credential validations recorded against this
    /// key. Defaults to 0 for keys that have never been used (or for
    /// servers that don't yet emit the field).
    #[serde(default)]
    pub usage_count: u64,
}

/// Per-collection scope attached to an API key.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApiKeyScope {
    /// Collection this scope applies to.
    pub collection: String,
    /// Permissions granted on that collection.
    #[serde(default)]
    pub permissions: Vec<String>,
}

/// Request body for `PUT /auth/keys/{id}/permissions`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateApiKeyPermissionsRequest {
    /// New permission list. Server rejects an empty list with 400.
    pub permissions: Vec<String>,
    /// `None` leaves existing scopes untouched. `Some(vec![])` clears
    /// scopes (default-deny on scope-aware routes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<ApiKeyScope>>,
}

/// Flattened key view returned by `update_api_key_permissions` and
/// `get_api_key_usage`. Mirrors the server's `ApiKeyView`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyView {
    pub id: String,
    pub name: String,
    pub user_id: String,
    #[serde(default)]
    pub permissions: Vec<String>,
    #[serde(default)]
    pub scopes: Vec<ApiKeyScope>,
    pub created_at: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_used: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
    #[serde(default)]
    pub active: bool,
    #[serde(default)]
    pub usage_count: u64,
}

/// One day's usage bucket from `GET /auth/keys/{id}/usage`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApiKeyUsageBucket {
    /// ISO-8601 date (UTC), e.g. `"2026-05-03"`.
    pub date: String,
    /// Successful validations recorded for that day.
    pub count: u64,
}

/// Response body for `GET /auth/keys/{id}/usage`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyUsageReport {
    /// Live key view with up-to-date `usage_count`.
    pub key: ApiKeyView,
    /// Daily counter buckets, oldest first. Days with zero validations
    /// are still present so the caller can render a continuous
    /// sparkline without gap-fill logic.
    pub buckets: Vec<ApiKeyUsageBucket>,
    /// Sum of `buckets[*].count`.
    pub window_total: u64,
}

/// Request body for `create_user` (`POST /auth/users`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserRequest {
    /// Username.
    pub username: String,
    /// Initial password.
    pub password: String,
    /// Roles to assign (optional; defaults to `["User"]`).
    #[serde(default)]
    pub roles: Vec<String>,
}

// ===== REPLICATION SDK TYPES (phase12) =====

/// Replication status returned by `GET /replication/status`.
/// Server: `{role, enabled, stats?, replicas?}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationStatus {
    /// Node role (`"Master"`, `"Replica"`, or `"Standalone"`).
    pub role: String,
    /// Whether replication is enabled on this node.
    pub enabled: bool,
    /// Replication stats (master or replica depending on role).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stats: Option<ReplicationStats>,
    /// Connected replicas (master only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replicas: Option<Vec<ReplicaInfo>>,
}

/// Request body for `configure_replication` (`POST /replication/configure`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplicationConfig {
    /// Target role: `"master"`, `"replica"`, or `"standalone"`.
    pub role: String,
    /// Bind address for master nodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bind_address: Option<String>,
    /// Master address for replica nodes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub master_address: Option<String>,
    /// Heartbeat interval in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub heartbeat_interval: Option<u64>,
    /// Replication log size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_size: Option<usize>,
}

// ===== HUB TYPES (phase12) =====

/// A user-scoped backup entry returned by `GET /hub/backups`.
/// Mirrors `vectorizer::hub::backup::UserBackupInfo`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserBackup {
    /// Backup UUID.
    pub id: String,
    /// User UUID (owner).
    pub user_id: String,
    /// Human-readable backup name.
    pub name: String,
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Collections included.
    #[serde(default)]
    pub collections: Vec<String>,
    /// Creation timestamp (RFC3339).
    pub created_at: String,
    /// Backup size in bytes.
    #[serde(default)]
    pub size: u64,
    /// Status string (`"active"`, `"creating"`, etc.).
    #[serde(default)]
    pub status: String,
}

/// Request for `create_user_backup` (`POST /hub/backups`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserBackupRequest {
    /// User UUID who owns the backup.
    pub user_id: String,
    /// Backup name.
    pub name: String,
    /// Optional description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Collections to include (None = all user collections).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collections: Option<Vec<String>>,
}

/// Request for `restore_user_backup` (`POST /hub/backups/restore`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestoreUserBackupRequest {
    /// User UUID.
    pub user_id: String,
    /// Backup UUID to restore.
    pub backup_id: String,
    /// Whether to overwrite existing collections.
    #[serde(default)]
    pub overwrite: bool,
}

/// Request for `upload_user_backup` (`POST /hub/backups/upload`).
///
/// The server actually accepts raw bytes via query params; the SDK
/// wraps the upload parameters here. The actual byte payload is passed
/// separately by the method.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadUserBackupRequest {
    /// User UUID.
    pub user_id: String,
    /// Optional backup name override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Binary backup data.
    #[serde(skip)]
    pub data: Vec<u8>,
}

/// Usage statistics returned by `GET /hub/usage/statistics`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageStatistics {
    /// Whether the call succeeded.
    #[serde(default)]
    pub success: bool,
    /// Human-readable message.
    #[serde(default)]
    pub message: String,
    /// The statistics payload (free-form per server).
    #[serde(default)]
    pub stats: Option<serde_json::Value>,
}

/// Quota information returned by `GET /hub/usage/quota`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuotaInfo {
    /// Whether the call succeeded.
    #[serde(default)]
    pub success: bool,
    /// Human-readable message.
    #[serde(default)]
    pub message: String,
    /// The quota payload (free-form per server).
    #[serde(default)]
    pub quota: Option<serde_json::Value>,
}

// ===== SCHEMA-EVOLUTION + OBSERVABILITY TYPES (phase14) =====

/// Parameters for `reindex_collection` (`POST /collections/{name}/reindex`).
///
/// All fields carry defaults matching the server handler: `m=16`,
/// `ef_construction=200`, `ef_search=100`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReindexParams {
    /// HNSW `M` parameter (number of bi-directional links).
    pub m: u32,
    /// HNSW `ef_construction` (size of the dynamic candidate list during build).
    pub ef_construction: u32,
    /// HNSW `ef_search` (size of the dynamic candidate list at query time).
    pub ef_search: u32,
}

/// Job descriptor returned by `reindex_collection`
/// (`POST /collections/{name}/reindex`).
///
/// Server contract: `{job_id, collection, state, params, progress}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReindexJob {
    /// Opaque job id generated by the server.
    pub job_id: String,
    /// Collection that was re-indexed.
    pub collection: String,
    /// Job state string (`"completed"` on success).
    pub state: String,
    /// HNSW parameters that were applied.
    pub params: serde_json::Value,
    /// Progress fraction in `[0.0, 1.0]`.
    pub progress: f64,
}

/// Native snapshot metadata returned by `create_native_snapshot` and
/// each entry in `list_native_snapshots`.
///
/// Server contract: `{id, collection, created_at, size_bytes}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NativeSnapshotInfo {
    /// Opaque snapshot id (UUID string).
    pub id: String,
    /// Collection the snapshot was taken from.
    pub collection: String,
    /// Creation timestamp in RFC-3339 format.
    pub created_at: String,
    /// Compressed snapshot size in bytes.
    pub size_bytes: u64,
}

/// Request body for `explain_search`
/// (`POST /collections/{name}/explain`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplainRequest {
    /// Query vector (must match the collection's dimension).
    pub vector: Vec<f32>,
    /// Number of nearest neighbours to retrieve (default 10).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub k: Option<u64>,
}

/// Execution trace attached to an `ExplainResponse`.
///
/// Server contract: `{visited_nodes, ef_search, hnsw_search_ms,
/// payload_filter_evals, quantization_score_ms, total_ms}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExplainTrace {
    /// Number of HNSW graph nodes visited during the search.
    pub visited_nodes: usize,
    /// Effective `ef_search` value used.
    pub ef_search: usize,
    /// Wall-clock time spent inside HNSW traversal (milliseconds).
    pub hnsw_search_ms: f64,
    /// Number of payload-filter predicate evaluations.
    pub payload_filter_evals: usize,
    /// Wall-clock time spent on quantized distance scoring (milliseconds).
    pub quantization_score_ms: f64,
    /// Total wall-clock time for the explain call (milliseconds).
    pub total_ms: f64,
}

/// Response from `explain_search`
/// (`POST /collections/{name}/explain`).
///
/// Server contract: `{collection, k, results, trace}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplainResponse {
    /// Collection the search ran against.
    pub collection: String,
    /// Number of neighbours requested.
    pub k: usize,
    /// Ranked search hits (same shape as regular search results).
    #[serde(default)]
    pub results: Vec<serde_json::Value>,
    /// Full execution trace.
    pub trace: ExplainTrace,
}

/// One entry in the slow-query ring buffer returned by `GET /slow_queries`.
///
/// Server contract: `{timestamp, collection, k, duration_ms}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SlowQueryEntry {
    /// ISO-8601 / RFC-3339 timestamp when the slow query was recorded.
    pub timestamp: String,
    /// Collection the query ran against.
    pub collection: String,
    /// Number of neighbours requested (`k`).
    pub k: usize,
    /// Observed query duration in milliseconds.
    pub duration_ms: f64,
}

/// Slow-query ring-buffer configuration returned by
/// `POST /slow_queries/config`.
///
/// Server contract: `{threshold_ms, capacity, status}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SlowQueryConfig {
    /// Minimum duration (ms) for a query to be recorded.
    pub threshold_ms: u64,
    /// Maximum number of entries retained in the ring buffer.
    pub capacity: usize,
}

/// Validation result returned by `POST /hub/validate-key`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HubApiKeyValidation {
    /// Whether the key is valid.
    pub valid: bool,
    /// Tenant id the key belongs to.
    #[serde(default)]
    pub tenant_id: String,
    /// Tenant name.
    #[serde(default)]
    pub tenant_name: String,
    /// Permissions granted by the key.
    #[serde(default)]
    pub permissions: Vec<String>,
    /// Validation timestamp (RFC3339).
    #[serde(default)]
    pub validated_at: String,
}

// ===== CLUSTER + AUTH ADMIN TYPES (phase15) =====

/// Report returned by `POST /cluster/failover`.
///
/// Server contract: `{promoted_replica_id, master_offset_at_promotion,
/// replica_offset_at_promotion, residual_lag_operations}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FailoverReport {
    /// ID of the replica that was promoted to primary.
    pub promoted_replica_id: String,
    /// Master WAL offset at the time of promotion.
    pub master_offset_at_promotion: u64,
    /// Replica's confirmed offset at the time of promotion.
    pub replica_offset_at_promotion: u64,
    /// Remaining lag in WAL operations.
    pub residual_lag_operations: u64,
}

/// Report returned by `POST /cluster/replicas/{id}/resync`.
///
/// Server contract: `{replica_id, snapshot_offset, full_snapshot}`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResyncJob {
    /// ID of the replica being resynced.
    pub replica_id: String,
    /// Master WAL offset used as the snapshot baseline.
    pub snapshot_offset: u64,
    /// Whether a full snapshot transfer was initiated.
    pub full_snapshot: bool,
}

/// Information about a newly added cluster peer.
///
/// Returned by `POST /cluster/peers`.
/// Server contract: `{node_id, address, role}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerInfo {
    /// Opaque node id assigned by the server.
    pub node_id: String,
    /// Address of the peer (host:port).
    pub address: String,
    /// Role string: `"member"` or `"observer"`.
    pub role: String,
}

/// Request body for `POST /cluster/peers`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddPeerRequest {
    /// Address of the new peer (host:port).
    pub address: String,
    /// Role: `"member"` (default) or `"observer"`.
    #[serde(default)]
    pub role: String,
}

/// Job descriptor returned by `POST /cluster/rebalance`.
///
/// Server contract: `{job_id, status, shards_to_move, shards_moved,
/// last_checkpoint_node, message}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RebalanceJob {
    /// Opaque job id.
    pub job_id: String,
    /// Lifecycle state: `"running"`, `"paused"`, `"completed"`, `"failed"`.
    pub status: String,
    /// Total shards that need to move.
    pub shards_to_move: usize,
    /// Shards moved so far.
    pub shards_moved: usize,
    /// Node-id of the last checkpoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_checkpoint_node: Option<String>,
    /// Human-readable status message.
    pub message: String,
}

/// Response from `POST /auth/keys/{id}/rotate`.
///
/// Server contract: `{old_key_id, new_key_id, new_token, grace_until}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RotatedKey {
    /// The old key id (still valid until `grace_until`).
    pub old_key_id: String,
    /// The new key id.
    pub new_key_id: String,
    /// The new key token value — store it securely.
    pub new_token: String,
    /// Unix timestamp until which the OLD key is still accepted.
    pub grace_until: u64,
}

/// Request body for `POST /auth/keys` — extended with optional per-collection scopes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateScopedApiKeyRequest {
    /// Key name / description.
    pub name: String,
    /// Global permissions (optional; defaults to `["Read"]`).
    #[serde(default)]
    pub permissions: Vec<String>,
    /// TTL in seconds from now (`None` = never expires).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in: Option<u64>,
    /// Per-collection scopes. Empty = default-deny on scope-enforced routes.
    #[serde(default)]
    pub scopes: Vec<TokenScope>,
}

/// Per-collection permission scope sent in [`CreateScopedApiKeyRequest`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenScope {
    /// Collection name this scope applies to.
    pub collection: String,
    /// Permissions granted on that collection (e.g. `["read", "write"]`).
    #[serde(default)]
    pub permissions: Vec<String>,
}

/// RFC 7662 token introspection response from `POST /auth/introspect`.
///
/// Server contract: `{active, scope?, sub?, exp?, username?}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenIntrospection {
    /// Whether the token is currently active.
    pub active: bool,
    /// Space-separated scope string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Subject (user_id or key_id).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sub: Option<String>,
    /// Expiry (Unix timestamp).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exp: Option<u64>,
    /// Username (non-standard extension; omitted for inactive tokens).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
}

/// One entry in the admin audit log returned by `GET /auth/audit`.
///
/// Server contract: `{actor, action, target, at, correlation_id}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Username or key-id of the actor.
    pub actor: String,
    /// Canonical action name, e.g. `"create_api_key"`.
    pub action: String,
    /// Target resource.
    pub target: String,
    /// UTC timestamp (RFC-3339).
    pub at: String,
    /// Correlation-ID propagated from the request middleware.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,
}

/// Query parameters for `GET /auth/audit`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AuditQuery {
    /// Filter by actor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// Filter by action name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
    /// Entries at or after this RFC-3339 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub since: Option<String>,
    /// Entries at or before this RFC-3339 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub until: Option<String>,
    /// Maximum entries to return (server default 200).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}