mockserver-client 7.4.0

An idiomatic Rust client for MockServer's control-plane API
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
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
//! The MockServer client and its builder.

use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use reqwest::blocking::Client;
use serde::Serialize;
use serde_json::Value;

/// Characters percent-encoded when interpolating a scenario name into a path
/// segment — everything unsafe for a single segment (matches the other clients'
/// path-escaping). Unreserved characters (`-` `_` `.` `~`) are left intact.
const SCENARIO_NAME: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'/')
    .add(b'?')
    .add(b'#')
    .add(b'%')
    .add(b'[')
    .add(b']')
    .add(b'{')
    .add(b'}')
    .add(b'|')
    .add(b'\\')
    .add(b'^')
    .add(b'"')
    .add(b'<')
    .add(b'>')
    .add(b'`');

/// Build the control-plane path for a named scenario with the name
/// percent-encoded as a single path segment (matching the other MockServer clients).
fn scenario_path(name: &str) -> String {
    format!(
        "/mockserver/scenario/{}",
        utf8_percent_encode(name, SCENARIO_NAME)
    )
}

use crate::breakpoint::{
    BreakpointMatcherList, BreakpointMatcherRegistration, BreakpointMatcherResponse,
    BreakpointRequestHandler, BreakpointResponseHandler, BreakpointStreamFrameHandler,
    BreakpointWebSocketClient,
};
use crate::error::{Error, Result};
use crate::model::*;

// ---------------------------------------------------------------------------
// ClientBuilder
// ---------------------------------------------------------------------------

/// Builder for constructing a [`MockServerClient`].
///
/// # Example
/// ```no_run
/// use mockserver_client::ClientBuilder;
///
/// let client = ClientBuilder::new("localhost", 1080)
///     .context_path("/api")
///     .secure(true)
///     .build()
///     .unwrap();
/// ```
pub struct ClientBuilder {
    host: String,
    port: u16,
    context_path: String,
    secure: bool,
    tls_verify: bool,
    control_plane_bearer_token: Option<String>,
    ca_cert_pem: Option<Vec<u8>>,
    /// Client identity for mTLS as `(certificate PEM, private key PEM)`.
    client_identity_pem: Option<(Vec<u8>, Vec<u8>)>,
}

impl ClientBuilder {
    /// Create a new builder targeting the given host and port.
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
            context_path: String::new(),
            secure: false,
            tls_verify: true,
            control_plane_bearer_token: None,
            ca_cert_pem: None,
            client_identity_pem: None,
        }
    }

    /// Set a context path prefix (e.g., "/mockserver" if deployed behind a reverse proxy).
    pub fn context_path(mut self, path: impl Into<String>) -> Self {
        self.context_path = path.into();
        self
    }

    /// Use HTTPS instead of HTTP.
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = secure;
        self
    }

    /// Whether to verify TLS certificates (default: true).
    pub fn tls_verify(mut self, verify: bool) -> Self {
        self.tls_verify = verify;
        self
    }

    /// Attach an `Authorization: Bearer <token>` header to **every control-plane
    /// request** the built client sends.
    ///
    /// Use this when the server requires a JWT on the control plane
    /// (`mockserver.controlPlaneJWTAuthenticationRequired=true`). The client does
    /// not generate the token — supply the JWT string here. The header is only
    /// sent on control-plane (`/mockserver/*`) requests issued by this client; it
    /// is not added to any proxied/data-plane traffic.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::ClientBuilder;
    ///
    /// let client = ClientBuilder::new("localhost", 1080)
    ///     .secure(true)
    ///     .control_plane_bearer_token("eyJhbGciOi...")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn control_plane_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.control_plane_bearer_token = Some(token.into());
        self
    }

    /// Trust the given CA certificate (PEM file path) when connecting over HTTPS.
    ///
    /// Reads the PEM file and adds it as an additional trusted root so a
    /// MockServer HTTPS certificate issued by that CA validates. Compose with
    /// [`secure(true)`](Self::secure). The CA is added to — not a replacement for
    /// — the platform's default trust store.
    ///
    /// Errors from reading the file surface when [`build`](Self::build) is called.
    pub fn ca_cert_pem_path(mut self, path: impl AsRef<std::path::Path>) -> Self {
        self.ca_cert_pem = std::fs::read(path.as_ref()).ok();
        // Defer error reporting to build(); but if the read failed we still want
        // build() to fail loudly rather than silently ignore the CA, so record a
        // sentinel empty Vec which Certificate::from_pem will reject.
        if self.ca_cert_pem.is_none() {
            self.ca_cert_pem = Some(Vec::new());
        }
        self
    }

    /// Trust the given CA certificate (PEM bytes) when connecting over HTTPS.
    ///
    /// In-memory counterpart to [`ca_cert_pem_path`](Self::ca_cert_pem_path).
    pub fn ca_cert_pem(mut self, bytes: impl Into<Vec<u8>>) -> Self {
        self.ca_cert_pem = Some(bytes.into());
        self
    }

    /// Present a client certificate + private key (PEM) for mutual TLS (mTLS).
    ///
    /// Reads the certificate and PKCS#8 private key PEM files and configures them
    /// as the client identity used in the TLS handshake — required when the
    /// server enforces `mockserver.controlPlaneTLSMutualAuthenticationRequired`.
    ///
    /// Errors from reading either file, or from building the identity, surface
    /// when [`build`](Self::build) is called.
    pub fn client_cert_pem(
        mut self,
        cert_path: impl AsRef<std::path::Path>,
        key_path: impl AsRef<std::path::Path>,
    ) -> Self {
        match (
            std::fs::read(cert_path.as_ref()),
            std::fs::read(key_path.as_ref()),
        ) {
            (Ok(cert), Ok(key)) => self.client_identity_pem = Some((cert, key)),
            // Record a sentinel empty buffer so build() fails loudly rather than
            // silently dropping the requested client certificate.
            _ => self.client_identity_pem = Some((Vec::new(), Vec::new())),
        }
        self
    }

    /// Build the client.
    pub fn build(self) -> Result<MockServerClient> {
        let scheme = if self.secure { "https" } else { "http" };
        let ctx = if self.context_path.is_empty() {
            String::new()
        } else if self.context_path.starts_with('/') {
            self.context_path
        } else {
            format!("/{}", self.context_path)
        };
        let base_url = format!("{scheme}://{}:{}{ctx}", self.host, self.port);

        let mut builder = Client::builder().danger_accept_invalid_certs(!self.tls_verify);

        // Attach the control-plane bearer token as a default header so it rides
        // on every control-plane request this client issues (this client only
        // ever talks to the `/mockserver/*` control plane).
        if let Some(token) = self.control_plane_bearer_token {
            let mut headers = reqwest::header::HeaderMap::new();
            let mut value = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
                .map_err(|e| Error::InvalidRequest(format!("invalid bearer token: {e}")))?;
            value.set_sensitive(true);
            headers.insert(reqwest::header::AUTHORIZATION, value);
            builder = builder.default_headers(headers);
        }

        if let Some(ca) = self.ca_cert_pem {
            let cert = reqwest::Certificate::from_pem(&ca)?;
            builder = builder.add_root_certificate(cert);
        }

        if let Some((cert_pem, key_pem)) = self.client_identity_pem {
            let identity = reqwest::Identity::from_pkcs8_pem(&cert_pem, &key_pem)?;
            builder = builder.identity(identity);
        }

        let http_client = builder.build()?;

        Ok(MockServerClient {
            base_url,
            http: http_client,
            breakpoint_ws: std::sync::Mutex::new(None),
        })
    }
}

// ---------------------------------------------------------------------------
// MockServerClient
// ---------------------------------------------------------------------------

/// A blocking client for the MockServer control-plane REST API.
///
/// Created via [`ClientBuilder`]. All methods are synchronous.
pub struct MockServerClient {
    pub(crate) base_url: String,
    http: Client,
    breakpoint_ws: std::sync::Mutex<Option<BreakpointWebSocketClient>>,
}

impl MockServerClient {
    // ------------------------------------------------------------------
    // Expectation creation
    // ------------------------------------------------------------------

    /// Create one or more expectations on the server.
    ///
    /// Returns the created expectations as echoed by the server.
    pub fn upsert(&self, expectations: &[Expectation]) -> Result<Vec<Expectation>> {
        let body = serde_json::to_value(expectations)?;
        let resp = self
            .http
            .put(self.url("/mockserver/expectation"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(expectations.to_vec())
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Create one or more expectations from raw JSON values.
    ///
    /// This is the lower-level counterpart to [`upsert`](Self::upsert) for
    /// expectation shapes that the typed [`Expectation`] model does not (yet)
    /// cover — notably the `httpLlmResponse` action and conversation scenario
    /// fields produced by the [`crate::llm`] builders, and the Velocity/JSON-RPC
    /// expectations produced by the [`crate::mcp`] builder.
    ///
    /// The `expectations` value should be a JSON object (single expectation) or
    /// a JSON array of expectation objects. Returns the raw JSON the server
    /// echoes back (or the submitted value if the server returns an empty body).
    pub fn upsert_raw(&self, expectations: Value) -> Result<Value> {
        let resp = self
            .http
            .put(self.url("/mockserver/expectation"))
            .json(&expectations)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(expectations)
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // OpenAPI import
    // ------------------------------------------------------------------

    /// Register expectations from an OpenAPI/Swagger specification.
    ///
    /// Sends a `PUT /mockserver/openapi` with the given [`OpenApiExpectation`].
    /// MockServer parses the spec and creates request matchers and example
    /// responses for the selected operations (or every operation when none are
    /// specified). Returns the created expectations as echoed by the server.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::{ClientBuilder, OpenApiExpectation};
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// client.openapi(
    ///     &OpenApiExpectation::new("https://example.com/petstore.yaml")
    ///         .operation("listPets", "200"),
    /// ).unwrap();
    /// ```
    pub fn openapi(&self, expectation: &OpenApiExpectation) -> Result<Vec<Expectation>> {
        let resp = self
            .http
            .put(self.url("/mockserver/openapi"))
            .json(expectation)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(vec![])
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Fluent API entry point
    // ------------------------------------------------------------------

    /// Begin building an expectation with the fluent `when(...).respond(...)` API.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// client.when(HttpRequest::new().method("GET").path("/foo"))
    ///     .respond(HttpResponse::new().status_code(200).body("bar"))
    ///     .unwrap();
    /// ```
    pub fn when(&self, request: HttpRequest) -> ForwardChainExpectation<'_> {
        ForwardChainExpectation {
            client: self,
            request,
            times: None,
            time_to_live: None,
            priority: None,
            id: None,
        }
    }

    // ------------------------------------------------------------------
    // Verify
    // ------------------------------------------------------------------

    /// Verify that a request was received the specified number of times.
    ///
    /// Returns `Ok(())` if verification passes, or
    /// `Err(Error::VerificationFailure)` with the server's failure message.
    pub fn verify(&self, request: HttpRequest, times: VerificationTimes) -> Result<()> {
        let verification = Verification {
            http_request: Some(request),
            http_response: None,
            times: Some(times),
            maximum_number_of_request_to_return_in_verification_failure: None,
        };
        self.do_verify(&verification)
    }

    /// Verify that a request/response pair was received the specified number of times.
    ///
    /// Both the request matcher and the response matcher must match for a
    /// recorded exchange to count. The response matcher uses the same
    /// [`HttpResponse`] type as expectations — the server matches against the
    /// recorded response's status code, headers, and body.
    pub fn verify_request_and_response(
        &self,
        request: HttpRequest,
        response: HttpResponse,
        times: VerificationTimes,
    ) -> Result<()> {
        let verification = Verification {
            http_request: Some(request),
            http_response: Some(response),
            times: Some(times),
            maximum_number_of_request_to_return_in_verification_failure: None,
        };
        self.do_verify(&verification)
    }

    /// Verify that a response (regardless of request) was returned the
    /// specified number of times.
    ///
    /// The `httpRequest` field is omitted from the JSON so the server matches
    /// any request.
    pub fn verify_response(&self, response: HttpResponse, times: VerificationTimes) -> Result<()> {
        let verification = Verification {
            http_request: None,
            http_response: Some(response),
            times: Some(times),
            maximum_number_of_request_to_return_in_verification_failure: None,
        };
        self.do_verify(&verification)
    }

    /// Verify that no requests at all were received by the server.
    ///
    /// Thin wrapper over [`verify`](Self::verify): matches any request (an empty
    /// matcher) with `exactly(0)` times. Returns `Ok(())` if the server received
    /// no requests, or `Err(Error::VerificationFailure)` otherwise.
    pub fn verify_zero_interactions(&self) -> Result<()> {
        self.verify(HttpRequest::new(), VerificationTimes::exactly(0))
    }

    /// Send a fully constructed [`Verification`] to the server.
    ///
    /// This is the most flexible form — callers can set every field,
    /// including `maximum_number_of_request_to_return_in_verification_failure`.
    pub fn verify_raw(&self, verification: &Verification) -> Result<()> {
        self.do_verify(verification)
    }

    /// Verify that requests were received in the given order.
    pub fn verify_sequence(&self, requests: Vec<HttpRequest>) -> Result<()> {
        let verification = VerificationSequence {
            http_requests: Some(requests),
            http_responses: None,
        };
        self.do_verify_sequence(&verification)
    }

    /// Verify that request/response pairs were received in the given order.
    ///
    /// `responses` is index-aligned with `requests` — each entry constrains
    /// the response that must have been returned for the corresponding request.
    pub fn verify_sequence_with_responses(
        &self,
        requests: Vec<HttpRequest>,
        responses: Vec<HttpResponse>,
    ) -> Result<()> {
        let verification = VerificationSequence {
            http_requests: Some(requests),
            http_responses: Some(responses),
        };
        self.do_verify_sequence(&verification)
    }

    /// Send a fully constructed [`VerificationSequence`] to the server.
    pub fn verify_sequence_raw(&self, verification: &VerificationSequence) -> Result<()> {
        self.do_verify_sequence(verification)
    }

    // ------------------------------------------------------------------
    // Clear / Reset
    // ------------------------------------------------------------------

    /// Clear expectations and/or logs matching the given request.
    ///
    /// If `request` is `None`, clears everything of the specified type.
    pub fn clear(
        &self,
        request: Option<&HttpRequest>,
        clear_type: Option<ClearType>,
    ) -> Result<()> {
        let mut url = self.url("/mockserver/clear");
        if let Some(ct) = clear_type {
            url = format!("{url}?type={}", ct.as_str());
        }

        let mut builder = self.http.put(&url);
        builder = builder.header("Content-Type", "application/json");
        if let Some(req) = request {
            builder = builder.json(req);
        } else {
            builder = builder.body("");
        }

        let resp = builder.send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Clear expectations by expectation ID.
    pub fn clear_by_id(
        &self,
        expectation_id: impl Into<String>,
        clear_type: Option<ClearType>,
    ) -> Result<()> {
        let mut url = self.url("/mockserver/clear");
        if let Some(ct) = clear_type {
            url = format!("{url}?type={}", ct.as_str());
        }

        let body = serde_json::json!({ "id": expectation_id.into() });
        let resp = self.http.put(&url).json(&body).send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Reset all expectations and recorded requests.
    pub fn reset(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/reset"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Retrieve
    // ------------------------------------------------------------------

    /// Retrieve recorded requests matching the optional filter.
    pub fn retrieve_recorded_requests(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<HttpRequest>> {
        let text = self.do_retrieve(request, RetrieveType::Requests, RetrieveFormat::Json)?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve active expectations matching the optional filter.
    pub fn retrieve_active_expectations(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<Expectation>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::ActiveExpectations,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve recorded expectations matching the optional filter.
    pub fn retrieve_recorded_expectations(
        &self,
        request: Option<&HttpRequest>,
    ) -> Result<Vec<Expectation>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::RecordedExpectations,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    /// Retrieve the active expectations as MockServer SDK setup code (the
    /// builder code that recreates the expectations) in the requested language.
    ///
    /// `format` must be one of the code-generation variants of
    /// [`RetrieveFormat`] (e.g. [`RetrieveFormat::Java`],
    /// [`RetrieveFormat::Rust`]). The generated code is returned as a string.
    pub fn retrieve_expectations_as_code(
        &self,
        format: RetrieveFormat,
        request: Option<&HttpRequest>,
    ) -> Result<String> {
        self.do_retrieve(request, RetrieveType::ActiveExpectations, format)
    }

    /// Retrieve the recorded (proxied) request/response pairs as MockServer SDK
    /// setup code in the requested language.
    ///
    /// `format` must be one of the code-generation variants of
    /// [`RetrieveFormat`]. The generated code is returned as a string.
    pub fn retrieve_recorded_expectations_as_code(
        &self,
        format: RetrieveFormat,
        request: Option<&HttpRequest>,
    ) -> Result<String> {
        self.do_retrieve(request, RetrieveType::RecordedExpectations, format)
    }

    /// Retrieve log messages matching the optional filter.
    pub fn retrieve_log_messages(&self, request: Option<&HttpRequest>) -> Result<Vec<String>> {
        let text = self.do_retrieve(request, RetrieveType::Logs, RetrieveFormat::LogEntries)?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        // Log messages may be returned as a JSON array of strings or as a
        // separator-delimited block. Try JSON first.
        if let Ok(arr) = serde_json::from_str::<Vec<String>>(&text) {
            return Ok(arr);
        }
        // Fall back to splitting on the separator used by MockServer.
        Ok(text
            .split("------------------------------------\n")
            .map(|s| s.to_string())
            .filter(|s| !s.is_empty())
            .collect())
    }

    /// Retrieve recorded request/response pairs.
    pub fn retrieve_request_responses(&self, request: Option<&HttpRequest>) -> Result<Vec<Value>> {
        let text = self.do_retrieve(
            request,
            RetrieveType::RequestResponses,
            RetrieveFormat::Json,
        )?;
        if text.is_empty() {
            return Ok(vec![]);
        }
        Ok(serde_json::from_str(&text)?)
    }

    // ------------------------------------------------------------------
    // Status / Bind
    // ------------------------------------------------------------------

    /// Query the server's listening ports.
    pub fn status(&self) -> Result<Ports> {
        let resp = self
            .http
            .put(self.url("/mockserver/status"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Bind additional listening ports.
    pub fn bind(&self, ports: &[u16]) -> Result<Ports> {
        let body = Ports {
            ports: ports.to_vec(),
        };
        let resp = self
            .http
            .put(self.url("/mockserver/bind"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Check if the MockServer has started (polls with retries).
    pub fn has_started(&self, attempts: u32, timeout_ms: u64) -> bool {
        for i in 0..attempts {
            match self.status() {
                Ok(_) => return true,
                Err(_) => {
                    if i < attempts - 1 {
                        std::thread::sleep(std::time::Duration::from_millis(timeout_ms));
                    }
                }
            }
        }
        false
    }

    // ------------------------------------------------------------------
    // Breakpoints
    // ------------------------------------------------------------------

    /// Ensure the breakpoint WebSocket client is connected and return the clientId.
    /// If the existing connection's read loop has exited, it is replaced transparently.
    fn ensure_breakpoint_ws(&self) -> Result<String> {
        let mut guard = self.breakpoint_ws.lock().unwrap();
        let needs_connect = match guard.as_ref() {
            None => true,
            Some(ws) => ws.is_dead(),
        };
        if needs_connect {
            // Close the old dead connection if present
            if let Some(old) = guard.take() {
                old.close();
            }
            let ws = BreakpointWebSocketClient::connect(&self.base_url)?;
            *guard = Some(ws);
        }
        Ok(guard.as_ref().unwrap().client_id.clone())
    }

    /// Register a breakpoint matcher with the given phases and handlers.
    /// Returns the server-assigned breakpoint id.
    pub fn add_breakpoint(
        &self,
        matcher: HttpRequest,
        phases: &[&str],
        request_handler: Option<BreakpointRequestHandler>,
        response_handler: Option<BreakpointResponseHandler>,
        stream_frame_handler: Option<BreakpointStreamFrameHandler>,
    ) -> Result<String> {
        if phases.is_empty() {
            return Err(Error::InvalidRequest(
                "At least one phase is required".into(),
            ));
        }

        let client_id = self.ensure_breakpoint_ws()?;

        let reg = BreakpointMatcherRegistration {
            http_request: matcher,
            phases: phases.iter().map(|s| s.to_string()).collect(),
            client_id: Some(client_id),
        };

        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher"))
            .json(&reg)
            .send()?;

        let status = resp.status().as_u16();
        let text = resp.text()?;
        if status >= 400 {
            return Err(Error::UnexpectedStatus { status, body: text });
        }

        let result: BreakpointMatcherResponse = serde_json::from_str(&text)?;
        let id = result.id.clone();

        // Register handlers
        let guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.as_ref() {
            if let Some(h) = request_handler {
                ws.set_request_handler(&id, h);
            }
            if let Some(h) = response_handler {
                ws.set_response_handler(&id, h);
            }
            if let Some(h) = stream_frame_handler {
                ws.set_stream_frame_handler(&id, h);
            }
        }

        Ok(id)
    }

    /// Convenience: register a REQUEST-only breakpoint.
    pub fn add_request_breakpoint(
        &self,
        matcher: HttpRequest,
        handler: BreakpointRequestHandler,
    ) -> Result<String> {
        self.add_breakpoint(
            matcher,
            &[crate::breakpoint::phase::REQUEST],
            Some(handler),
            None,
            None,
        )
    }

    /// Convenience: register a REQUEST + RESPONSE breakpoint.
    pub fn add_request_response_breakpoint(
        &self,
        matcher: HttpRequest,
        request_handler: BreakpointRequestHandler,
        response_handler: BreakpointResponseHandler,
    ) -> Result<String> {
        self.add_breakpoint(
            matcher,
            &[
                crate::breakpoint::phase::REQUEST,
                crate::breakpoint::phase::RESPONSE,
            ],
            Some(request_handler),
            Some(response_handler),
            None,
        )
    }

    /// Convenience: register a streaming-phase breakpoint.
    pub fn add_stream_breakpoint(
        &self,
        matcher: HttpRequest,
        phases: &[&str],
        handler: BreakpointStreamFrameHandler,
    ) -> Result<String> {
        self.add_breakpoint(matcher, phases, None, None, Some(handler))
    }

    /// List all registered breakpoint matchers.
    pub fn list_breakpoint_matchers(&self) -> Result<BreakpointMatcherList> {
        let resp = self
            .http
            .get(self.url("/mockserver/breakpoint/matchers"))
            .send()?;

        let status = resp.status().as_u16();
        let text = resp.text()?;
        if status >= 400 {
            return Err(Error::UnexpectedStatus { status, body: text });
        }

        Ok(serde_json::from_str(&text)?)
    }

    /// Remove a breakpoint matcher by id.
    pub fn remove_breakpoint_matcher(&self, id: impl Into<String>) -> Result<()> {
        let id = id.into();
        let body = serde_json::json!({ "id": &id });
        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher/remove"))
            .json(&body)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let guard = self.breakpoint_ws.lock().unwrap();
                if let Some(ws) = guard.as_ref() {
                    ws.remove_handlers(&id);
                }
                Ok(())
            }
            404 => Err(Error::InvalidRequest(format!(
                "Breakpoint matcher not found: {id}"
            ))),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Remove all registered breakpoint matchers.
    pub fn clear_breakpoint_matchers(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/breakpoint/matcher/clear"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        if status >= 400 {
            return Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            });
        }

        let guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.as_ref() {
            ws.clear_handlers();
        }
        Ok(())
    }

    /// Close the breakpoint callback WebSocket connection.
    pub fn close_breakpoint_websocket(&self) {
        let mut guard = self.breakpoint_ws.lock().unwrap();
        if let Some(ws) = guard.take() {
            ws.close();
        }
    }

    // ------------------------------------------------------------------
    // Object (closure) callbacks
    // ------------------------------------------------------------------

    /// Register an expectation whose response is produced by a Rust closure
    /// invoked over the callback WebSocket (an `httpResponseObjectCallback`).
    ///
    /// When a request matches `matcher`, MockServer pushes it to this client over
    /// the shared callback WebSocket; `handler` receives the [`HttpRequest`] and
    /// returns the [`HttpResponse`] to send back. The closure runs on the client's
    /// background WebSocket-read thread, so it must be `Send + 'static`.
    ///
    /// The callback WebSocket is shared with breakpoints — only one socket is
    /// opened per client. There is a single object-response handler per client;
    /// calling this again replaces it. Narrow which requests reach the closure
    /// with the `matcher`.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// client.mock_with_callback(
    ///     HttpRequest::new().method("GET").path("/echo"),
    ///     |req| {
    ///         HttpResponse::new()
    ///             .status_code(200)
    ///             .body(format!("you asked for {}", req.path.unwrap_or_default()))
    ///     },
    /// ).unwrap();
    /// ```
    pub fn mock_with_callback<F>(
        &self,
        matcher: HttpRequest,
        handler: F,
    ) -> Result<Vec<Expectation>>
    where
        F: Fn(HttpRequest) -> HttpResponse + Send + 'static,
    {
        // Ensure the shared callback WebSocket is connected and learn its clientId.
        let client_id = self.ensure_breakpoint_ws()?;

        // Adapt the typed closure to the JSON-level ObjectResponseHandler the WS
        // read loop drives. The reply must echo the WebSocketCorrelationId header,
        // which route_object_callback re-applies after the closure returns.
        let object_handler: crate::breakpoint::ObjectResponseHandler =
            Box::new(move |request_json: Value| {
                let request: HttpRequest =
                    serde_json::from_value(request_json).unwrap_or_default();
                let response = handler(request);
                serde_json::to_value(&response).unwrap_or_else(|_| serde_json::json!({}))
            });

        {
            let guard = self.breakpoint_ws.lock().unwrap();
            if let Some(ws) = guard.as_ref() {
                ws.set_object_response_handler(object_handler);
            }
        }

        let expectation = Expectation::new(matcher)
            .respond_object_callback(HttpObjectCallback::new(client_id));
        self.upsert(&[expectation])
    }

    // ------------------------------------------------------------------
    // gRPC descriptor management
    // ------------------------------------------------------------------

    /// Upload a compiled protobuf descriptor set so gRPC requests can be matched.
    ///
    /// `descriptor` must be the raw bytes of a `FileDescriptorSet` (e.g. the
    /// output of `protoc --descriptor_set_out=... --include_imports`). The bytes
    /// are sent verbatim as `application/octet-stream` — they are **not**
    /// base64-encoded. Sends a `PUT /mockserver/grpc/descriptors`; the server
    /// responds `201 Created` on success.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::ClientBuilder;
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// let descriptor_set: Vec<u8> = std::fs::read("greeter.desc").unwrap();
    /// client.upload_grpc_descriptor(&descriptor_set).unwrap();
    /// ```
    pub fn upload_grpc_descriptor(&self, descriptor: &[u8]) -> Result<()> {
        if descriptor.is_empty() {
            return Err(Error::InvalidRequest(
                "descriptor set bytes must not be empty".into(),
            ));
        }
        let resp = self
            .http
            .put(self.url("/mockserver/grpc/descriptors"))
            .header("Content-Type", "application/octet-stream")
            .body(descriptor.to_vec())
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 201 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Retrieve the gRPC services registered from uploaded descriptor sets.
    ///
    /// Sends a `PUT /mockserver/grpc/services` and returns the parsed list of
    /// [`GrpcService`]s, each with its [`GrpcMethod`]s.
    pub fn retrieve_grpc_services(&self) -> Result<Vec<GrpcService>> {
        let resp = self
            .http
            .put(self.url("/mockserver/grpc/services"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(vec![])
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Clear all uploaded gRPC descriptor sets and registered services.
    ///
    /// Sends a `PUT /mockserver/grpc/clear`; the server responds `200 OK`.
    pub fn clear_grpc_descriptors(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/grpc/clear"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Stateful scenarios
    // ------------------------------------------------------------------

    /// Obtain a handle for inspecting and driving a named scenario state-machine.
    ///
    /// The returned [`Scenario`] borrows the client and issues control-plane
    /// requests against `/mockserver/scenario/{name}`.
    ///
    /// # Example
    /// ```no_run
    /// use mockserver_client::ClientBuilder;
    ///
    /// let client = ClientBuilder::new("localhost", 1080).build().unwrap();
    /// client.scenario("Deploy").set("Deploying").unwrap();
    /// client.scenario("Deploy").set_timed("Deploying", 5000, "Deployed").unwrap();
    /// client.scenario("Deploy").trigger("Failed").unwrap();
    /// let state = client.scenario("Deploy").state().unwrap();
    /// assert_eq!(state, "Failed");
    /// ```
    pub fn scenario(&self, name: &str) -> Scenario<'_> {
        Scenario {
            client: self,
            name: name.to_string(),
        }
    }

    /// List every known scenario and its current state.
    ///
    /// Sends a `GET /mockserver/scenario` and returns the parsed list of
    /// [`ScenarioState`]s.
    pub fn scenarios(&self) -> Result<Vec<ScenarioState>> {
        let resp = self.http.get(self.url("/mockserver/scenario")).send()?;
        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(vec![])
                } else {
                    let list: ScenarioList = serde_json::from_str(&text)?;
                    Ok(list.scenarios)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Get the current state of a named scenario.
    fn scenario_state(&self, name: &str) -> Result<String> {
        let resp = self
            .http
            .get(self.url(&scenario_path(name)))
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                let state: ScenarioState = serde_json::from_str(&text)?;
                Ok(state.current_state)
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Set a scenario's state, optionally scheduling a timed transition.
    fn scenario_set(
        &self,
        name: &str,
        state: &str,
        transition_after_ms: Option<u64>,
        next_state: Option<&str>,
    ) -> Result<()> {
        let mut body = serde_json::json!({ "state": state });
        if let Some(ms) = transition_after_ms {
            body["transitionAfterMs"] = serde_json::json!(ms);
        }
        if let Some(next) = next_state {
            body["nextState"] = serde_json::json!(next);
        }
        let resp = self
            .http
            .put(self.url(&scenario_path(name)))
            .json(&body)
            .send()?;
        self.scenario_ok(resp)
    }

    /// Externally trigger a scenario state transition.
    fn scenario_trigger(&self, name: &str, new_state: &str) -> Result<()> {
        let body = serde_json::json!({ "newState": new_state });
        let resp = self
            .http
            .put(self.url(&format!("{}/trigger", scenario_path(name))))
            .json(&body)
            .send()?;
        self.scenario_ok(resp)
    }

    /// Map a scenario REST response to `Ok(())` on `200`, surfacing the server's
    /// error body on `400` and any other status as [`Error::UnexpectedStatus`].
    fn scenario_ok(&self, resp: reqwest::blocking::Response) -> Result<()> {
        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // SRE control plane — load scenario registry
    // ------------------------------------------------------------------

    /// Register (load) a load scenario in the registry without running it.
    ///
    /// Sends a `PUT /mockserver/loadScenario` with the given [`LoadScenario`].
    /// The scenario's [`name`](LoadScenario::name) is the unique registry key
    /// used later by [`start_load_scenarios`](Self::start_load_scenarios) /
    /// [`stop_load_scenarios`](Self::stop_load_scenarios) and the per-scenario
    /// fetch/delete endpoints.
    ///
    /// Registering is always allowed — even when load generation is disabled on
    /// the server — so this does not surface [`Error::FeatureDisabled`]. Returns
    /// the raw JSON the server echoes (`{"name":..,"state":"LOADED"}`).
    pub fn load_scenario(&self, scenario: &LoadScenario) -> Result<Value> {
        let resp = self
            .http
            .put(self.url("/mockserver/loadScenario"))
            .json(scenario)
            .send()?;
        self.load_scenario_json(resp)
    }

    /// List every registered load scenario.
    ///
    /// Sends a `GET /mockserver/loadScenario` and returns the raw JSON
    /// (`{"scenarios":[{"name":..,"state":..,"definition":..,"status":..?}]}`).
    pub fn load_scenarios(&self) -> Result<Value> {
        let resp = self.http.get(self.url("/mockserver/loadScenario")).send()?;
        self.load_scenario_json(resp)
    }

    /// Fetch a single registered load scenario by name.
    ///
    /// Sends a `GET /mockserver/loadScenario/{name}`. Returns
    /// [`Error::NotFound`] when no scenario with that name is registered.
    pub fn get_load_scenario(&self, name: impl AsRef<str>) -> Result<Value> {
        let resp = self
            .http
            .get(self.url(&format!("/mockserver/loadScenario/{}", name.as_ref())))
            .send()?;
        self.load_scenario_json(resp)
    }

    /// Remove a single registered load scenario by name.
    ///
    /// Sends a `DELETE /mockserver/loadScenario/{name}`. Returns
    /// [`Error::NotFound`] when no scenario with that name is registered.
    pub fn delete_load_scenario(&self, name: impl AsRef<str>) -> Result<Value> {
        let resp = self
            .http
            .delete(self.url(&format!("/mockserver/loadScenario/{}", name.as_ref())))
            .send()?;
        self.load_scenario_json(resp)
    }

    /// Clear all registered load scenarios.
    ///
    /// Sends a `DELETE /mockserver/loadScenario`. Idempotent.
    pub fn clear_load_scenarios(&self) -> Result<Value> {
        let resp = self
            .http
            .delete(self.url("/mockserver/loadScenario"))
            .send()?;
        self.load_scenario_json(resp)
    }

    /// Start one or more registered load scenarios by name.
    ///
    /// Sends a `PUT /mockserver/loadScenario/start` with `{"names":[...]}`.
    /// Requires load generation to be enabled on the server — returns
    /// [`Error::FeatureDisabled`] on `403` (`loadGenerationEnabled=false`) — and
    /// [`Error::NotFound`] when a name is not registered. Honours each
    /// scenario's `startDelayMillis`. Returns the raw JSON
    /// (`{"started":[{"name":..,"state":..}],"status":..}`).
    pub fn start_load_scenarios<S: AsRef<str>>(&self, names: &[S]) -> Result<Value> {
        let names: Vec<&str> = names.iter().map(|n| n.as_ref()).collect();
        let body = serde_json::json!({ "names": names });
        let resp = self
            .http
            .put(self.url("/mockserver/loadScenario/start"))
            .json(&body)
            .send()?;
        self.load_scenario_json(resp)
    }

    /// Stop running load scenarios.
    ///
    /// Sends a `PUT /mockserver/loadScenario/stop`. When `names` is non-empty the
    /// body is `{"names":[...]}`; when it is empty (or `&[]`) the body is empty,
    /// which the server treats as "stop all". Returns the raw JSON
    /// (`{"stopped":[..],"status":..}`).
    pub fn stop_load_scenarios<S: AsRef<str>>(&self, names: &[S]) -> Result<Value> {
        let mut req = self.http.put(self.url("/mockserver/loadScenario/stop"));
        if names.is_empty() {
            req = req.header("Content-Type", "application/json").body("");
        } else {
            let names: Vec<&str> = names.iter().map(|n| n.as_ref()).collect();
            req = req.json(&serde_json::json!({ "names": names }));
        }
        let resp = req.send()?;
        self.load_scenario_json(resp)
    }

    /// Convenience: register `scenario` then immediately start it by name.
    ///
    /// Equivalent to [`load_scenario`](Self::load_scenario) followed by
    /// [`start_load_scenarios`](Self::start_load_scenarios) with the scenario's
    /// own name. Returns the JSON from the `start` call. Surfaces
    /// [`Error::FeatureDisabled`] from `start` when load generation is disabled.
    pub fn run_load_scenario(&self, scenario: &LoadScenario) -> Result<Value> {
        self.load_scenario(scenario)?;
        self.start_load_scenarios(&[scenario.name.as_str()])
    }

    /// Fetch the end-of-run summary report for a load scenario run.
    ///
    /// Sends a `GET /mockserver/loadScenario/{name}/report`. When `format` is
    /// `Some("junit")` a `?format=junit` query is appended and the server returns
    /// a JUnit-XML `<testsuite>` document; omit `format` (`None`) for the JSON
    /// report. The raw response body is returned as a string so either form (JSON
    /// or XML) passes through verbatim. Returns [`Error::NotFound`] when the
    /// scenario never ran.
    pub fn get_load_scenario_report(
        &self,
        name: impl AsRef<str>,
        format: Option<&str>,
    ) -> Result<String> {
        let mut path = format!("/mockserver/loadScenario/{}/report", name.as_ref());
        if let Some(format) = format {
            path.push_str("?format=");
            path.push_str(format);
        }
        let resp = self.http.get(self.url(&path)).send()?;
        let status = resp.status().as_u16();
        match status {
            200 | 201 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            404 => Err(Error::NotFound(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Generate (and register) an editable load scenario from an OpenAPI spec.
    ///
    /// Sends a `PUT /mockserver/loadScenario/generateFromOpenAPI`. The `body`
    /// carries the generated scenario `name`, the `specUrlOrPayload`, and an
    /// optional `target` and `profile`. Like [`load_scenario`](Self::load_scenario)
    /// this only registers (LOADED) the scenario — it generates no traffic and is
    /// allowed even when load generation is disabled. Returns the raw JSON
    /// (`{"status":"loaded","name":..,"state":..,"scenario":..}`).
    pub fn generate_load_scenario_from_openapi<T: Serialize + ?Sized>(
        &self,
        body: &T,
    ) -> Result<Value> {
        let resp = self
            .http
            .put(self.url("/mockserver/loadScenario/generateFromOpenAPI"))
            .json(body)
            .send()?;
        self.load_scenario_json(resp)
    }

    /// Generate (and register) an editable load scenario from recorded proxy
    /// traffic.
    ///
    /// Sends a `PUT /mockserver/loadScenario/generateFromRecording`. The `body`
    /// carries the generated scenario `name` and the recording selection/options.
    /// Like [`load_scenario`](Self::load_scenario) this only registers (LOADED)
    /// the scenario — it generates no traffic. Returns the raw JSON
    /// (`{"status":"loaded","name":..,"state":..,"scenario":..}`).
    pub fn generate_load_scenario_from_recording<T: Serialize + ?Sized>(
        &self,
        body: &T,
    ) -> Result<Value> {
        let resp = self
            .http
            .put(self.url("/mockserver/loadScenario/generateFromRecording"))
            .json(body)
            .send()?;
        self.load_scenario_json(resp)
    }

    // ------------------------------------------------------------------
    // SRE control plane — service chaos
    // ------------------------------------------------------------------

    /// Register a service-scoped HTTP chaos profile for a downstream host.
    ///
    /// Sends a `PUT /mockserver/serviceChaos`. `ttl_millis`, when supplied, sets
    /// an optional time-to-live after which the registration auto-reverts.
    /// Returns the raw JSON the server echoes.
    pub fn set_service_chaos(
        &self,
        host: impl Into<String>,
        profile: &HttpChaosProfile,
        ttl_millis: Option<u64>,
    ) -> Result<Value> {
        let mut body = serde_json::json!({
            "host": host.into(),
            "chaos": profile,
        });
        if let Some(ttl) = ttl_millis {
            body["ttlMillis"] = serde_json::json!(ttl);
        }
        let resp = self
            .http
            .put(self.url("/mockserver/serviceChaos"))
            .json(&body)
            .send()?;
        self.json_or_feature_error(resp)
    }

    /// Remove a single host's service-scoped chaos profile.
    ///
    /// Sends a `PUT /mockserver/serviceChaos` with `{"host":..,"remove":true}`.
    pub fn remove_service_chaos(&self, host: impl Into<String>) -> Result<Value> {
        let body = serde_json::json!({ "host": host.into(), "remove": true });
        let resp = self
            .http
            .put(self.url("/mockserver/serviceChaos"))
            .json(&body)
            .send()?;
        self.json_or_feature_error(resp)
    }

    /// Clear all service-scoped chaos.
    ///
    /// Sends a `PUT /mockserver/serviceChaos` with `{"clear":true}`.
    pub fn clear_service_chaos(&self) -> Result<Value> {
        let body = serde_json::json!({ "clear": true });
        let resp = self
            .http
            .put(self.url("/mockserver/serviceChaos"))
            .json(&body)
            .send()?;
        self.json_or_feature_error(resp)
    }

    // ------------------------------------------------------------------
    // SRE control plane — SLO verdicts
    // ------------------------------------------------------------------

    /// Verify a set of service-level objectives over a window.
    ///
    /// Sends a `PUT /mockserver/verifySLO`. The HTTP status encodes the verdict:
    /// `200` for PASS or INCONCLUSIVE, `406` for FAIL — both deserialize into a
    /// [`SloVerdict`] (inspect [`SloVerdict::result`]). A `400` (malformed
    /// criteria, or SLO tracking disabled) surfaces as [`Error::FeatureDisabled`].
    ///
    /// Returns `Ok(SloVerdict)` for both PASS/INCONCLUSIVE (200) and FAIL (406)
    /// so callers can branch on the verdict; transport/parse failures and `400`
    /// are returned as `Err`.
    pub fn verify_slo(&self, criteria: &SloCriteria) -> Result<SloVerdict> {
        let resp = self
            .http
            .put(self.url("/mockserver/verifySLO"))
            .json(criteria)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            // PASS / INCONCLUSIVE (200) and FAIL (406) both carry a SloVerdict.
            200 | 406 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            400 => Err(Error::FeatureDisabled(resp.text()?)),
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // SRE control plane — preemption
    // ------------------------------------------------------------------

    /// Cordon and drain the server (preemption simulation).
    ///
    /// Sends a `PUT /mockserver/preemption` with the given [`PreemptionRequest`]
    /// and returns the resulting [`PreemptionStatus`].
    pub fn set_preemption(&self, request: &PreemptionRequest) -> Result<PreemptionStatus> {
        let resp = self
            .http
            .put(self.url("/mockserver/preemption"))
            .json(request)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Retrieve the current preemption status.
    ///
    /// Sends a `GET /mockserver/preemption` and returns the [`PreemptionStatus`].
    pub fn preemption_status(&self) -> Result<PreemptionStatus> {
        let resp = self
            .http
            .get(self.url("/mockserver/preemption"))
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                Ok(serde_json::from_str(&text)?)
            }
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Uncordon the server (clear any active preemption simulation).
    ///
    /// Sends a `DELETE /mockserver/preemption`. Idempotent — succeeds whether or
    /// not a simulation was active. Returns the raw JSON status.
    pub fn clear_preemption(&self) -> Result<Value> {
        let resp = self
            .http
            .delete(self.url("/mockserver/preemption"))
            .send()?;
        self.json_or_feature_error(resp)
    }

    // ------------------------------------------------------------------
    // SRE control plane — chaos experiments
    // ------------------------------------------------------------------

    /// Start a scheduled multi-stage chaos experiment.
    ///
    /// Sends a `PUT /mockserver/chaosExperiment` with the given
    /// [`ChaosExperiment`]. Only one experiment may be active at a time; starting
    /// a new one stops the previous one. Returns the raw JSON status
    /// (`{"status":"started","name":..}`).
    pub fn start_chaos_experiment(&self, experiment: &ChaosExperiment) -> Result<Value> {
        let resp = self
            .http
            .put(self.url("/mockserver/chaosExperiment"))
            .json(experiment)
            .send()?;
        self.json_or_feature_error(resp)
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    /// Common handler for SRE endpoints returning JSON on `200`, mapping `403`
    /// to [`Error::FeatureDisabled`] (the feature is disabled on the server),
    /// `400` to [`Error::InvalidRequest`], and any other status to
    /// [`Error::UnexpectedStatus`]. An empty `200` body deserializes to JSON
    /// `null`.
    fn json_or_feature_error(&self, resp: reqwest::blocking::Response) -> Result<Value> {
        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(Value::Null)
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Handler for load-scenario registry endpoints. Like
    /// [`json_or_feature_error`](Self::json_or_feature_error) but additionally
    /// maps `404` to [`Error::NotFound`] (an unknown scenario name).
    fn load_scenario_json(&self, resp: reqwest::blocking::Response) -> Result<Value> {
        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.is_empty() {
                    Ok(Value::Null)
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            403 => Err(Error::FeatureDisabled(resp.text()?)),
            404 => Err(Error::NotFound(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Clock control
    // ------------------------------------------------------------------

    /// Freeze the simulated clock (`PUT /mockserver/clock`, `action=freeze`).
    ///
    /// Pass `Some(instant)` — an ISO-8601 instant string such as
    /// `"2024-01-01T00:00:00Z"` — to freeze at a specific time, or `None` to
    /// freeze at the current time. Returns the clock-status JSON the server
    /// echoes back.
    pub fn freeze_clock(&self, instant: Option<&str>) -> Result<String> {
        let body = match instant {
            Some(i) => serde_json::json!({ "action": "freeze", "instant": i }),
            None => serde_json::json!({ "action": "freeze" }),
        };
        self.clock_put(&body)
    }

    /// Advance the simulated clock by `duration_millis` (`PUT /mockserver/clock`,
    /// `action=advance`). The value must be positive — the server returns `400`
    /// for `<= 0`. Returns the clock-status JSON the server echoes back.
    pub fn advance_clock(&self, duration_millis: i64) -> Result<String> {
        let body = serde_json::json!({ "action": "advance", "durationMillis": duration_millis });
        self.clock_put(&body)
    }

    /// Reset the simulated clock back to the real system clock
    /// (`PUT /mockserver/clock`, `action=reset`). Returns the clock-status JSON.
    pub fn reset_clock(&self) -> Result<String> {
        let body = serde_json::json!({ "action": "reset" });
        self.clock_put(&body)
    }

    /// Read the current clock status (`GET /mockserver/clock`). Returns the JSON
    /// body verbatim, e.g.
    /// `{"currentInstant":"...","currentEpochMillis":...,"frozen":true}`.
    pub fn clock_status(&self) -> Result<String> {
        let resp = self.http.get(self.url("/mockserver/clock")).send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    fn clock_put(&self, body: &Value) -> Result<String> {
        let resp = self
            .http
            .put(self.url("/mockserver/clock"))
            .json(body)
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Metrics
    // ------------------------------------------------------------------

    /// Retrieve the JSON metrics counter snapshot
    /// (`PUT /mockserver/retrieve?type=METRICS`). Returns a flat JSON object
    /// mapping each metric name to its long value (`{}` when metrics are
    /// disabled).
    pub fn retrieve_metrics(&self) -> Result<String> {
        let url = format!(
            "{}?type=METRICS",
            self.url("/mockserver/retrieve")
        );
        let resp = self
            .http
            .put(&url)
            .header("Content-Type", "application/json")
            .body("")
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Scrape the Prometheus exposition metrics (`GET /mockserver/metrics`).
    /// Returns the exposition text. When metrics are disabled the server replies
    /// `404`, surfaced as [`Error::NotFound`].
    pub fn scrape_metrics(&self) -> Result<String> {
        let resp = self.http.get(self.url("/mockserver/metrics")).send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            404 => Err(Error::NotFound(resp.text().unwrap_or_default())),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Configuration
    // ------------------------------------------------------------------

    /// Read the effective live configuration (`GET /mockserver/configuration`).
    /// Returns the serialized `Configuration` JSON.
    pub fn retrieve_configuration(&self) -> Result<String> {
        let resp = self
            .http
            .get(self.url("/mockserver/configuration"))
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Update the live configuration (`PUT /mockserver/configuration`).
    ///
    /// `config_json` is a `ConfigurationDTO` JSON document — only the fields
    /// present are applied (partial update). Returns the serialized *updated*
    /// configuration JSON.
    pub fn update_configuration(&self, config_json: &str) -> Result<String> {
        let resp = self
            .http
            .put(self.url("/mockserver/configuration"))
            .header("Content-Type", "application/json")
            .body(config_json.to_string())
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Drift detection
    // ------------------------------------------------------------------

    /// Retrieve the recorded mock drift report (`GET /mockserver/drift`).
    ///
    /// Returns the serialized report JSON, of the form
    /// `{"count": <n>, "drifts": [ ... ]}`, where each entry describes a
    /// difference detected between a mock's configured response and the live
    /// upstream response for the same request.
    pub fn retrieve_drift(&self) -> Result<String> {
        let resp = self.http.get(self.url("/mockserver/drift")).send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Clear all recorded mock drift (`PUT /mockserver/drift/clear`).
    pub fn clear_drift(&self) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/drift/clear"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Pact (import / export / verify)
    // ------------------------------------------------------------------

    /// Import a Pact v3 contract (`PUT /mockserver/pact/import`).
    ///
    /// Returns the JSON array of upserted expectations the server creates.
    pub fn pact_import(&self, json: &str) -> Result<Vec<Expectation>> {
        let resp = self
            .http
            .put(self.url("/mockserver/pact/import"))
            .header("Content-Type", "application/json")
            .body(json.to_string())
            .send()?;
        self.expectations_response(resp)
    }

    /// Export the active expectations as a Pact v3 contract
    /// (`PUT /mockserver/pact?consumer=&provider=`).
    ///
    /// A query parameter is only added when the corresponding value is non-blank
    /// (matching the Java client); blank values fall back to the server defaults.
    /// Returns the generated Pact JSON.
    pub fn pact_export(&self, consumer: &str, provider: &str) -> Result<String> {
        let mut params: Vec<(&str, &str)> = Vec::new();
        if !consumer.trim().is_empty() {
            params.push(("consumer", consumer));
        }
        if !provider.trim().is_empty() {
            params.push(("provider", provider));
        }
        let mut builder = self
            .http
            .put(self.url("/mockserver/pact"))
            .header("Content-Type", "application/json")
            .body("");
        if !params.is_empty() {
            builder = builder.query(&params);
        }
        let resp = builder.send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Verify a Pact v3 contract against the active expectations
    /// (`PUT /mockserver/pact/verify`).
    ///
    /// The verification *outcome* is returned in the [`Ok`] value rather than as
    /// an error: `202 ACCEPTED` maps to [`PactVerification`] with `passed = true`
    /// and `406 NOT_ACCEPTABLE` to `passed = false`. Both carry the server's
    /// verification report. A `400` (bad input) is surfaced as
    /// [`Error::InvalidRequest`].
    pub fn pact_verify(&self, json: &str) -> Result<PactVerification> {
        let resp = self
            .http
            .put(self.url("/mockserver/pact/verify"))
            .header("Content-Type", "application/json")
            .body(json.to_string())
            .send()?;
        let status = resp.status().as_u16();
        match status {
            202 => Ok(PactVerification {
                passed: true,
                report: resp.text()?,
            }),
            406 => Ok(PactVerification {
                passed: false,
                report: resp.text()?,
            }),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // File store
    // ------------------------------------------------------------------

    /// Store a file in the in-memory file store (`PUT /mockserver/files/store`).
    ///
    /// `content` is sent base64-encoded (with `"base64": true`) so arbitrary
    /// binary data round-trips intact. Returns the `{"name":..,"size":..}` JSON.
    pub fn store_file(&self, name: &str, content: &[u8]) -> Result<String> {
        let body = serde_json::json!({
            "name": name,
            "content": BASE64.encode(content),
            "base64": true,
        });
        let resp = self
            .http
            .put(self.url("/mockserver/files/store"))
            .json(&body)
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 | 201 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Retrieve a file's raw bytes (`PUT /mockserver/files/retrieve`).
    ///
    /// Returns the raw `200` body bytes. An unknown file (`404`) is surfaced as
    /// [`Error::NotFound`] (mirroring the crate's status-to-error mapping).
    pub fn retrieve_file(&self, name: &str) -> Result<Vec<u8>> {
        let body = serde_json::json!({ "name": name });
        let resp = self
            .http
            .put(self.url("/mockserver/files/retrieve"))
            .json(&body)
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.bytes()?.to_vec()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            404 => Err(Error::NotFound(resp.text().unwrap_or_default())),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// List the names of all stored files (`PUT /mockserver/files/list`).
    pub fn list_files(&self) -> Result<Vec<String>> {
        let resp = self
            .http
            .put(self.url("/mockserver/files/list"))
            .header("Content-Type", "application/json")
            .body("")
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => {
                let text = resp.text()?;
                if text.trim().is_empty() {
                    Ok(vec![])
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Delete a stored file (`PUT /mockserver/files/delete`). An unknown file
    /// (`404`) is surfaced as [`Error::NotFound`].
    pub fn delete_file(&self, name: &str) -> Result<()> {
        let body = serde_json::json!({ "name": name });
        let resp = self
            .http
            .put(self.url("/mockserver/files/delete"))
            .json(&body)
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(()),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            404 => Err(Error::NotFound(resp.text().unwrap_or_default())),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // Import (HAR / Postman)
    // ------------------------------------------------------------------

    /// Import a HAR document (`PUT /mockserver/import?format=har`). Returns the
    /// upserted expectations.
    pub fn import_har(&self, har_json: &str) -> Result<Vec<Expectation>> {
        self.import_document(har_json, "har")
    }

    /// Import a Postman collection
    /// (`PUT /mockserver/import?format=postman`). Returns the upserted
    /// expectations.
    pub fn import_postman_collection(&self, collection_json: &str) -> Result<Vec<Expectation>> {
        self.import_document(collection_json, "postman")
    }

    fn import_document(&self, json: &str, format: &str) -> Result<Vec<Expectation>> {
        let url = format!("{}?format={format}", self.url("/mockserver/import"));
        let resp = self
            .http
            .put(&url)
            .header("Content-Type", "application/json")
            .body(json.to_string())
            .send()?;
        self.expectations_response(resp)
    }

    // ------------------------------------------------------------------
    // Operating mode
    // ------------------------------------------------------------------

    /// Set the high-level operating mode (`PUT /mockserver/mode?mode=<MODE>`).
    /// Returns the `{"mode":..,"proxyUnmatchedRequests":..}` JSON.
    pub fn set_mode(&self, mode: MockMode) -> Result<String> {
        let url = format!("{}?mode={}", self.url("/mockserver/mode"), mode.as_str());
        let resp = self
            .http
            .put(&url)
            .header("Content-Type", "application/json")
            .body("")
            .send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    /// Read the current operating mode (`GET /mockserver/mode`). Returns the
    /// `{"mode":..,"proxyUnmatchedRequests":..}` JSON.
    pub fn retrieve_mode(&self) -> Result<String> {
        let resp = self.http.get(self.url("/mockserver/mode")).send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    // ------------------------------------------------------------------
    // WSDL
    // ------------------------------------------------------------------

    /// Generate expectations from a WSDL document (`PUT /mockserver/wsdl`).
    ///
    /// The raw WSDL XML is sent as the request body (Content-Type `text/xml`).
    /// Returns the generated (upserted) expectations.
    pub fn wsdl_expectation(&self, wsdl: &str) -> Result<Vec<Expectation>> {
        let resp = self
            .http
            .put(self.url("/mockserver/wsdl"))
            .header("Content-Type", "text/xml")
            .body(wsdl.to_string())
            .send()?;
        self.expectations_response(resp)
    }

    /// Map a `201`/`200` JSON-array-of-expectations response (used by import,
    /// pact-import and WSDL) to `Vec<Expectation>`, applying the crate's status
    /// conventions.
    fn expectations_response(
        &self,
        resp: reqwest::blocking::Response,
    ) -> Result<Vec<Expectation>> {
        let status = resp.status().as_u16();
        match status {
            200 | 201 => {
                let text = resp.text()?;
                if text.trim().is_empty() {
                    Ok(vec![])
                } else {
                    Ok(serde_json::from_str(&text)?)
                }
            }
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    fn do_verify(&self, verification: &Verification) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/verify"))
            .json(verification)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 202 => Ok(()),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    fn do_verify_sequence(&self, verification: &VerificationSequence) -> Result<()> {
        let resp = self
            .http
            .put(self.url("/mockserver/verifySequence"))
            .json(verification)
            .send()?;

        let status = resp.status().as_u16();
        match status {
            200 | 202 => Ok(()),
            406 => Err(Error::VerificationFailure(resp.text()?)),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }

    fn url(&self, path: &str) -> String {
        format!("{}{path}", self.base_url)
    }

    fn do_retrieve(
        &self,
        request: Option<&HttpRequest>,
        retrieve_type: RetrieveType,
        format: RetrieveFormat,
    ) -> Result<String> {
        let url = format!(
            "{}?type={}&format={}",
            self.url("/mockserver/retrieve"),
            retrieve_type.as_str(),
            format.as_str(),
        );

        let mut builder = self.http.put(&url);
        builder = builder.header("Content-Type", "application/json");
        if let Some(req) = request {
            builder = builder.json(req);
        } else {
            builder = builder.body("");
        }

        let resp = builder.send()?;
        let status = resp.status().as_u16();
        match status {
            200 => Ok(resp.text()?),
            400 => Err(Error::InvalidRequest(resp.text()?)),
            _ => Err(Error::UnexpectedStatus {
                status,
                body: resp.text().unwrap_or_default(),
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// ForwardChainExpectation (fluent builder)
// ---------------------------------------------------------------------------

/// Fluent builder for creating an expectation via `client.when(...).respond(...)`.
pub struct ForwardChainExpectation<'a> {
    client: &'a MockServerClient,
    request: HttpRequest,
    times: Option<Times>,
    time_to_live: Option<TimeToLive>,
    priority: Option<i32>,
    id: Option<String>,
}

impl<'a> ForwardChainExpectation<'a> {
    /// Set how many times this expectation should match.
    pub fn times(mut self, times: Times) -> Self {
        self.times = Some(times);
        self
    }

    /// Set the time-to-live for this expectation.
    pub fn time_to_live(mut self, ttl: TimeToLive) -> Self {
        self.time_to_live = Some(ttl);
        self
    }

    /// Set the priority for this expectation.
    pub fn priority(mut self, priority: i32) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Set the expectation ID (for upsert semantics).
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Complete the expectation with a response action.
    pub fn respond(self, response: HttpResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond(response);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a forward action.
    pub fn forward(self, forward: HttpForward) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.forward(forward);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with an error action.
    pub fn error(self, error: HttpError) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.error(error);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a Server-Sent Events (SSE) response action.
    pub fn respond_sse(self, sse: HttpSseResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond_sse(sse);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a WebSocket response action.
    pub fn respond_web_socket(self, ws: HttpWebSocketResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond_web_socket(ws);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a DNS response action.
    pub fn respond_dns(self, dns: DnsResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond_dns(dns);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a raw binary response action.
    pub fn respond_binary(self, binary: BinaryResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond_binary(binary);
        client.upsert(&[expectation])
    }

    /// Complete the expectation with a gRPC streaming response action.
    pub fn respond_grpc_stream(self, grpc: GrpcStreamResponse) -> Result<Vec<Expectation>> {
        let (client, expectation) = self.into_parts();
        let expectation = expectation.respond_grpc_stream(grpc);
        client.upsert(&[expectation])
    }

    // ------------------------------------------------------------------
    // `respond_with_*` aliases (cross-client naming parity)
    //
    // The Python, PHP, and .NET clients expose these advanced response
    // builders under `respond_with_*` names. These aliases give the Rust
    // fluent chain the same surface so examples translate verbatim across
    // clients; each simply delegates to its idiomatic Rust counterpart.
    // ------------------------------------------------------------------

    /// Alias of [`respond_sse`](Self::respond_sse) for cross-client naming parity.
    pub fn respond_with_sse(self, sse: HttpSseResponse) -> Result<Vec<Expectation>> {
        self.respond_sse(sse)
    }

    /// Alias of [`respond_web_socket`](Self::respond_web_socket) for cross-client naming parity.
    pub fn respond_with_web_socket(self, ws: HttpWebSocketResponse) -> Result<Vec<Expectation>> {
        self.respond_web_socket(ws)
    }

    /// Alias of [`respond_dns`](Self::respond_dns) for cross-client naming parity.
    pub fn respond_with_dns(self, dns: DnsResponse) -> Result<Vec<Expectation>> {
        self.respond_dns(dns)
    }

    /// Alias of [`respond_binary`](Self::respond_binary) for cross-client naming parity.
    pub fn respond_with_binary(self, binary: BinaryResponse) -> Result<Vec<Expectation>> {
        self.respond_binary(binary)
    }

    /// Alias of [`respond_grpc_stream`](Self::respond_grpc_stream) for cross-client naming parity.
    pub fn respond_with_grpc_stream(self, grpc: GrpcStreamResponse) -> Result<Vec<Expectation>> {
        self.respond_grpc_stream(grpc)
    }

    fn into_parts(self) -> (&'a MockServerClient, Expectation) {
        let ForwardChainExpectation {
            client,
            request,
            times,
            time_to_live,
            priority,
            id,
        } = self;
        let mut exp = Expectation::new(request);
        exp.times = times;
        exp.time_to_live = time_to_live;
        exp.priority = priority;
        exp.id = id;
        (client, exp)
    }
}

// ---------------------------------------------------------------------------
// Scenario (control-plane handle)
// ---------------------------------------------------------------------------

/// A handle for inspecting and driving a named scenario state-machine.
///
/// Obtained via [`MockServerClient::scenario`]. Each method issues a single
/// control-plane request against `/mockserver/scenario/{name}`.
pub struct Scenario<'a> {
    client: &'a MockServerClient,
    name: String,
}

impl Scenario<'_> {
    /// Get the scenario's current state.
    ///
    /// Sends `GET /mockserver/scenario/{name}`.
    pub fn state(&self) -> Result<String> {
        self.client.scenario_state(&self.name)
    }

    /// Set the scenario's state.
    ///
    /// Sends `PUT /mockserver/scenario/{name}` with `{"state": state}`.
    pub fn set(&self, state: &str) -> Result<()> {
        self.client.scenario_set(&self.name, state, None, None)
    }

    /// Set the scenario's state and schedule an automatic transition to
    /// `next_state` after `transition_after_ms` milliseconds.
    ///
    /// Sends `PUT /mockserver/scenario/{name}` with
    /// `{"state", "transitionAfterMs", "nextState"}`.
    pub fn set_timed(
        &self,
        state: &str,
        transition_after_ms: u64,
        next_state: &str,
    ) -> Result<()> {
        self.client.scenario_set(
            &self.name,
            state,
            Some(transition_after_ms),
            Some(next_state),
        )
    }

    /// Externally trigger a transition to `new_state`.
    ///
    /// Sends `PUT /mockserver/scenario/{name}/trigger` with `{"newState": new_state}`.
    pub fn trigger(&self, new_state: &str) -> Result<()> {
        self.client.scenario_trigger(&self.name, new_state)
    }
}