rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
//! Stub analysis for detecting conflicts, overlaps, and potential issues.
//!
//! This module provides Rift extensions for analyzing stubs that go beyond
//! Mountebank compatibility:
//!
//! - Duplicate ID detection
//! - Predicate overlap analysis
//! - Shadowed stub warnings
//!
//! **Mountebank Behavioral Note**: Mountebank does NOT provide any overlap
//! detection or warnings. It silently uses first-match-wins semantics.
//! These features are Rift extensions for improved developer experience.

use crate::imposter::Gate;
use crate::imposter::StubResponse;
use crate::imposter::{ImposterConfig, Stub};
use crate::imposter::{Predicate, PredicateOperation};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Cap on the number of stub-analysis warnings retained in a single result (issue #423). Beyond
/// this, a single [`WarningType::Truncated`] summary records how many were suppressed, so a
/// pathological config (thousands of overlapping stubs) can't allocate unbounded memory.
pub const MAX_STUB_WARNINGS: usize = 100;

/// Above this stub count the O(n²) subset-shadowing heuristic is skipped (issue #423): it is
/// advisory only, and quadratic pairwise comparison is not worth its cost on large imposters.
/// Exact-duplicate detection stays O(n) (hash-based) at any size.
const SHADOW_HEURISTIC_MAX_STUBS: usize = 200;

/// Warning types for stub analysis (Rift extension)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StubWarning {
    /// Type of warning
    pub warning_type: WarningType,
    /// Human-readable message
    pub message: String,
    /// Index of the affected stub (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stub_index: Option<usize>,
    /// ID of the affected stub (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stub_id: Option<String>,
    /// Index of the shadowing stub (for shadow warnings)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shadowed_by_index: Option<usize>,
}

/// Types of warnings that can be generated
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum WarningType {
    /// Stub with same ID already exists
    DuplicateId,
    /// Stub predicates are identical to another stub
    ExactDuplicate,
    /// Stub may be shadowed by an earlier stub with overlapping predicates
    PotentiallyShadowed,
    /// Stub has empty predicates (matches all requests)
    CatchAll,
    /// Catch-all stub is not at the end of the list
    CatchAllNotLast,
    /// Analysis produced more warnings than the retained cap; the summary records how many were
    /// suppressed (issue #423).
    Truncated,
    /// `_rift.stateOps` (issue #969) declared on a response shape that never runs it — `stateOps`
    /// executes only after an `is` response is rendered (see `extensions::state_ops`'s module
    /// doc). A `proxy`, `inject` or `fault` response does not get this warning: no part of its
    /// `_rift` block applies, and the whole block is reported as `ConfigKeyIgnored` instead. The
    /// reachable case is a script response (`_rift.script`). A bare-`_rift` response without a
    /// script is served as `is: {}` (issue #1685), so its `stateOps` run and it is not flagged.
    StateOpsNeverRuns,
    /// `_rift.conditional` (issue #1280) that can never answer 304 (issue #1296): it is read only
    /// on an `is` response, and only for GET/HEAD. Raised for a script response (`_rift.script`),
    /// and for an `is` response — or a bare-`_rift` one without a script, served as `is: {}`
    /// (issue #1685) — in a stub whose top-level `method` predicate excludes GET and HEAD. A
    /// `proxy`/`inject`/`fault` response gets [`WarningType::ConfigKeyIgnored`] instead.
    ConditionalNeverRuns,
    /// A key this engine parses and does not act on (issue #1152). The value reads back unchanged,
    /// so without this nothing distinguishes "honoured" from "dropped". See
    /// [`ignored_config_keys`] for the list.
    ConfigKeyIgnored,
}

/// The shape of a response that carries a `_rift` block no feature applies to.
fn ignored_rift_shape(response: &StubResponse) -> Option<&'static str> {
    match response {
        StubResponse::Proxy {
            ignored_rift: Some(_),
            ..
        } => Some("proxy"),
        StubResponse::Inject {
            ignored_rift: Some(_),
            ..
        } => Some("inject"),
        StubResponse::Fault {
            ignored_rift: Some(_),
            ..
        } => Some("fault"),
        _ => None,
    }
}

/// The shape of a response whose `_rift.script` never runs (issue #1729): one beside an `is`. Every
/// config door refuses it as two response types, so only a replayed or `--datadir` config an older
/// engine admitted reaches here; the `is` is served, with the block's other keys.
fn ignored_script_shape(response: &StubResponse) -> Option<&'static str> {
    match response {
        StubResponse::Is {
            rift: Some(rift), ..
        } if rift.script.is_some() => Some("is"),
        _ => None,
    }
}

/// The shape of a response whose behaviors block holds something no behavior runs on (issue #1181).
/// Behaviors run on `is`, `inject` and `proxy` responses; `repeat` applies to every response (#1188), so a
/// block that sets nothing else is not ignored.
fn ignored_behaviors_shape(response: &StubResponse) -> Option<&'static str> {
    let (shape, block) = match response {
        StubResponse::Fault {
            ignored_behaviors: Some(block),
            ..
        } => ("fault", block),
        StubResponse::RiftScript {
            ignored_behaviors: Some(block),
            ..
        } => ("_rift", block),
        _ => return None,
    };
    // The block is a compiled program (issue #1198): one element per step, `null`s already applied.
    // No `repeat` sets anything here: the first element's is the response's, which applies to every
    // response, and a later one is an inert custom key (issue #1672), as rift-lint reads it too.
    let sets_more_than_repeat = block.as_array().is_some_and(|program| {
        program
            .iter()
            .filter_map(serde_json::Value::as_object)
            .any(|element| element.keys().any(|k| k != "repeat"))
    });
    sets_more_than_repeat.then_some(shape)
}

/// The stubs with a response `shape_of` classifies as `shape`: the first index, and the indices as
/// a warning lists them — at most ten, then "and N more".
fn stubs_with_shape(
    stubs: &[Stub],
    shape: &str,
    shape_of: fn(&StubResponse) -> Option<&'static str>,
) -> Option<(usize, String)> {
    let indices: Vec<usize> = stubs
        .iter()
        .enumerate()
        .filter(|(_, stub)| stub.responses.iter().any(|r| shape_of(r) == Some(shape)))
        .map(|(index, _)| index)
        .collect();
    listed_stubs(&indices)
}

/// The first of `indices`, and the indices as a warning lists them — at most ten, then "and N
/// more".
fn listed_stubs(indices: &[usize]) -> Option<(usize, String)> {
    const LISTED: usize = 10;
    let &first = indices.first()?;
    let mut listed = indices
        .iter()
        .take(LISTED)
        .map(usize::to_string)
        .collect::<Vec<_>>()
        .join(", ");
    if indices.len() > LISTED {
        listed.push_str(&format!(" and {} more", indices.len() - LISTED));
    }
    Some((first, listed))
}

/// Every key in `config` that this engine parses and does not act on — the single list behind the
/// load-time log line, the `_rift.warnings` entries and the docs (issue #1152). `stubs` are the
/// imposter's current stubs, which a stub mutation may have changed since `config` was built.
///
/// The keys are kept, not refused: the SDKs emit several of them (`metrics`, `proxyPool`,
/// `recordMatches`), and a refusal would break every SDK user who touched those builders.
pub fn ignored_config_keys(config: &ImposterConfig, stubs: &[Stub]) -> Vec<StubWarning> {
    let imposter_level = |message: &str| StubWarning {
        warning_type: WarningType::ConfigKeyIgnored,
        message: message.to_owned(),
        stub_index: None,
        stub_id: None,
        shadowed_by_index: None,
    };
    let mut warnings = Vec::new();
    let rift = config.rift.as_ref();
    if rift.is_some_and(|r| r.metrics.is_some()) {
        warnings.push(imposter_level(
            "`_rift.metrics` has no effect: metrics are process-wide, served on --metrics-port \
             (default 9090), and not configurable per imposter",
        ));
    }
    if rift.is_some_and(|r| r.proxy.is_some()) {
        warnings.push(imposter_level(
            "`_rift.proxy` has no effect: a proxy response's upstream is its own `proxy.to`, and \
             connection pooling is not configurable per imposter",
        ));
    }
    if config.record_matches {
        warnings.push(imposter_level(
            "`recordMatches` has no effect: this engine does not record per-stub `matches`; use \
             `recordRequests` and GET /imposters/:port to see the requests",
        ));
    }
    // https only: on any other protocol the imposter drops it, as Mountebank does (#1576).
    if config.ciphers.is_some() && config.protocol.eq_ignore_ascii_case("https") {
        warnings.push(imposter_level(
            "`ciphers` is stored and printed but not applied: the TLS listener uses rustls' \
             default suites (Mountebank passes it to OpenSSL as a cipher list)",
        ));
    }
    if config
        .default_response
        .as_ref()
        .is_some_and(|d| d.proxy.is_some())
    {
        warnings.push(imposter_level(
            "`defaultResponse.proxy` has no effect: an unmatched request is answered from \
             `defaultResponse`'s statusCode/headers/body (Mountebank does not proxy from it either); \
             use `defaultForward` to forward unmatched requests",
        ));
    }
    // One entry per shape, however many stubs carry it: a generated imposter can put `_rift` on
    // every response, and one entry per response would undo the MAX_STUB_WARNINGS bound (#423).
    let per_shape = |first: usize, message: String| StubWarning {
        warning_type: WarningType::ConfigKeyIgnored,
        message,
        stub_index: Some(first),
        stub_id: stubs[first].id.clone(),
        shadowed_by_index: None,
    };
    for shape in ["proxy", "inject", "fault"] {
        if let Some((first, listed)) = stubs_with_shape(stubs, shape, ignored_rift_shape) {
            warnings.push(per_shape(
                first,
                format!(
                    "`_rift` on a `{shape}` response has no effect: no `_rift` feature applies to \
                     a `{shape}` response (stubs {listed})"
                ),
            ));
        }
    }
    if let Some((first, listed)) = stubs_with_shape(stubs, "is", ignored_script_shape) {
        warnings.push(per_shape(
            first,
            format!(
                "`_rift.script` beside an `is` response has no effect: a script is a response type \
                 of its own, and the `is` is served (stubs {listed})"
            ),
        ));
    }
    for (shape, noun, why) in [
        (
            "fault",
            "a `fault` response",
            "the rest do not apply to a fault, as in Mountebank",
        ),
        (
            "_rift",
            "a `_rift`-only response",
            "the rest do not apply to a script response",
        ),
    ] {
        if let Some((first, listed)) = stubs_with_shape(stubs, shape, ignored_behaviors_shape) {
            warnings.push(per_shape(
                first,
                format!(
                    "A behaviors block on {noun} has no effect except `repeat`: {why} \
                     (stubs {listed})"
                ),
            ));
        }
    }
    if let Some(warning) = unread_generator_keys_warning(stubs) {
        warnings.push(warning);
    }
    if let Some(warning) = unknown_fault_warning(stubs) {
        warnings.push(warning);
    }
    warnings
}

/// One entry for every top-level `fault` name the engine does not know (issue #1556), naming the
/// names and the stubs. Mountebank admits such a config and ignores the fault at serve time (an
/// empty response, completed by `defaultResponse`), so Rift does too, and says so once at load
/// rather than per request.
fn unknown_fault_warning(stubs: &[Stub]) -> Option<StubWarning> {
    let mut names: Vec<&str> = Vec::new();
    let mut indices: Vec<usize> = Vec::new();
    for (index, stub) in stubs.iter().enumerate() {
        let mut unknown_here = false;
        for response in &stub.responses {
            if let StubResponse::Fault { fault, .. } = response
                && crate::imposter::fault_io::TcpFaultKind::parse(fault).is_none()
            {
                unknown_here = true;
                if !names.contains(&fault.as_str()) {
                    names.push(fault);
                }
            }
        }
        if unknown_here {
            indices.push(index);
        }
    }
    let (first, listed) = listed_stubs(&indices)?;
    let names = names
        .iter()
        .map(|name| format!("`{name}`"))
        .collect::<Vec<_>>()
        .join(", ");
    Some(StubWarning {
        warning_type: WarningType::ConfigKeyIgnored,
        message: format!(
            "`fault` {names} is not a fault Rift knows: it is ignored and the response is served as \
             an empty response completed by `defaultResponse`, as in Mountebank (stubs {listed})"
        ),
        stub_index: Some(first),
        stub_id: stubs[first].id.clone(),
        shadowed_by_index: None,
    })
}

/// One entry for every proxy `predicateGenerators` key the engine does not read (issue #1327),
/// naming the keys and the stubs: accepted, so a Mountebank config keeps loading, and reported so a
/// typo (`matchs`) is not a silent no-op generator.
fn unread_generator_keys_warning(stubs: &[Stub]) -> Option<StubWarning> {
    let mut keys: Vec<String> = Vec::new();
    let mut indices: Vec<usize> = Vec::new();
    for (index, stub) in stubs.iter().enumerate() {
        let unread: Vec<String> = stub
            .responses
            .iter()
            .filter_map(|response| match response {
                StubResponse::Proxy { proxy, .. } => Some(&proxy.predicate_generators),
                _ => None,
            })
            .flatten()
            .flat_map(crate::imposter::unread_generator_keys)
            .collect();
        if !unread.is_empty() {
            indices.push(index);
            keys.extend(unread);
        }
    }
    let (first, listed) = listed_stubs(&indices)?;
    keys.sort_unstable();
    keys.dedup();
    Some(StubWarning {
        warning_type: WarningType::ConfigKeyIgnored,
        message: format!(
            "proxy `predicateGenerators` key(s) {} have no effect: this engine reads inject, \
             matches, caseSensitive, predicateOperator, except, jsonpath, xpath and ignore \
             (stubs {listed})",
            keys.iter()
                .map(|key| format!("`{key}`"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
        stub_index: Some(first),
        stub_id: stubs[first].id.clone(),
        shadowed_by_index: None,
    })
}

/// Result of stub analysis
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct StubAnalysisResult {
    /// Warnings generated during analysis
    pub warnings: Vec<StubWarning>,
}

impl StubAnalysisResult {
    pub fn new() -> Self {
        Self { warnings: vec![] }
    }

    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }

    pub fn add_warning(&mut self, warning: StubWarning) {
        self.warnings.push(warning);
    }
}

/// Analyzes stubs for potential issues like duplicates, overlaps, and shadowing.
///
/// This is a Rift extension - Mountebank does not provide this functionality.
pub fn analyze_stubs(stubs: &[Stub]) -> StubAnalysisResult {
    let mut result = StubAnalysisResult::new();
    // Count of every warning the analysis *would* emit; `result.warnings` retains at most
    // MAX_STUB_WARNINGS of them, and the gap becomes the Truncated summary (issue #423).
    let mut total: usize = 0;
    let mut push = |warnings: &mut Vec<StubWarning>, w: StubWarning| {
        total += 1;
        if warnings.len() < MAX_STUB_WARNINGS {
            warnings.push(w);
        }
    };

    let mut seen_ids: HashMap<String, usize> = HashMap::new();
    // Canonical predicate-set key -> first stub index carrying it. Exact-duplicate detection is
    // O(n) instead of the old O(n²) pairwise scan (issue #423): the key encodes exactly what
    // `predicates_equal` compares — the predicate count plus the order-independent, de-duplicated
    // set of canonicalized predicates — so a hash hit means the same match set.
    // Each key holds every `(gate, index)` first seen with it: a stub is a duplicate only of an
    // earlier stub whose gate covers its own (issue #1308), so the bucket is scanned for one.
    let mut seen_predicates: HashMap<String, Vec<(Gate<'_>, usize)>> = HashMap::new();
    // Index of the first catch-all (empty-predicate) stub seen so far, of any gate. Drives the
    // `CatchAll` / `CatchAllNotLast` summaries.
    let mut first_catch_all: Option<usize> = None;
    // The catch-alls that shadow later stubs (issue #1308): the first ungated one covers every
    // gate; a gated one covers only stubs behind its exact gate.
    let mut first_ungated_catch_all: Option<usize> = None;
    let mut first_catch_all_by_gate: HashMap<Gate<'_>, usize> = HashMap::new();
    // The subset-shadowing heuristic is the only remaining quadratic scan; gate it by size.
    let run_shadow_heuristic = stubs.len() <= SHADOW_HEURISTIC_MAX_STUBS;

    for (index, stub) in stubs.iter().enumerate() {
        // Duplicate IDs.
        if let Some(id) = &stub.id {
            if let Some(&existing_index) = seen_ids.get(id) {
                push(
                    &mut result.warnings,
                    StubWarning {
                        warning_type: WarningType::DuplicateId,
                        message: format!(
                            "Stub at index {index} has duplicate ID '{id}' (same as stub at index {existing_index})"
                        ),
                        stub_index: Some(index),
                        stub_id: Some(id.clone()),
                        shadowed_by_index: Some(existing_index),
                    },
                );
            } else {
                seen_ids.insert(id.clone(), index);
            }
        }

        // Catch-all (empty predicates).
        if stub.predicates.is_empty() {
            if first_catch_all.is_none() {
                first_catch_all = Some(index);
            }
            let gate = stub.gate();
            if gate.is_open() {
                first_ungated_catch_all.get_or_insert(index);
            } else {
                first_catch_all_by_gate.entry(gate).or_insert(index);
            }
            push(
                &mut result.warnings,
                StubWarning {
                    warning_type: WarningType::CatchAll,
                    message: format!(
                        "Stub at index {index} has empty predicates and will match ALL requests"
                    ),
                    stub_index: Some(index),
                    stub_id: stub.id.clone(),
                    shadowed_by_index: None,
                },
            );
        }

        // `_rift.stateOps` on a response shape that never runs it (issue #969). `proxy`/`inject`
        // keep their `_rift` as `ignored_rift` (reported as `ConfigKeyIgnored`), so the only
        // reachable shape here is a scripted `RiftScript`; a script-less one is served as `is: {}`
        // and runs its ops (issue #1685).
        for response in &stub.responses {
            if let StubResponse::RiftScript { rift, .. } = response
                && rift.script.is_some()
                && !rift.state_ops.is_empty()
            {
                push(
                    &mut result.warnings,
                    StubWarning {
                        warning_type: WarningType::StateOpsNeverRuns,
                        message: format!(
                            "Stub at index {index} has _rift.stateOps on a script response \
                             (`_rift.script`); stateOps only runs after an `is` response is \
                             rendered, so these operations never execute"
                        ),
                        stub_index: Some(index),
                        stub_id: stub.id.clone(),
                        shadowed_by_index: None,
                    },
                );
            }
        }

        // `_rift.conditional` that can never answer 304 (issue #1296).
        let excluded_method = non_get_head_method(&stub.predicates);
        for response in &stub.responses {
            let message = match response {
                StubResponse::RiftScript { rift, .. }
                    if rift.script.is_some() && declares_conditional(rift) =>
                {
                    format!(
                        "Stub at index {index} has _rift.conditional on a script response \
                         (`_rift.script`); conditional GET applies only to an `is` response \
                         (move it to an `is`, or drop it)"
                    )
                }
                // A script-less `_rift` response is served as `is: {}` (issue #1685).
                StubResponse::Is {
                    rift: Some(rift), ..
                }
                | StubResponse::RiftScript { rift, .. }
                    if declares_conditional(rift) =>
                {
                    let Some(method) = excluded_method else {
                        continue;
                    };
                    format!(
                        "Stub at index {index} has _rift.conditional but its method predicate \
                         ({method}) excludes GET and HEAD, so it never answers 304"
                    )
                }
                _ => continue,
            };
            push(
                &mut result.warnings,
                StubWarning {
                    warning_type: WarningType::ConditionalNeverRuns,
                    message,
                    stub_index: Some(index),
                    stub_id: stub.id.clone(),
                    shadowed_by_index: None,
                },
            );
        }

        // Exact predicate duplicates — O(1) hash lookup against the first stub with this key.
        let key = predicate_key(&stub.predicates);
        let gate = stub.gate();
        let bucket = seen_predicates.entry(key).or_default();
        match bucket.iter().find(|(earlier, _)| earlier.covers(&gate)) {
            Some(&(_, first_index)) => push(
                &mut result.warnings,
                StubWarning {
                    warning_type: WarningType::ExactDuplicate,
                    message: format!(
                        "Stub at index {index} has identical predicates to stub at index {first_index} and will never match"
                    ),
                    stub_index: Some(index),
                    stub_id: stub.id.clone(),
                    shadowed_by_index: Some(first_index),
                },
            ),
            None => bucket.push((gate, index)),
        }

        // Potential shadowing of a specific (non-empty) stub by an earlier one.
        if !stub.predicates.is_empty() {
            // An earlier catch-all shadows this stub when its gate covers the stub's: the first
            // ungated one always does, else the one behind the stub's exact gate — O(1).
            let catch_all = first_ungated_catch_all
                .or_else(|| first_catch_all_by_gate.get(&stub.gate()).copied());
            if let Some(catch_all_index) = catch_all {
                push(
                    &mut result.warnings,
                    StubWarning {
                        warning_type: WarningType::PotentiallyShadowed,
                        message: format!(
                            "Stub at index {index} may be shadowed by catch-all stub at index {catch_all_index}"
                        ),
                        stub_index: Some(index),
                        stub_id: stub.id.clone(),
                        shadowed_by_index: Some(catch_all_index),
                    },
                );
            }
            // Subset-overlap heuristic — the remaining O(n²) scan, skipped on large imposters.
            if run_shadow_heuristic {
                for (earlier_index, earlier_stub) in stubs[..index].iter().enumerate() {
                    if !earlier_stub.predicates.is_empty()
                        && earlier_stub.gate().covers(&stub.gate())
                        && is_subset_predicates(&stub.predicates, &earlier_stub.predicates)
                    {
                        push(
                            &mut result.warnings,
                            StubWarning {
                                warning_type: WarningType::PotentiallyShadowed,
                                message: format!(
                                    "Stub at index {index} may be partially shadowed by stub at index {earlier_index} which has overlapping predicates"
                                ),
                                stub_index: Some(index),
                                stub_id: stub.id.clone(),
                                shadowed_by_index: Some(earlier_index),
                            },
                        );
                    }
                }
            }
        }
    }

    // Warn if a catch-all is not at the end.
    if let Some(catch_all_idx) = first_catch_all
        && catch_all_idx < stubs.len() - 1
    {
        push(
            &mut result.warnings,
            StubWarning {
                warning_type: WarningType::CatchAllNotLast,
                message: format!(
                    "Catch-all stub at index {} will shadow {} stub(s) after it",
                    catch_all_idx,
                    stubs.len() - catch_all_idx - 1
                ),
                stub_index: Some(catch_all_idx),
                stub_id: stubs[catch_all_idx].id.clone(),
                shadowed_by_index: None,
            },
        );
    }

    // Record how many warnings were suppressed by the cap rather than silently dropping them.
    let retained = result.warnings.len();
    if total > retained {
        result.warnings.push(StubWarning {
            warning_type: WarningType::Truncated,
            message: format!(
                "{} additional stub warning(s) suppressed (showing first {retained})",
                total - retained
            ),
            stub_index: None,
            stub_id: None,
            shadowed_by_index: None,
        });
    }

    result
}

/// Canonical key for a predicate list that matches [`predicates_equal`] semantics: two lists share
/// a key iff they have the same length and the same order-independent set of canonicalized
/// predicates. Used for O(n) exact-duplicate detection (issue #423).
/// `_rift.conditional` is declared and not switched off with `false`.
fn declares_conditional(rift: &crate::imposter::RiftResponseExtension) -> bool {
    !matches!(
        rift.conditional,
        None | Some(crate::imposter::ConditionalGet::Enabled(false))
    )
}

/// The value of a top-level `equals`/`deepEquals` `method` predicate that is a single string other
/// than GET/HEAD (compared case-insensitively), so conditional GET can never apply behind it.
///
/// Deliberately narrow: a `method` under `or`/`not`/`and`, a `matches`/`exists`, a non-string value
/// or a predicate with `except`/a selector is not judged. A false negative is fine; a false
/// positive on a working stub is not.
fn non_get_head_method(predicates: &[Predicate]) -> Option<&str> {
    predicates.iter().find_map(|p| {
        let (PredicateOperation::Equals(fields) | PredicateOperation::DeepEquals(fields)) =
            &p.operation
        else {
            return None;
        };
        if !p.parameters.except.is_empty() || p.parameters.selector.is_some() {
            return None;
        }
        let method = fields.get("method")?.as_str()?;
        (!method.eq_ignore_ascii_case("GET") && !method.eq_ignore_ascii_case("HEAD"))
            .then_some(method)
    })
}

fn predicate_key(predicates: &[Predicate]) -> String {
    let mut set: Vec<String> = predicates
        .iter()
        .map(|pred| {
            let mut value =
                serde_json::to_value(pred).expect("predicate can be serialized to json");
            value.sort_all_objects();
            value.to_string()
        })
        .collect();
    set.sort();
    set.dedup();
    // Length prefix so `[P, P]` and `[P]` (equal sets, different lengths) stay distinct.
    format!("{}\u{1e}{}", predicates.len(), set.join("\u{1e}"))
}

/// Analyzes adding a new stub to existing stubs.
///
/// Returns warnings about how the new stub interacts with existing stubs.
pub fn analyze_new_stub(
    existing_stubs: &[Stub],
    new_stub: &Stub,
    insert_index: usize,
) -> StubAnalysisResult {
    let mut result = StubAnalysisResult::new();

    // Check for duplicate ID
    if let Some(new_id) = &new_stub.id {
        for (index, stub) in existing_stubs.iter().enumerate() {
            if stub.id.as_ref() == Some(new_id) {
                result.add_warning(StubWarning {
                    warning_type: WarningType::DuplicateId,
                    message: format!(
                        "New stub has duplicate ID '{new_id}' (same as existing stub at index {index})"
                    ),
                    stub_index: Some(insert_index),
                    stub_id: Some(new_id.clone()),
                    shadowed_by_index: Some(index),
                });
            }
        }
    }

    // Check if new stub is a catch-all
    if new_stub.predicates.is_empty() {
        result.add_warning(StubWarning {
            warning_type: WarningType::CatchAll,
            message: "New stub has empty predicates and will match ALL requests".to_string(),
            stub_index: Some(insert_index),
            stub_id: new_stub.id.clone(),
            shadowed_by_index: None,
        });

        // Warn about stubs it will shadow
        let stubs_after = existing_stubs.len() - insert_index.min(existing_stubs.len());
        if stubs_after > 0 {
            result.add_warning(StubWarning {
                warning_type: WarningType::CatchAllNotLast,
                message: format!(
                    "New catch-all stub will shadow {stubs_after} existing stub(s) after it"
                ),
                stub_index: Some(insert_index),
                stub_id: new_stub.id.clone(),
                shadowed_by_index: None,
            });
        }
    }

    // Check for exact duplicates with existing stubs
    for (index, stub) in existing_stubs.iter().enumerate() {
        if predicates_equal(&new_stub.predicates, &stub.predicates) {
            let (shadower, shadowed) = if index < insert_index {
                (index, insert_index)
            } else {
                (insert_index, index)
            };
            // Only the earlier of the two can kill the later, and only when its gate covers it.
            let (earlier_gate, later_gate) = if index < insert_index {
                (stub.gate(), new_stub.gate())
            } else {
                (new_stub.gate(), stub.gate())
            };
            if !earlier_gate.covers(&later_gate) {
                continue;
            }
            result.add_warning(StubWarning {
                warning_type: WarningType::ExactDuplicate,
                message: format!(
                    "New stub has identical predicates to stub at index {index}. Stub at index {shadower} will shadow the other."
                ),
                stub_index: Some(shadowed),
                stub_id: new_stub.id.clone(),
                shadowed_by_index: Some(shadower),
            });
        }
    }

    // Check if new stub will be shadowed by existing stubs before it
    if !new_stub.predicates.is_empty() {
        for (index, stub) in existing_stubs.iter().enumerate() {
            if index >= insert_index {
                break;
            }
            if stub.predicates.is_empty() && stub.gate().covers(&new_stub.gate()) {
                result.add_warning(StubWarning {
                    warning_type: WarningType::PotentiallyShadowed,
                    message: format!(
                        "New stub will be shadowed by catch-all stub at index {index}"
                    ),
                    stub_index: Some(insert_index),
                    stub_id: new_stub.id.clone(),
                    shadowed_by_index: Some(index),
                });
            }
        }
    }

    result
}

/// Check if two predicate arrays are exactly equal
fn predicates_equal(a: &[Predicate], b: &[Predicate]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let canonicalize = |pred: &Predicate| {
        let mut value = serde_json::to_value(pred).expect("predicate can be serialized to json");
        value.sort_all_objects();
        value.to_string()
    };
    // Convert to sets for order-independent comparison
    // (predicates are AND'd, so order doesn't matter for matching)
    let a_set: HashSet<String> = a.iter().map(canonicalize).collect();
    let b_set: HashSet<String> = b.iter().map(canonicalize).collect();
    a_set == b_set
}

/// Check if `a` predicates are a subset of `b` predicates.
/// This is a heuristic - if all predicates in `b` are also in `a`,
/// then any request matching `a` would also match `b`.
fn is_subset_predicates(a: &[Predicate], b: &[Predicate]) -> bool {
    if b.is_empty() || a.is_empty() {
        return false;
    }

    // Simple heuristic: check if predicates share the same fields but with different specificity
    // For example, if stub A matches path="/api/users" and stub B matches path="/api",
    // then B is more general and will shadow A for paths starting with /api.

    // Extract field paths from predicates for comparison
    let a_fields = extract_predicate_fields(a);
    let b_fields = extract_predicate_fields(b);

    // If B's fields are a subset of A's fields with the same values, B is more general
    // This is a conservative check - we only flag clear cases
    for (field, b_value) in &b_fields {
        if let Some(a_value) = a_fields.get(field) {
            // Check if B's constraint is more general (e.g., startsWith vs equals)
            if is_more_general_constraint(b_value, a_value) {
                return true;
            }
        }
    }

    false
}

/// Extract field paths from predicates for comparison
fn extract_predicate_fields(predicates: &[Predicate]) -> HashMap<String, PredicateConstraint> {
    let mut fields = HashMap::new();

    for pred in predicates {
        match &pred.operation {
            PredicateOperation::Equals(equals) => {
                fields.extend(
                    equals
                        .iter()
                        .map(|(k, v)| (k.clone(), PredicateConstraint::Equals(v.clone()))),
                );
            }
            PredicateOperation::Contains(contains) => {
                fields.extend(
                    contains
                        .iter()
                        .map(|(k, v)| (k.clone(), PredicateConstraint::Contains(v.clone()))),
                );
            }
            PredicateOperation::StartsWith(starts_with) => {
                fields.extend(
                    starts_with
                        .iter()
                        .map(|(k, v)| (k.clone(), PredicateConstraint::StartsWith(v.clone()))),
                );
            }
            _ => {}
        }
    }

    fields
}

#[derive(Debug, Clone)]
enum PredicateConstraint {
    Equals(serde_json::Value),
    StartsWith(serde_json::Value),
    Contains(serde_json::Value),
}

/// Check if constraint `a` is more general than constraint `b`
fn is_more_general_constraint(a: &PredicateConstraint, b: &PredicateConstraint) -> bool {
    match (a, b) {
        // startsWith is more general than equals if the prefix matches
        (PredicateConstraint::StartsWith(prefix), PredicateConstraint::Equals(exact)) => {
            if let (Some(prefix_str), Some(exact_str)) = (prefix.as_str(), exact.as_str()) {
                exact_str.starts_with(prefix_str)
            } else {
                false
            }
        }
        // contains is more general than equals if the substring is present
        (PredicateConstraint::Contains(needle), PredicateConstraint::Equals(exact)) => {
            if let (Some(needle_str), Some(exact_str)) = (needle.as_str(), exact.as_str()) {
                exact_str.contains(needle_str)
            } else {
                false
            }
        }
        // startsWith is more general than startsWith if it's a prefix of the other
        (PredicateConstraint::StartsWith(a_prefix), PredicateConstraint::StartsWith(b_prefix)) => {
            if let (Some(a_str), Some(b_str)) = (a_prefix.as_str(), b_prefix.as_str()) {
                b_str.starts_with(a_str) && a_str != b_str
            } else {
                false
            }
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::RiftResponseExtension;
    use serde_json::json;

    fn predicates_from_jsons(predicates: Vec<serde_json::Value>) -> Vec<Predicate> {
        predicates
            .into_iter()
            .map(|v| serde_json::from_value(v).unwrap())
            .collect()
    }

    fn stub_with_predicates(predicates: Vec<serde_json::Value>) -> Stub {
        let predicates = predicates_from_jsons(predicates);
        Stub {
            name: None,
            id: None,
            route_pattern: None,
            predicates,
            responses: vec![],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        }
    }

    fn stub_with_id_and_predicates(id: &str, predicates: Vec<serde_json::Value>) -> Stub {
        let predicates = predicates_from_jsons(predicates);
        Stub {
            name: None,
            id: Some(id.to_string()),
            route_pattern: None,
            predicates,
            responses: vec![],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        }
    }

    #[test]
    fn test_duplicate_id_detection() {
        let stubs = vec![
            stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/a"}})]),
            stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/b"}})]),
        ];

        let result = analyze_stubs(&stubs);
        assert!(result.has_warnings());
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::DuplicateId)
        );
    }

    #[test]
    fn test_catch_all_detection() {
        let stubs = vec![
            stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]),
            stub_with_predicates(vec![]), // catch-all
        ];

        let result = analyze_stubs(&stubs);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::CatchAll)
        );
    }

    #[test]
    fn test_catch_all_not_last_warning() {
        let stubs = vec![
            stub_with_predicates(vec![]), // catch-all at start
            stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]),
        ];

        let result = analyze_stubs(&stubs);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::CatchAllNotLast)
        );
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::PotentiallyShadowed)
        );
    }

    #[test]
    fn test_exact_duplicate_detection() {
        let stubs = vec![
            stub_with_predicates(vec![json!({"equals": {"path": "/test", "method": "GET"}})]),
            stub_with_predicates(vec![json!({"equals": {"path": "/test", "method": "GET"}})]),
        ];

        let result = analyze_stubs(&stubs);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::ExactDuplicate)
        );
    }

    // Issue #423: N identical-predicate stubs must be analyzed in O(N) with a bounded warning set
    // (the old O(N²) exact-duplicate loop emitted ≈N²/2 warnings — hundreds of MB at N=1000).
    #[test]
    fn analyze_stubs_linear_capped_on_overlap() {
        let stubs: Vec<Stub> = (0..500)
            .map(|_| stub_with_predicates(vec![json!({"equals": {"path": "/data"}})]))
            .collect();

        let result = analyze_stubs(&stubs);

        // Bounded: at most the cap plus the single Truncated summary — never O(N²).
        assert!(
            result.warnings.len() <= MAX_STUB_WARNINGS + 1,
            "warnings must be bounded, got {}",
            result.warnings.len()
        );
        // The overlap is still detected...
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::ExactDuplicate)
        );
        // ...and truncation is reported rather than silently dropped, with the exact count.
        // 500 identical stubs => 499 ExactDuplicate warnings (stubs 1..=499); 100 retained,
        // 399 suppressed (the shadow heuristic is gated off at N=500, so nothing else fires).
        let summary = result
            .warnings
            .iter()
            .find(|w| w.warning_type == WarningType::Truncated)
            .expect("a Truncated summary must record the suppressed warnings");
        assert!(
            summary.message.contains("399 additional"),
            "wrong suppressed count: {}",
            summary.message
        );
    }

    // Issue #423: exact-duplicate detection is now O(n) and points every duplicate at the FIRST
    // occurrence — three identical stubs yield exactly two warnings (not one per earlier pair).
    #[test]
    fn exact_duplicate_points_at_first_occurrence() {
        let stubs: Vec<Stub> = (0..3)
            .map(|_| stub_with_predicates(vec![json!({"equals": {"path": "/same"}})]))
            .collect();

        let result = analyze_stubs(&stubs);
        let dups: Vec<&StubWarning> = result
            .warnings
            .iter()
            .filter(|w| w.warning_type == WarningType::ExactDuplicate)
            .collect();
        assert_eq!(
            dups.len(),
            2,
            "one warning per later duplicate, not per pair"
        );
        assert!(
            dups.iter().all(|w| w.shadowed_by_index == Some(0)),
            "each duplicate must point at the first occurrence"
        );
    }

    // Issue #423: the O(n²) subset-shadowing heuristic is gated off above the threshold, so a
    // general stub followed by many specifics doesn't reintroduce quadratic work — while the same
    // shape below the threshold still produces the advisory warning.
    #[test]
    fn subset_shadow_heuristic_gated_above_threshold() {
        let mut stubs = vec![stub_with_predicates(vec![
            json!({"startsWith": {"path": "/api"}}),
        ])];
        for i in 0..SHADOW_HEURISTIC_MAX_STUBS {
            stubs.push(stub_with_predicates(vec![
                json!({"equals": {"path": format!("/api/{i}")}}),
            ]));
        }
        assert!(stubs.len() > SHADOW_HEURISTIC_MAX_STUBS);
        assert!(
            !analyze_stubs(&stubs)
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::PotentiallyShadowed),
            "subset-shadowing heuristic must be skipped above the threshold"
        );

        let small = vec![
            stub_with_predicates(vec![json!({"startsWith": {"path": "/api"}})]),
            stub_with_predicates(vec![json!({"equals": {"path": "/api/users"}})]),
        ];
        assert!(
            analyze_stubs(&small)
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::PotentiallyShadowed),
            "below the threshold the heuristic still runs"
        );
    }

    #[test]
    fn test_no_warnings_for_different_stubs() {
        let stubs = vec![
            stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/a"}})]),
            stub_with_id_and_predicates("stub2", vec![json!({"equals": {"path": "/b"}})]),
        ];

        let result = analyze_stubs(&stubs);
        // May have warnings about different things, but not duplicates
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::DuplicateId)
        );
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::ExactDuplicate)
        );
    }

    #[test]
    fn test_shadowing_by_startswith() {
        let stubs = vec![
            stub_with_predicates(vec![json!({"startsWith": {"path": "/api"}})]),
            stub_with_predicates(vec![json!({"equals": {"path": "/api/users"}})]),
        ];

        let result = analyze_stubs(&stubs);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::PotentiallyShadowed)
        );
    }

    #[test]
    fn test_analyze_new_stub_duplicate_id() {
        let existing = vec![stub_with_id_and_predicates(
            "stub1",
            vec![json!({"equals": {"path": "/a"}})],
        )];
        let new_stub =
            stub_with_id_and_predicates("stub1", vec![json!({"equals": {"path": "/b"}})]);

        let result = analyze_new_stub(&existing, &new_stub, 1);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::DuplicateId)
        );
    }

    #[test]
    fn test_analyze_new_stub_shadowed_by_catchall() {
        let existing = vec![
            stub_with_predicates(vec![]), // catch-all
        ];
        let new_stub = stub_with_predicates(vec![json!({"equals": {"path": "/specific"}})]);

        let result = analyze_new_stub(&existing, &new_stub, 1);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::PotentiallyShadowed)
        );
    }

    // Issue #969: `_rift.stateOps` on a `RiftScript` response (the reachable non-`is` shape —
    // `proxy`/`inject` drop `_rift` entirely at parse time) must warn, since stateOps never runs
    // outside an `is` response.
    #[test]
    fn state_ops_on_a_rift_script_response_warns() {
        let rift: RiftResponseExtension = serde_json::from_value(json!({
            "script": { "code": "response.body = 'x';" },
            "stateOps": [{ "op": "increment", "key": "hits" }]
        }))
        .expect("parses");
        let stub = Stub {
            name: None,
            id: None,
            route_pattern: None,
            predicates: vec![],
            responses: vec![StubResponse::RiftScript {
                rift: Box::new(rift),
                ignored_behaviors: None,
            }],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        };

        let result = analyze_stubs(&[stub]);
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
            "a RiftScript response's stateOps must be flagged as never running: {:?}",
            result.warnings
        );
    }

    // A `RiftScript` response with NO `stateOps` (an actual script-only response) must not warn —
    // only a non-empty `stateOps` block on a non-`is` response is the problem.
    #[test]
    fn a_script_only_response_without_state_ops_does_not_warn() {
        let rift: RiftResponseExtension = serde_json::from_value(json!({
            "script": { "code": "response.body = 'x';" }
        }))
        .expect("parses");
        let stub = Stub {
            name: None,
            id: None,
            route_pattern: None,
            predicates: vec![],
            responses: vec![StubResponse::RiftScript {
                rift: Box::new(rift),
                ignored_behaviors: None,
            }],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        };

        let result = analyze_stubs(&[stub]);
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
            "a script-only response with no stateOps must not warn: {:?}",
            result.warnings
        );
    }

    // `stateOps` on an `is` response — the reachable, correct shape — must never warn.
    #[test]
    fn state_ops_on_an_is_response_does_not_warn() {
        let rift: RiftResponseExtension = serde_json::from_value(json!({
            "stateOps": [{ "op": "increment", "key": "hits" }]
        }))
        .expect("parses");
        let is_response = crate::imposter::StubResponse::new_is(
            crate::imposter::IsResponse::new(200, Default::default(), None, Default::default()),
            None,
            Some(Box::new(rift)),
        );
        let stub = Stub {
            name: None,
            id: None,
            route_pattern: None,
            predicates: vec![],
            responses: vec![is_response],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        };

        let result = analyze_stubs(&[stub]);
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
            "stateOps on an `is` response must not warn: {:?}",
            result.warnings
        );
    }

    // Issue #1685: a `_rift`-only response without a script is served as `is: {}`, so its
    // `stateOps` run and must not be flagged.
    #[test]
    fn state_ops_on_a_script_less_rift_response_does_not_warn() {
        let rift: RiftResponseExtension = serde_json::from_value(json!({
            "stateOps": [{ "op": "increment", "key": "hits" }]
        }))
        .expect("parses");
        let mut stub = conditional_stub(json!([]), true);
        stub.responses = vec![StubResponse::RiftScript {
            rift: Box::new(rift),
            ignored_behaviors: None,
        }];
        let result = analyze_stubs(&[stub]);
        assert!(
            !result
                .warnings
                .iter()
                .any(|w| w.warning_type == WarningType::StateOpsNeverRuns),
            "a script-less `_rift` response runs its stateOps: {:?}",
            result.warnings
        );
    }

    // Issue #1685: the same for `conditional` — it is read as on `is: {}`, so it warns only when the
    // stub's method predicate excludes GET and HEAD, as on an `is` response.
    #[test]
    fn conditional_on_a_script_less_rift_response_warns_only_like_is() {
        let script_less = |predicates: serde_json::Value| {
            let mut stub = conditional_stub(predicates, true);
            stub.responses = vec![StubResponse::RiftScript {
                rift: Box::new(
                    serde_json::from_value(json!({ "conditional": true })).expect("parses"),
                ),
                ignored_behaviors: None,
            }];
            conditional_warnings(stub)
        };
        let w = script_less(json!([]));
        assert!(w.is_empty(), "{w:?}");
        let w = script_less(json!([{ "equals": { "method": "post" } }]));
        assert_eq!(w.len(), 1, "{w:?}");
        assert!(w[0].message.contains("post"), "{}", w[0].message);
    }

    // ─── Issue #1296: `_rift.conditional` that can never fire ───────────────────────────────

    fn conditional_stub(predicates: serde_json::Value, script_only: bool) -> Stub {
        let rift: RiftResponseExtension = serde_json::from_value(json!({
            "conditional": true,
            "script": { "code": "response.body = 'x';" }
        }))
        .expect("parses");
        let response = if script_only {
            StubResponse::RiftScript {
                rift: Box::new(rift),
                ignored_behaviors: None,
            }
        } else {
            crate::imposter::StubResponse::new_is(
                crate::imposter::IsResponse::new(200, Default::default(), None, Default::default()),
                None,
                Some(Box::new(rift)),
            )
        };
        Stub {
            name: None,
            id: None,
            route_pattern: None,
            predicates: serde_json::from_value(predicates).expect("predicates parse"),
            responses: vec![response],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        }
    }

    fn conditional_warnings(stub: Stub) -> Vec<StubWarning> {
        analyze_stubs(&[stub])
            .warnings
            .into_iter()
            .filter(|w| w.warning_type == WarningType::ConditionalNeverRuns)
            .collect()
    }

    #[test]
    fn conditional_on_script_only_warns() {
        let w = conditional_warnings(conditional_stub(json!([]), true));
        assert_eq!(w.len(), 1, "{w:?}");
        assert!(w[0].message.contains("script response"), "{}", w[0].message);
    }

    #[test]
    fn conditional_behind_a_post_method_predicate_warns() {
        let w = conditional_warnings(conditional_stub(
            json!([{ "equals": { "method": "post" } }]),
            false,
        ));
        assert_eq!(w.len(), 1, "{w:?}");
        assert!(w[0].message.contains("post"), "{}", w[0].message);
        let w = conditional_warnings(conditional_stub(
            json!([{ "deepEquals": { "method": "POST" } }]),
            false,
        ));
        assert_eq!(w.len(), 1, "{w:?}");
    }

    #[test]
    fn conditional_on_a_get_stub_is_quiet() {
        for preds in [
            json!([]),
            json!([{ "equals": { "method": "GET" } }]),
            json!([{ "equals": { "method": "head" } }]),
            json!([{ "equals": { "path": "/x" } }]),
        ] {
            let w = conditional_warnings(conditional_stub(preds.clone(), false));
            assert!(w.is_empty(), "{preds}: {w:?}");
        }
    }

    #[test]
    fn conditional_under_or_is_not_judged() {
        for preds in [
            json!([{ "or": [{ "equals": { "method": "POST" } }, { "equals": { "method": "GET" } }] }]),
            json!([{ "not": { "equals": { "method": "GET" } } }]),
            json!([{ "matches": { "method": "^P" } }]),
            json!([{ "exists": { "method": true } }]),
            json!([{ "equals": { "method": 5 } }]),
        ] {
            let w = conditional_warnings(conditional_stub(preds.clone(), false));
            assert!(w.is_empty(), "{preds}: {w:?}");
        }
    }

    #[test]
    fn test_predicates_equal_order_independent() {
        let a = vec![
            json!({"equals": {"path": "/test"}}),
            json!({"equals": {"method": "GET"}}),
        ];
        let b = vec![
            json!({"equals": {"method": "GET"}}),
            json!({"equals": {"path": "/test"}}),
        ];
        let a = predicates_from_jsons(a);
        let b = predicates_from_jsons(b);
        assert!(predicates_equal(&a, &b));
    }

    #[test]
    fn test_predicates_not_equal() {
        let a = vec![json!({"equals": {"path": "/test"}})];
        let b = vec![json!({"equals": {"path": "/other"}})];
        let a = predicates_from_jsons(a);
        let b = predicates_from_jsons(b);
        assert!(!predicates_equal(&a, &b));
    }

    // Issue #1308: the analysis must read the same gates the matcher does.
    fn gated_stub(
        space: Option<&str>,
        scenario: Option<(&str, &str)>,
        predicates: Vec<serde_json::Value>,
    ) -> Stub {
        let mut stub = stub_with_predicates(predicates);
        stub.space = space.map(str::to_string);
        if let Some((name, state)) = scenario {
            stub.scenario_name = Some(name.to_string());
            stub.required_scenario_state = Some(state.to_string());
        }
        stub
    }

    fn count(result: &StubAnalysisResult, ty: WarningType) -> usize {
        result
            .warnings
            .iter()
            .filter(|w| w.warning_type == ty)
            .count()
    }

    fn pay() -> Vec<serde_json::Value> {
        vec![json!({"equals": {"method": "POST", "path": "/pay"}})]
    }

    #[test]
    fn a_scenario_gated_pair_with_identical_predicates_is_not_a_duplicate() {
        let stubs = vec![
            gated_stub(None, Some(("checkout", "Started")), pay()),
            gated_stub(None, Some(("checkout", "paid")), pay()),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::ExactDuplicate), 0);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
    }

    #[test]
    fn stubs_in_different_spaces_are_neither_duplicates_nor_shadowing() {
        let stubs = vec![
            gated_stub(Some("a"), None, vec![]),
            gated_stub(Some("b"), None, vec![]),
            gated_stub(Some("a"), None, pay()),
            gated_stub(Some("b"), None, pay()),
            gated_stub(
                Some("c"),
                None,
                vec![json!({"startsWith": {"path": "/api"}})],
            ),
            gated_stub(
                Some("d"),
                None,
                vec![json!({"equals": {"path": "/api/users"}})],
            ),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::ExactDuplicate), 0);
        // stubs 2 and 3 are shadowed by their own space's catch-all, and nothing else.
        let shadowed: Vec<_> = result
            .warnings
            .iter()
            .filter(|w| w.warning_type == WarningType::PotentiallyShadowed)
            .map(|w| (w.stub_index, w.shadowed_by_index))
            .collect();
        assert_eq!(shadowed, vec![(Some(2), Some(0)), (Some(3), Some(1))]);
    }

    #[test]
    fn a_gated_catch_all_does_not_shadow_an_ungated_stub() {
        let stubs = vec![
            gated_stub(None, Some(("s", "Started")), vec![]),
            gated_stub(None, None, vec![json!({"equals": {"path": "/x"}})]),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
    }

    #[test]
    fn the_subset_heuristic_honours_gates() {
        let stubs = vec![
            gated_stub(
                None,
                Some(("s", "Started")),
                vec![json!({"startsWith": {"path": "/api"}})],
            ),
            gated_stub(
                None,
                Some(("s", "paid")),
                vec![json!({"equals": {"path": "/api/users"}})],
            ),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);
    }

    #[test]
    fn analyze_new_stub_honours_gates_for_duplicates_and_catch_alls() {
        let started = gated_stub(None, Some(("s", "Started")), pay());
        let paid = gated_stub(None, Some(("s", "paid")), pay());
        let result = analyze_new_stub(std::slice::from_ref(&started), &paid, 1);
        assert_eq!(count(&result, WarningType::ExactDuplicate), 0);

        let gated_catch_all = gated_stub(None, Some(("s", "Started")), vec![]);
        let ungated = stub_with_predicates(pay());
        let result = analyze_new_stub(std::slice::from_ref(&gated_catch_all), &ungated, 1);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 0);

        let same_gate = gated_stub(None, Some(("s", "Started")), pay());
        let result = analyze_new_stub(std::slice::from_ref(&gated_catch_all), &same_gate, 1);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
    }

    #[test]
    fn an_ungated_twin_ahead_still_makes_a_gated_stub_a_duplicate() {
        let stubs = vec![
            stub_with_predicates(pay()),
            gated_stub(None, Some(("s", "paid")), pay()),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::ExactDuplicate), 1);
        let result = analyze_new_stub(&stubs[..1], &stubs[1], 1);
        assert_eq!(count(&result, WarningType::ExactDuplicate), 1);
    }

    #[test]
    fn an_ungated_catch_all_still_shadows_a_gated_stub() {
        let stubs = vec![
            stub_with_predicates(vec![]),
            gated_stub(None, Some(("s", "paid")), pay()),
        ];
        let result = analyze_stubs(&stubs);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
        let result = analyze_new_stub(&stubs[..1], &stubs[1], 1);
        assert_eq!(count(&result, WarningType::PotentiallyShadowed), 1);
    }

    /// Issue #1729: a `_rift.script` beside `is`, which only a replayed config can still carry, is
    /// one load-time entry; a `_rift` block without a script beside `is` applies and is not listed.
    #[test]
    fn a_rift_script_beside_is_is_reported_ignored() {
        let replayed = |response: serde_json::Value| -> Stub {
            crate::imposter::deserialize_replayed(json!({ "responses": [response] }))
                .expect("a replayed stub decodes")
        };
        let script =
            json!({ "script": { "engine": "rhai", "code": "fn respond(ctx) { pass() }" } });
        let stubs = [
            replayed(json!({ "is": { "body": "plain" } })),
            replayed(json!({ "is": { "statusCode": 200 }, "_rift": script })),
            replayed(
                json!({ "is": {}, "_rift": { "fault": { "latency": { "probability": 1.0, "ms": 5 } } } }),
            ),
            replayed(json!({ "is": { "statusCode": 201 }, "_rift": script })),
        ];
        let config: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
        let warnings = ignored_config_keys(&config, &stubs);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
        assert_eq!(warnings[0].stub_index, Some(1));
        assert_eq!(
            warnings[0].message,
            "`_rift.script` beside an `is` response has no effect: a script is a response type of \
             its own, and the `is` is served (stubs 1, 3)"
        );
        assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
        assert!(ignored_config_keys(&config, &stubs[2..3]).is_empty());
    }

    /// Issue #1327: predicate-generator keys the engine does not read are one entry, naming the
    /// keys and the stubs; a generator using only read keys adds nothing.
    #[test]
    fn unread_predicate_generator_keys_are_reported() {
        let proxy = |generators: serde_json::Value| -> Stub {
            serde_json::from_value(json!({
                "responses": [{ "proxy": { "to": "http://127.0.0.1:9", "predicateGenerators": generators } }]
            }))
            .expect("valid stub")
        };
        let stubs = [
            proxy(
                json!([{ "matches": { "body": true }, "jsonpath": { "selector": "$.id" }, "ignore": { "query": "ts" } }]),
            ),
            // Each with a real `matches`: an entry with neither is refused (#1413).
            proxy(json!([{ "matches": { "method": true }, "matchs": { "path": true } }])),
            proxy(
                json!([{ "matches": { "path": true }, "keyCaseSensitive": true }, { "matches": {}, "matchs": {} }]),
            ),
        ];
        let config: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
        let warnings = ignored_config_keys(&config, &stubs);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
        assert_eq!(warnings[0].stub_index, Some(1));
        assert_eq!(
            warnings[0].message,
            "proxy `predicateGenerators` key(s) `keyCaseSensitive`, `matchs` have no effect: this \
             engine reads inject, matches, caseSensitive, predicateOperator, except, jsonpath, \
             xpath and ignore (stubs 1, 2)"
        );
        assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
    }

    /// Issue #1556: an unknown top-level `fault` name is one load-time entry naming the names and
    /// the stubs; Mountebank's two names and Rift's aliases add nothing.
    #[test]
    fn an_unknown_fault_name_is_reported_once() {
        let fault = |name: &str| -> Stub {
            serde_json::from_value(json!({ "responses": [{ "fault": name }] })).expect("valid stub")
        };
        let stubs = [
            fault("CONNECTION_RESET_BY_PEER"),
            fault("NON_EXISTENT_FAULT"),
            fault("RANDOM_DATA_THEN_CLOSE"),
            fault("reset"),
            fault("EMPTY_RESPONSE"),
            fault("connection_reset_by_peer"),
            fault("NON_EXISTENT_FAULT"),
        ];
        let config: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http" })).expect("config");
        let warnings = ignored_config_keys(&config, &stubs);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
        assert_eq!(warnings[0].stub_index, Some(1));
        assert_eq!(
            warnings[0].message,
            "`fault` `NON_EXISTENT_FAULT`, `connection_reset_by_peer` is not a fault Rift knows: \
             it is ignored and the response is served as an empty response completed by \
             `defaultResponse`, as in Mountebank (stubs 1, 5, 6)"
        );
        assert!(ignored_config_keys(&config, &stubs[..1]).is_empty());
        assert!(ignored_config_keys(&config, &stubs[2..5]).is_empty());
    }

    /// Issue #1576: `ciphers` is stored and printed but not applied, so it is reported once.
    #[test]
    fn ciphers_is_reported_as_ignored() {
        let config: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "https", "ciphers": "x" }))
                .expect("config");
        let warnings = ignored_config_keys(&config, &[]);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert_eq!(warnings[0].warning_type, WarningType::ConfigKeyIgnored);
        assert!(
            warnings[0]
                .message
                .starts_with("`ciphers` is stored and printed but not applied"),
            "{}",
            warnings[0].message
        );
        let plain: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "https" })).expect("config");
        assert!(ignored_config_keys(&plain, &[]).is_empty());
        // On http it is dropped, as Mountebank drops it, so there is nothing to report.
        let http: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http", "ciphers": "x" }))
                .expect("config");
        assert!(ignored_config_keys(&http, &[]).is_empty());
    }
}