mockforge-bench 0.3.127

Load and performance testing for MockForge
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
//! Spec-driven conformance testing
//!
//! Analyzes the user's OpenAPI spec to determine which features their API uses,
//! then generates k6 conformance tests against their real endpoints.

use super::generator::ConformanceConfig;
use super::schema_validator::SchemaValidatorGenerator;
use super::spec::ConformanceFeature;
use crate::error::Result;
use crate::request_gen::RequestGenerator;
use crate::spec_parser::ApiOperation;
use openapiv3::{
    OpenAPI, Operation, Parameter, ParameterSchemaOrContent, ReferenceOr, RequestBody, Response,
    Schema, SchemaKind, SecurityScheme, StringFormat, Type, VariantOrUnknownOrEmpty,
};
use std::collections::HashSet;

/// Resolve `$ref` references against the OpenAPI components
mod ref_resolver {
    use super::*;

    pub fn resolve_parameter<'a>(
        param_ref: &'a ReferenceOr<Parameter>,
        spec: &'a OpenAPI,
    ) -> Option<&'a Parameter> {
        match param_ref {
            ReferenceOr::Item(param) => Some(param),
            ReferenceOr::Reference { reference } => {
                let name = reference.strip_prefix("#/components/parameters/")?;
                let components = spec.components.as_ref()?;
                match components.parameters.get(name)? {
                    ReferenceOr::Item(param) => Some(param),
                    ReferenceOr::Reference {
                        reference: inner_ref,
                    } => {
                        // One level of recursive resolution
                        let inner_name = inner_ref.strip_prefix("#/components/parameters/")?;
                        match components.parameters.get(inner_name)? {
                            ReferenceOr::Item(param) => Some(param),
                            ReferenceOr::Reference { .. } => None,
                        }
                    }
                }
            }
        }
    }

    pub fn resolve_request_body<'a>(
        body_ref: &'a ReferenceOr<RequestBody>,
        spec: &'a OpenAPI,
    ) -> Option<&'a RequestBody> {
        match body_ref {
            ReferenceOr::Item(body) => Some(body),
            ReferenceOr::Reference { reference } => {
                let name = reference.strip_prefix("#/components/requestBodies/")?;
                let components = spec.components.as_ref()?;
                match components.request_bodies.get(name)? {
                    ReferenceOr::Item(body) => Some(body),
                    ReferenceOr::Reference {
                        reference: inner_ref,
                    } => {
                        // One level of recursive resolution
                        let inner_name = inner_ref.strip_prefix("#/components/requestBodies/")?;
                        match components.request_bodies.get(inner_name)? {
                            ReferenceOr::Item(body) => Some(body),
                            ReferenceOr::Reference { .. } => None,
                        }
                    }
                }
            }
        }
    }

    pub fn resolve_schema<'a>(
        schema_ref: &'a ReferenceOr<Schema>,
        spec: &'a OpenAPI,
    ) -> Option<&'a Schema> {
        resolve_schema_with_visited(schema_ref, spec, &mut HashSet::new())
    }

    fn resolve_schema_with_visited<'a>(
        schema_ref: &'a ReferenceOr<Schema>,
        spec: &'a OpenAPI,
        visited: &mut HashSet<String>,
    ) -> Option<&'a Schema> {
        match schema_ref {
            ReferenceOr::Item(schema) => Some(schema),
            ReferenceOr::Reference { reference } => {
                if !visited.insert(reference.clone()) {
                    return None; // Cycle detected
                }
                let name = reference.strip_prefix("#/components/schemas/")?;
                let components = spec.components.as_ref()?;
                let nested = components.schemas.get(name)?;
                resolve_schema_with_visited(nested, spec, visited)
            }
        }
    }

    /// Resolve a boxed schema reference (used by array items and object properties)
    pub fn resolve_boxed_schema<'a>(
        schema_ref: &'a ReferenceOr<Box<Schema>>,
        spec: &'a OpenAPI,
    ) -> Option<&'a Schema> {
        match schema_ref {
            ReferenceOr::Item(schema) => Some(schema.as_ref()),
            ReferenceOr::Reference { reference } => {
                // Delegate to the regular schema resolver
                let name = reference.strip_prefix("#/components/schemas/")?;
                let components = spec.components.as_ref()?;
                let nested = components.schemas.get(name)?;
                resolve_schema_with_visited(nested, spec, &mut HashSet::new())
            }
        }
    }

    pub fn resolve_response<'a>(
        resp_ref: &'a ReferenceOr<Response>,
        spec: &'a OpenAPI,
    ) -> Option<&'a Response> {
        match resp_ref {
            ReferenceOr::Item(resp) => Some(resp),
            ReferenceOr::Reference { reference } => {
                let name = reference.strip_prefix("#/components/responses/")?;
                let components = spec.components.as_ref()?;
                match components.responses.get(name)? {
                    ReferenceOr::Item(resp) => Some(resp),
                    ReferenceOr::Reference {
                        reference: inner_ref,
                    } => {
                        // One level of recursive resolution
                        let inner_name = inner_ref.strip_prefix("#/components/responses/")?;
                        match components.responses.get(inner_name)? {
                            ReferenceOr::Item(resp) => Some(resp),
                            ReferenceOr::Reference { .. } => None,
                        }
                    }
                }
            }
        }
    }
}

/// Resolved security scheme details for an operation
#[derive(Debug, Clone)]
pub enum SecuritySchemeInfo {
    /// HTTP Bearer token
    Bearer,
    /// HTTP Basic auth
    Basic,
    /// API Key in header, query, or cookie
    ApiKey {
        location: ApiKeyLocation,
        name: String,
    },
}

/// Where an API key is transmitted
#[derive(Debug, Clone, PartialEq)]
pub enum ApiKeyLocation {
    Header,
    Query,
    Cookie,
}

/// An API operation annotated with the conformance features it exercises
#[derive(Debug, Clone)]
pub struct AnnotatedOperation {
    pub path: String,
    pub method: String,
    pub features: Vec<ConformanceFeature>,
    pub request_body_content_type: Option<String>,
    pub sample_body: Option<String>,
    pub query_params: Vec<(String, String)>,
    pub header_params: Vec<(String, String)>,
    pub path_params: Vec<(String, String)>,
    /// Response schema for validation (JSON string of the schema)
    pub response_schema: Option<Schema>,
    /// Security scheme details resolved from the OpenAPI spec
    pub security_schemes: Vec<SecuritySchemeInfo>,
}

/// Generates spec-driven conformance k6 scripts
pub struct SpecDrivenConformanceGenerator {
    config: ConformanceConfig,
    operations: Vec<AnnotatedOperation>,
}

impl SpecDrivenConformanceGenerator {
    pub fn new(config: ConformanceConfig, operations: Vec<AnnotatedOperation>) -> Self {
        Self { config, operations }
    }

    /// Annotate a list of API operations with conformance features
    pub fn annotate_operations(
        operations: &[ApiOperation],
        spec: &OpenAPI,
    ) -> Vec<AnnotatedOperation> {
        operations.iter().map(|op| Self::annotate_operation(op, spec)).collect()
    }

    /// Analyze an operation and determine which conformance features it exercises
    fn annotate_operation(op: &ApiOperation, spec: &OpenAPI) -> AnnotatedOperation {
        let mut features = Vec::new();
        let mut query_params = Vec::new();
        let mut header_params = Vec::new();
        let mut path_params = Vec::new();

        // Detect HTTP method feature
        match op.method.to_uppercase().as_str() {
            "GET" => features.push(ConformanceFeature::MethodGet),
            "POST" => features.push(ConformanceFeature::MethodPost),
            "PUT" => features.push(ConformanceFeature::MethodPut),
            "PATCH" => features.push(ConformanceFeature::MethodPatch),
            "DELETE" => features.push(ConformanceFeature::MethodDelete),
            "HEAD" => features.push(ConformanceFeature::MethodHead),
            "OPTIONS" => features.push(ConformanceFeature::MethodOptions),
            _ => {}
        }

        // Detect parameter features (resolves $ref)
        for param_ref in &op.operation.parameters {
            if let Some(param) = ref_resolver::resolve_parameter(param_ref, spec) {
                Self::annotate_parameter(
                    param,
                    spec,
                    &mut features,
                    &mut query_params,
                    &mut header_params,
                    &mut path_params,
                );
            }
        }

        // Detect path parameters from the path template itself
        for segment in op.path.split('/') {
            if segment.starts_with('{') && segment.ends_with('}') {
                let name = &segment[1..segment.len() - 1];
                // Only add if not already found from parameters
                if !path_params.iter().any(|(n, _)| n == name) {
                    path_params.push((name.to_string(), "test-value".to_string()));
                    // Determine type from path params we didn't already handle
                    if !features.contains(&ConformanceFeature::PathParamString)
                        && !features.contains(&ConformanceFeature::PathParamInteger)
                    {
                        features.push(ConformanceFeature::PathParamString);
                    }
                }
            }
        }

        // Detect request body features (resolves $ref)
        let mut request_body_content_type = None;
        let mut sample_body = None;

        let resolved_body = op
            .operation
            .request_body
            .as_ref()
            .and_then(|b| ref_resolver::resolve_request_body(b, spec));

        if let Some(body) = resolved_body {
            for (content_type, _media) in &body.content {
                match content_type.as_str() {
                    "application/json" => {
                        features.push(ConformanceFeature::BodyJson);
                        request_body_content_type = Some("application/json".to_string());
                        // Generate sample body from schema
                        if let Ok(template) = RequestGenerator::generate_template(op) {
                            if let Some(body_val) = &template.body {
                                sample_body = Some(body_val.to_string());
                            }
                        }
                    }
                    "application/x-www-form-urlencoded" => {
                        features.push(ConformanceFeature::BodyFormUrlencoded);
                        request_body_content_type =
                            Some("application/x-www-form-urlencoded".to_string());
                    }
                    "multipart/form-data" => {
                        features.push(ConformanceFeature::BodyMultipart);
                        request_body_content_type = Some("multipart/form-data".to_string());
                    }
                    _ => {}
                }
            }

            // Detect schema features in request body (resolves $ref in schema)
            if let Some(media) = body.content.get("application/json") {
                if let Some(schema_ref) = &media.schema {
                    if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
                        Self::annotate_schema(schema, spec, &mut features);
                    }
                }
            }
        }

        // Detect response code features
        Self::annotate_responses(&op.operation, spec, &mut features);

        // Extract response schema for validation (resolves $ref)
        let response_schema = Self::extract_response_schema(&op.operation, spec);
        if response_schema.is_some() {
            features.push(ConformanceFeature::ResponseValidation);
        }

        // Detect content negotiation (response with multiple content types)
        Self::annotate_content_negotiation(&op.operation, spec, &mut features);

        // Detect security features and resolve scheme details
        let mut security_schemes = Vec::new();
        Self::annotate_security(&op.operation, spec, &mut features, &mut security_schemes);

        // Deduplicate features
        features.sort_by_key(|f| f.check_name());
        features.dedup_by_key(|f| f.check_name());

        AnnotatedOperation {
            path: op.path.clone(),
            method: op.method.to_uppercase(),
            features,
            request_body_content_type,
            sample_body,
            query_params,
            header_params,
            path_params,
            response_schema,
            security_schemes,
        }
    }

    /// Annotate parameter features
    fn annotate_parameter(
        param: &Parameter,
        spec: &OpenAPI,
        features: &mut Vec<ConformanceFeature>,
        query_params: &mut Vec<(String, String)>,
        header_params: &mut Vec<(String, String)>,
        path_params: &mut Vec<(String, String)>,
    ) {
        let (location, data) = match param {
            Parameter::Query { parameter_data, .. } => ("query", parameter_data),
            Parameter::Path { parameter_data, .. } => ("path", parameter_data),
            Parameter::Header { parameter_data, .. } => ("header", parameter_data),
            Parameter::Cookie { .. } => {
                features.push(ConformanceFeature::CookieParam);
                return;
            }
        };

        // Detect type from schema
        let is_integer = Self::param_schema_is_integer(data, spec);
        let is_array = Self::param_schema_is_array(data, spec);

        // Generate sample value
        let sample = if is_integer {
            "42".to_string()
        } else if is_array {
            "a,b".to_string()
        } else {
            "test-value".to_string()
        };

        match location {
            "path" => {
                if is_integer {
                    features.push(ConformanceFeature::PathParamInteger);
                } else {
                    features.push(ConformanceFeature::PathParamString);
                }
                path_params.push((data.name.clone(), sample));
            }
            "query" => {
                if is_array {
                    features.push(ConformanceFeature::QueryParamArray);
                } else if is_integer {
                    features.push(ConformanceFeature::QueryParamInteger);
                } else {
                    features.push(ConformanceFeature::QueryParamString);
                }
                query_params.push((data.name.clone(), sample));
            }
            "header" => {
                features.push(ConformanceFeature::HeaderParam);
                header_params.push((data.name.clone(), sample));
            }
            _ => {}
        }

        // Check for constraint features on the parameter (resolves $ref)
        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
                Self::annotate_schema(schema, spec, features);
            }
        }

        // Required/optional
        if data.required {
            features.push(ConformanceFeature::ConstraintRequired);
        } else {
            features.push(ConformanceFeature::ConstraintOptional);
        }
    }

    fn param_schema_is_integer(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Integer(_)));
            }
        }
        false
    }

    fn param_schema_is_array(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Array(_)));
            }
        }
        false
    }

    /// Annotate schema-level features (types, composition, formats, constraints)
    fn annotate_schema(schema: &Schema, spec: &OpenAPI, features: &mut Vec<ConformanceFeature>) {
        match &schema.schema_kind {
            SchemaKind::Type(Type::String(s)) => {
                features.push(ConformanceFeature::SchemaString);
                // Check format
                match &s.format {
                    VariantOrUnknownOrEmpty::Item(StringFormat::Date) => {
                        features.push(ConformanceFeature::FormatDate);
                    }
                    VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
                        features.push(ConformanceFeature::FormatDateTime);
                    }
                    VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
                        "email" => features.push(ConformanceFeature::FormatEmail),
                        "uuid" => features.push(ConformanceFeature::FormatUuid),
                        "uri" | "url" => features.push(ConformanceFeature::FormatUri),
                        "ipv4" => features.push(ConformanceFeature::FormatIpv4),
                        "ipv6" => features.push(ConformanceFeature::FormatIpv6),
                        _ => {}
                    },
                    _ => {}
                }
                // Check constraints
                if s.pattern.is_some() {
                    features.push(ConformanceFeature::ConstraintPattern);
                }
                if !s.enumeration.is_empty() {
                    features.push(ConformanceFeature::ConstraintEnum);
                }
                if s.min_length.is_some() || s.max_length.is_some() {
                    features.push(ConformanceFeature::ConstraintMinMax);
                }
            }
            SchemaKind::Type(Type::Integer(i)) => {
                features.push(ConformanceFeature::SchemaInteger);
                if i.minimum.is_some() || i.maximum.is_some() {
                    features.push(ConformanceFeature::ConstraintMinMax);
                }
                if !i.enumeration.is_empty() {
                    features.push(ConformanceFeature::ConstraintEnum);
                }
            }
            SchemaKind::Type(Type::Number(n)) => {
                features.push(ConformanceFeature::SchemaNumber);
                if n.minimum.is_some() || n.maximum.is_some() {
                    features.push(ConformanceFeature::ConstraintMinMax);
                }
            }
            SchemaKind::Type(Type::Boolean(_)) => {
                features.push(ConformanceFeature::SchemaBoolean);
            }
            SchemaKind::Type(Type::Array(arr)) => {
                features.push(ConformanceFeature::SchemaArray);
                if let Some(item_ref) = &arr.items {
                    if let Some(item_schema) = ref_resolver::resolve_boxed_schema(item_ref, spec) {
                        Self::annotate_schema(item_schema, spec, features);
                    }
                }
            }
            SchemaKind::Type(Type::Object(obj)) => {
                features.push(ConformanceFeature::SchemaObject);
                // Check required fields
                if !obj.required.is_empty() {
                    features.push(ConformanceFeature::ConstraintRequired);
                }
                // Walk properties (resolves $ref)
                for (_name, prop_ref) in &obj.properties {
                    if let Some(prop_schema) = ref_resolver::resolve_boxed_schema(prop_ref, spec) {
                        Self::annotate_schema(prop_schema, spec, features);
                    }
                }
            }
            SchemaKind::OneOf { .. } => {
                features.push(ConformanceFeature::CompositionOneOf);
            }
            SchemaKind::AnyOf { .. } => {
                features.push(ConformanceFeature::CompositionAnyOf);
            }
            SchemaKind::AllOf { .. } => {
                features.push(ConformanceFeature::CompositionAllOf);
            }
            _ => {}
        }
    }

    /// Detect response code features (resolves $ref in responses)
    fn annotate_responses(
        operation: &Operation,
        spec: &OpenAPI,
        features: &mut Vec<ConformanceFeature>,
    ) {
        for (status_code, resp_ref) in &operation.responses.responses {
            // Only count features for responses that actually resolve
            if ref_resolver::resolve_response(resp_ref, spec).is_some() {
                match status_code {
                    openapiv3::StatusCode::Code(200) => {
                        features.push(ConformanceFeature::Response200)
                    }
                    openapiv3::StatusCode::Code(201) => {
                        features.push(ConformanceFeature::Response201)
                    }
                    openapiv3::StatusCode::Code(204) => {
                        features.push(ConformanceFeature::Response204)
                    }
                    openapiv3::StatusCode::Code(400) => {
                        features.push(ConformanceFeature::Response400)
                    }
                    openapiv3::StatusCode::Code(404) => {
                        features.push(ConformanceFeature::Response404)
                    }
                    _ => {}
                }
            }
        }
    }

    /// Extract the response schema for the primary success response (200 or 201)
    /// Resolves $ref for both the response and the schema within it.
    fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
        // Try 200 first, then 201
        for code in [200u16, 201] {
            if let Some(resp_ref) =
                operation.responses.responses.get(&openapiv3::StatusCode::Code(code))
            {
                if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
                    if let Some(media) = response.content.get("application/json") {
                        if let Some(schema_ref) = &media.schema {
                            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
                                return Some(schema.clone());
                            }
                        }
                    }
                }
            }
        }
        None
    }

    /// Detect content negotiation: response supports multiple content types
    fn annotate_content_negotiation(
        operation: &Operation,
        spec: &OpenAPI,
        features: &mut Vec<ConformanceFeature>,
    ) {
        for (_status_code, resp_ref) in &operation.responses.responses {
            if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
                if response.content.len() > 1 {
                    features.push(ConformanceFeature::ContentNegotiation);
                    return; // Only need to detect once per operation
                }
            }
        }
    }

    /// Detect security scheme features.
    /// Checks operation-level security first, falling back to global security requirements.
    /// Resolves scheme names against SecurityScheme definitions in components.
    fn annotate_security(
        operation: &Operation,
        spec: &OpenAPI,
        features: &mut Vec<ConformanceFeature>,
        security_schemes: &mut Vec<SecuritySchemeInfo>,
    ) {
        // Use operation-level security if present, otherwise fall back to global
        let security_reqs = operation.security.as_ref().or(spec.security.as_ref());

        if let Some(security) = security_reqs {
            for security_req in security {
                for scheme_name in security_req.keys() {
                    // Try to resolve the scheme from components for accurate type detection
                    if let Some(resolved) = Self::resolve_security_scheme(scheme_name, spec) {
                        match resolved {
                            SecurityScheme::HTTP { ref scheme, .. } => {
                                if scheme.eq_ignore_ascii_case("bearer") {
                                    features.push(ConformanceFeature::SecurityBearer);
                                    security_schemes.push(SecuritySchemeInfo::Bearer);
                                } else if scheme.eq_ignore_ascii_case("basic") {
                                    features.push(ConformanceFeature::SecurityBasic);
                                    security_schemes.push(SecuritySchemeInfo::Basic);
                                }
                            }
                            SecurityScheme::APIKey { location, name, .. } => {
                                features.push(ConformanceFeature::SecurityApiKey);
                                let loc = match location {
                                    openapiv3::APIKeyLocation::Query => ApiKeyLocation::Query,
                                    openapiv3::APIKeyLocation::Header => ApiKeyLocation::Header,
                                    openapiv3::APIKeyLocation::Cookie => ApiKeyLocation::Cookie,
                                };
                                security_schemes.push(SecuritySchemeInfo::ApiKey {
                                    location: loc,
                                    name: name.clone(),
                                });
                            }
                            // OAuth2 and OpenIDConnect don't map to our current feature set
                            _ => {}
                        }
                    } else {
                        // Fallback: heuristic name matching for unresolvable schemes
                        let name_lower = scheme_name.to_lowercase();
                        if name_lower.contains("bearer") || name_lower.contains("jwt") {
                            features.push(ConformanceFeature::SecurityBearer);
                            security_schemes.push(SecuritySchemeInfo::Bearer);
                        } else if name_lower.contains("api") && name_lower.contains("key") {
                            features.push(ConformanceFeature::SecurityApiKey);
                            security_schemes.push(SecuritySchemeInfo::ApiKey {
                                location: ApiKeyLocation::Header,
                                name: "X-API-Key".to_string(),
                            });
                        } else if name_lower.contains("basic") {
                            features.push(ConformanceFeature::SecurityBasic);
                            security_schemes.push(SecuritySchemeInfo::Basic);
                        }
                    }
                }
            }
        }
    }

    /// Resolve a security scheme name to its SecurityScheme definition
    fn resolve_security_scheme<'a>(name: &str, spec: &'a OpenAPI) -> Option<&'a SecurityScheme> {
        let components = spec.components.as_ref()?;
        match components.security_schemes.get(name)? {
            ReferenceOr::Item(scheme) => Some(scheme),
            ReferenceOr::Reference { .. } => None,
        }
    }

    /// Returns the number of operations being tested
    pub fn operation_count(&self) -> usize {
        self.operations.len()
    }

    /// Generate the k6 conformance script.
    /// Returns (script, check_count) where check_count is the number of unique checks emitted.
    pub fn generate(&self) -> Result<(String, usize)> {
        let mut script = String::with_capacity(16384);

        // Imports
        script.push_str("import http from 'k6/http';\n");
        script.push_str("import { check, group } from 'k6';\n");
        if self.config.request_delay_ms > 0 {
            script.push_str("import { sleep } from 'k6';\n");
        }
        script.push('\n');

        // Tell k6 that all HTTP status codes are "expected" in conformance mode.
        // Without this, k6 counts 4xx responses (e.g. intentional 404 tests) as
        // http_req_failed errors, producing a misleading error rate percentage.
        script.push_str(
            "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
        );

        // Options
        script.push_str("export const options = {\n");
        script.push_str("  vus: 1,\n");
        script.push_str("  iterations: 1,\n");
        if self.config.skip_tls_verify {
            script.push_str("  insecureSkipTLSVerify: true,\n");
        }
        script.push_str("  thresholds: {\n");
        script.push_str("    checks: ['rate>0'],\n");
        script.push_str("  },\n");
        script.push_str("};\n\n");

        // Base URL (includes base_path if configured)
        script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
        script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");

        // Failure detail collector — logs req/res info for failed checks via console.log
        // (k6's handleSummary runs in a separate JS context, so we can't use module-level arrays)
        script
            .push_str("function __captureFailure(checkName, res, expected, schemaViolations) {\n");
        script.push_str("  let bodyStr = '';\n");
        script.push_str("  try { bodyStr = res.body ? res.body.substring(0, 2000) : ''; } catch(e) { bodyStr = '<unreadable>'; }\n");
        script.push_str("  let reqHeaders = {};\n");
        script.push_str(
            "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
        );
        script.push_str("  let reqBody = '';\n");
        script.push_str("  if (res.request && res.request.body) { try { reqBody = res.request.body.substring(0, 2000); } catch(e) {} }\n");
        script.push_str("  let payload = {\n");
        script.push_str("    check: checkName,\n");
        script.push_str("    request: {\n");
        script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
        script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
        script.push_str("      headers: reqHeaders,\n");
        script.push_str("      body: reqBody,\n");
        script.push_str("    },\n");
        script.push_str("    response: {\n");
        script.push_str("      status: res.status,\n");
        script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
        script.push_str("      body: bodyStr,\n");
        script.push_str("    },\n");
        script.push_str("    expected: expected,\n");
        script.push_str("  };\n");
        script.push_str("  if (schemaViolations && schemaViolations.length > 0) { payload.schema_violations = schemaViolations; }\n");
        script.push_str("  console.log('MOCKFORGE_FAILURE:' + JSON.stringify(payload));\n");
        script.push_str("}\n\n");

        // Request/response capture for --export-requests
        if self.config.export_requests {
            script.push_str("function __captureExchange(checkName, res) {\n");
            script.push_str("  let bodyStr = '';\n");
            script.push_str("  try { bodyStr = res.body ? res.body.substring(0, 2000) : ''; } catch(e) { bodyStr = '<unreadable>'; }\n");
            script.push_str("  let reqHeaders = {};\n");
            script.push_str(
                "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
            );
            script.push_str("  let reqBody = '';\n");
            script.push_str("  if (res.request && res.request.body) { try { reqBody = res.request.body.substring(0, 2000); } catch(e) {} }\n");
            script.push_str("  console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
            script.push_str("    check: checkName,\n");
            script.push_str("    request: {\n");
            script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
            script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
            script.push_str("      headers: reqHeaders,\n");
            script.push_str("      body: reqBody,\n");
            script.push_str("    },\n");
            script.push_str("    response: {\n");
            script.push_str("      status: res.status,\n");
            script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
            script.push_str("      body: bodyStr,\n");
            script.push_str("    },\n");
            script.push_str("  }));\n");
            script.push_str("}\n\n");
        }

        // Default function
        script.push_str("export default function () {\n");

        if self.config.has_cookie_header() {
            script.push_str(
                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
            );
            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
        }

        // Group operations by category
        let mut category_ops: std::collections::BTreeMap<
            &'static str,
            Vec<(&AnnotatedOperation, &ConformanceFeature)>,
        > = std::collections::BTreeMap::new();

        for op in &self.operations {
            for feature in &op.features {
                let category = feature.category();
                if self.config.should_include_category(category) {
                    category_ops.entry(category).or_default().push((op, feature));
                }
            }
        }

        // Emit grouped tests
        let mut total_checks = 0usize;
        for (category, ops) in &category_ops {
            script.push_str(&format!("  group('{}', function () {{\n", category));

            if self.config.all_operations {
                // All-operations mode: test every operation, using path-qualified check names
                let mut emitted_checks: HashSet<String> = HashSet::new();
                for (op, feature) in ops {
                    let qualified = format!("{}:{}", feature.check_name(), op.path);
                    if emitted_checks.insert(qualified.clone()) {
                        self.emit_check_named(&mut script, op, feature, &qualified);
                        total_checks += 1;
                    }
                }
            } else {
                // Default: one representative operation per feature, with path-qualified
                // check names so failures identify which endpoint was tested.
                let mut emitted_features: HashSet<&str> = HashSet::new();
                for (op, feature) in ops {
                    if emitted_features.insert(feature.check_name()) {
                        let qualified = format!("{}:{}", feature.check_name(), op.path);
                        self.emit_check_named(&mut script, op, feature, &qualified);
                        total_checks += 1;
                    }
                }
            }

            script.push_str("  });\n\n");
        }

        // Custom checks from YAML file
        if let Some(custom_group) = self.config.generate_custom_group()? {
            script.push_str(&custom_group);
        }

        script.push_str("}\n\n");

        // handleSummary
        self.generate_handle_summary(&mut script);

        Ok((script, total_checks))
    }

    /// Emit a single k6 check for an operation + feature with a custom check name
    fn emit_check_named(
        &self,
        script: &mut String,
        op: &AnnotatedOperation,
        feature: &ConformanceFeature,
        check_name: &str,
    ) {
        // Escape single quotes in check name since it's embedded in JS single-quoted strings
        let check_name = check_name.replace('\'', "\\'");
        let check_name = check_name.as_str();

        script.push_str("    {\n");

        // Build the URL path with parameters substituted
        let mut url_path = op.path.clone();
        for (name, value) in &op.path_params {
            url_path = url_path.replace(&format!("{{{}}}", name), value);
        }

        // Build query string
        if !op.query_params.is_empty() {
            let qs: Vec<String> =
                op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
            url_path = format!("{}?{}", url_path, qs.join("&"));
        }

        let full_url = format!("${{BASE_URL}}{}", url_path);

        // Build effective headers: merge spec-derived headers with custom headers.
        // Custom headers override spec-derived ones with the same name.
        let mut effective_headers = self.effective_headers(&op.header_params);

        // For non-default response code checks, add header to tell the mock server
        // which status code to return (the server defaults to the first declared status)
        if matches!(feature, ConformanceFeature::Response400 | ConformanceFeature::Response404) {
            let expected_code = match feature {
                ConformanceFeature::Response400 => "400",
                ConformanceFeature::Response404 => "404",
                _ => unreachable!(),
            };
            effective_headers
                .push(("X-Mockforge-Response-Status".to_string(), expected_code.to_string()));
        }

        // For security checks AND for all requests on endpoints with security requirements,
        // inject auth credentials so the server doesn't reject with 401.
        // Only inject if the user hasn't already provided the header via --custom-headers.
        let needs_auth = matches!(
            feature,
            ConformanceFeature::SecurityBearer
                | ConformanceFeature::SecurityBasic
                | ConformanceFeature::SecurityApiKey
        ) || !op.security_schemes.is_empty();

        if needs_auth {
            self.inject_security_headers(&op.security_schemes, &mut effective_headers);
        }

        let has_headers = !effective_headers.is_empty();
        let headers_obj = if has_headers {
            Self::format_headers(&effective_headers)
        } else {
            String::new()
        };

        // Determine HTTP method and emit request
        match op.method.as_str() {
            "GET" => {
                if has_headers {
                    script.push_str(&format!(
                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
                        full_url, headers_obj
                    ));
                } else {
                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
                }
            }
            "POST" => {
                self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
            }
            "PUT" => {
                self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
            }
            "PATCH" => {
                self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
            }
            "DELETE" => {
                if has_headers {
                    script.push_str(&format!(
                        "      let res = http.del(`{}`, null, {{ headers: {} }});\n",
                        full_url, headers_obj
                    ));
                } else {
                    script.push_str(&format!("      let res = http.del(`{}`);\n", full_url));
                }
            }
            "HEAD" => {
                if has_headers {
                    script.push_str(&format!(
                        "      let res = http.head(`{}`, {{ headers: {} }});\n",
                        full_url, headers_obj
                    ));
                } else {
                    script.push_str(&format!("      let res = http.head(`{}`);\n", full_url));
                }
            }
            "OPTIONS" => {
                if has_headers {
                    script.push_str(&format!(
                        "      let res = http.options(`{}`, null, {{ headers: {} }});\n",
                        full_url, headers_obj
                    ));
                } else {
                    script.push_str(&format!("      let res = http.options(`{}`);\n", full_url));
                }
            }
            _ => {
                if has_headers {
                    script.push_str(&format!(
                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
                        full_url, headers_obj
                    ));
                } else {
                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
                }
            }
        }

        // Capture request/response for --export-requests
        // (check_name is already escaped at line 829 above — don't double-escape)
        if self.config.export_requests {
            script.push_str(&format!(
                "      if (typeof __captureExchange === 'function') __captureExchange('{}', res);\n",
                check_name
            ));
        }

        // Check: emit assertion based on feature type, with failure detail capture
        if matches!(
            feature,
            ConformanceFeature::Response200
                | ConformanceFeature::Response201
                | ConformanceFeature::Response204
                | ConformanceFeature::Response400
                | ConformanceFeature::Response404
        ) {
            let expected_code = match feature {
                ConformanceFeature::Response200 => 200,
                ConformanceFeature::Response201 => 201,
                ConformanceFeature::Response204 => 204,
                ConformanceFeature::Response400 => 400,
                ConformanceFeature::Response404 => 404,
                _ => 200,
            };
            script.push_str(&format!(
                "      {{ let ok = check(res, {{ '{}': (r) => r.status === {} }}); if (!ok) __captureFailure('{}', res, 'status === {}'); }}\n",
                check_name, expected_code, check_name, expected_code
            ));
        } else if matches!(feature, ConformanceFeature::ResponseValidation) {
            // Response schema validation — validate the response body against the schema
            // Uses inline field-level error collection so failure details include
            // which specific fields violated the schema (field_path, violation_type,
            // expected, actual) — matching the Ajv `errors` array structure.
            if let Some(schema) = &op.response_schema {
                let validation_js = SchemaValidatorGenerator::generate_validation(schema);
                let schema_json = serde_json::to_string(schema).unwrap_or_default();
                // Escape backticks and backslashes for JS template literal safety
                let schema_json_escaped = schema_json.replace('\\', "\\\\").replace('`', "\\`");
                script.push_str(&format!(
                    concat!(
                        "      try {{\n",
                        "        let body = res.json();\n",
                        "        let ok = check(res, {{ '{check}': (r) => ( {validation} ) }});\n",
                        "        if (!ok) {{\n",
                        "          let __violations = [];\n",
                        "          try {{\n",
                        "            let __schema = JSON.parse(`{schema}`);\n",
                        "            function __collectErrors(schema, data, path) {{\n",
                        "              if (!schema || typeof schema !== 'object') return;\n",
                        "              let st = schema.type || (schema.schema_kind && schema.schema_kind.Type && Object.keys(schema.schema_kind.Type)[0]);\n",
                        "              if (st) {{ st = st.toLowerCase(); }}\n",
                        "              if (st === 'object') {{\n",
                        "                if (typeof data !== 'object' || data === null) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'object', actual: typeof data }}); return; }}\n",
                        "                let props = schema.properties || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.properties) || {{}};\n",
                        "                let req = schema.required || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.required) || [];\n",
                        "                for (let f of req) {{ if (!(f in data)) {{ __violations.push({{ field_path: path + '/' + f, violation_type: 'required', expected: 'present', actual: 'missing' }}); }} }}\n",
                        "                for (let [k, v] of Object.entries(props)) {{ if (data[k] !== undefined) {{ let ps = v.Item || v; __collectErrors(ps, data[k], path + '/' + k); }} }}\n",
                        "              }} else if (st === 'array') {{\n",
                        "                if (!Array.isArray(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'array', actual: typeof data }}); return; }}\n",
                        "                let items = schema.items || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Array && schema.schema_kind.Type.Array.items);\n",
                        "                if (items) {{ let is = items.Item || items; for (let i = 0; i < Math.min(data.length, 5); i++) {{ __collectErrors(is, data[i], path + '/' + i); }} }}\n",
                        "              }} else if (st === 'string') {{\n",
                        "                if (typeof data !== 'string') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'string', actual: typeof data }}); }}\n",
                        "              }} else if (st === 'integer') {{\n",
                        "                if (typeof data !== 'number' || !Number.isInteger(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'integer', actual: typeof data }}); }}\n",
                        "              }} else if (st === 'number') {{\n",
                        "                if (typeof data !== 'number') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'number', actual: typeof data }}); }}\n",
                        "              }} else if (st === 'boolean') {{\n",
                        "                if (typeof data !== 'boolean') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'boolean', actual: typeof data }}); }}\n",
                        "              }}\n",
                        "            }}\n",
                        "            __collectErrors(__schema, body, '');\n",
                        "          }} catch(_e) {{}}\n",
                        "          __captureFailure('{check}', res, 'schema validation', __violations);\n",
                        "        }}\n",
                        "      }} catch(e) {{ check(res, {{ '{check}': () => false }}); __captureFailure('{check}', res, 'JSON parse failed: ' + e.message); }}\n",
                    ),
                    check = check_name,
                    validation = validation_js,
                    schema = schema_json_escaped,
                ));
            }
        } else if matches!(
            feature,
            ConformanceFeature::SecurityBearer
                | ConformanceFeature::SecurityBasic
                | ConformanceFeature::SecurityApiKey
        ) {
            // Security checks verify the server accepts the auth credentials (not 401/403)
            script.push_str(&format!(
                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 400 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 400 (auth accepted)'); }}\n",
                check_name, check_name
            ));
        } else {
            script.push_str(&format!(
                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 500'); }}\n",
                check_name, check_name
            ));
        }

        // Clear cookie jar after each request to prevent Set-Cookie leaking
        let has_cookie = self.config.has_cookie_header()
            || effective_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case("Cookie"));
        if has_cookie {
            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
        }

        script.push_str("    }\n");

        // Rate-limit delay between checks (to avoid 429 from target API)
        if self.config.request_delay_ms > 0 {
            script.push_str(&format!(
                "    sleep({:.3});\n",
                self.config.request_delay_ms as f64 / 1000.0
            ));
        }
    }

    /// Emit an HTTP request with a body
    fn emit_request_with_body(
        &self,
        script: &mut String,
        method: &str,
        url: &str,
        op: &AnnotatedOperation,
        effective_headers: &[(String, String)],
    ) {
        if let Some(body) = &op.sample_body {
            let escaped_body = body.replace('\'', "\\'");
            let headers = if !effective_headers.is_empty() {
                format!(
                    "Object.assign({{}}, JSON_HEADERS, {})",
                    Self::format_headers(effective_headers)
                )
            } else {
                "JSON_HEADERS".to_string()
            };
            script.push_str(&format!(
                "      let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
                method, url, escaped_body, headers
            ));
        } else if !effective_headers.is_empty() {
            script.push_str(&format!(
                "      let res = http.{}(`{}`, null, {{ headers: {} }});\n",
                method,
                url,
                Self::format_headers(effective_headers)
            ));
        } else {
            script.push_str(&format!("      let res = http.{}(`{}`, null);\n", method, url));
        }
    }

    /// Build effective headers by merging spec-derived headers with custom headers.
    /// Custom headers override spec-derived ones with the same name (case-insensitive).
    /// Custom headers not in the spec are appended.
    fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
        let custom = &self.config.custom_headers;
        if custom.is_empty() {
            return spec_headers.to_vec();
        }

        let mut result: Vec<(String, String)> = Vec::new();

        // Start with spec headers, replacing values if a custom header matches
        for (name, value) in spec_headers {
            if let Some((_, custom_val)) =
                custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
            {
                result.push((name.clone(), custom_val.clone()));
            } else {
                result.push((name.clone(), value.clone()));
            }
        }

        // Append custom headers that aren't already in spec headers
        for (name, value) in custom {
            if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
                result.push((name.clone(), value.clone()));
            }
        }

        result
    }

    /// Inject security headers based on resolved security scheme details.
    /// Respects user-provided custom headers (won't overwrite if already set).
    fn inject_security_headers(
        &self,
        schemes: &[SecuritySchemeInfo],
        headers: &mut Vec<(String, String)>,
    ) {
        let mut to_add: Vec<(String, String)> = Vec::new();

        let has_header = |name: &str, headers: &[(String, String)]| {
            headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
                || self.config.custom_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
        };

        // If user provides Cookie header, they're using session-based auth — skip auto auth
        let has_cookie_auth = has_header("Cookie", headers);

        for scheme in schemes {
            match scheme {
                SecuritySchemeInfo::Bearer => {
                    if !has_cookie_auth && !has_header("Authorization", headers) {
                        // MockForge mock server accepts any Bearer token
                        to_add.push((
                            "Authorization".to_string(),
                            "Bearer mockforge-conformance-test-token".to_string(),
                        ));
                    }
                }
                SecuritySchemeInfo::Basic => {
                    if !has_cookie_auth && !has_header("Authorization", headers) {
                        let creds = self.config.basic_auth.as_deref().unwrap_or("test:test");
                        use base64::Engine;
                        let encoded =
                            base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
                        to_add.push(("Authorization".to_string(), format!("Basic {}", encoded)));
                    }
                }
                SecuritySchemeInfo::ApiKey { location, name } => match location {
                    ApiKeyLocation::Header => {
                        if !has_header(name, headers) {
                            let key = self
                                .config
                                .api_key
                                .as_deref()
                                .unwrap_or("mockforge-conformance-test-key");
                            to_add.push((name.clone(), key.to_string()));
                        }
                    }
                    ApiKeyLocation::Cookie => {
                        if !has_header("Cookie", headers) {
                            to_add.push((
                                "Cookie".to_string(),
                                format!("{}=mockforge-conformance-test-session", name),
                            ));
                        }
                    }
                    ApiKeyLocation::Query => {
                        // Query params are handled via URL, not headers — skip here
                    }
                },
            }
        }

        headers.extend(to_add);
    }

    /// Format header params as a JS object literal
    fn format_headers(headers: &[(String, String)]) -> String {
        let entries: Vec<String> = headers
            .iter()
            .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
            .collect();
        format!("{{ {} }}", entries.join(", "))
    }

    /// handleSummary — same format as reference mode for report compatibility
    fn generate_handle_summary(&self, script: &mut String) {
        // Use absolute path for report output so k6 writes where the CLI expects
        let report_path = match &self.config.output_dir {
            Some(dir) => {
                let abs = std::fs::canonicalize(dir)
                    .unwrap_or_else(|_| dir.clone())
                    .join("conformance-report.json");
                abs.to_string_lossy().to_string()
            }
            None => "conformance-report.json".to_string(),
        };

        script.push_str("export function handleSummary(data) {\n");
        script.push_str("  let checks = {};\n");
        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
        script.push_str("  }\n");
        script.push_str("  let checkResults = {};\n");
        script.push_str("  function walkGroups(group) {\n");
        script.push_str("    if (group.checks) {\n");
        script.push_str("      for (let checkObj of group.checks) {\n");
        script.push_str("        checkResults[checkObj.name] = {\n");
        script.push_str("          passes: checkObj.passes,\n");
        script.push_str("          fails: checkObj.fails,\n");
        script.push_str("        };\n");
        script.push_str("      }\n");
        script.push_str("    }\n");
        script.push_str("    if (group.groups) {\n");
        script.push_str("      for (let subGroup of group.groups) {\n");
        script.push_str("        walkGroups(subGroup);\n");
        script.push_str("      }\n");
        script.push_str("    }\n");
        script.push_str("  }\n");
        script.push_str("  if (data.root_group) {\n");
        script.push_str("    walkGroups(data.root_group);\n");
        script.push_str("  }\n");
        script.push_str("  return {\n");
        script.push_str(&format!(
            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
            report_path
        ));
        script.push_str("    'summary.json': JSON.stringify(data),\n");
        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
        script.push_str("  };\n");
        script.push_str("}\n\n");
        script.push_str("function textSummary(data, opts) {\n");
        script.push_str("  return JSON.stringify(data, null, 2);\n");
        script.push_str("}\n");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use openapiv3::{
        Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
        SchemaData, SchemaKind, StringType, Type,
    };

    fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
        ApiOperation {
            method: method.to_string(),
            path: path.to_string(),
            operation,
            operation_id: None,
        }
    }

    fn empty_spec() -> OpenAPI {
        OpenAPI::default()
    }

    #[test]
    fn test_annotate_get_with_path_param() {
        let mut op = Operation::default();
        op.parameters.push(ReferenceOr::Item(Parameter::Path {
            parameter_data: ParameterData {
                name: "id".to_string(),
                description: None,
                required: true,
                deprecated: None,
                format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
                    schema_data: SchemaData::default(),
                    schema_kind: SchemaKind::Type(Type::String(StringType::default())),
                })),
                example: None,
                examples: Default::default(),
                explode: None,
                extensions: Default::default(),
            },
            style: PathStyle::Simple,
        }));

        let api_op = make_op("get", "/users/{id}", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
        assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
        assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
        assert_eq!(annotated.path_params.len(), 1);
        assert_eq!(annotated.path_params[0].0, "id");
    }

    #[test]
    fn test_annotate_post_with_json_body() {
        let mut op = Operation::default();
        let mut body = openapiv3::RequestBody {
            required: true,
            ..Default::default()
        };
        body.content
            .insert("application/json".to_string(), openapiv3::MediaType::default());
        op.request_body = Some(ReferenceOr::Item(body));

        let api_op = make_op("post", "/items", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
        assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
    }

    #[test]
    fn test_annotate_response_codes() {
        let mut op = Operation::default();
        op.responses
            .responses
            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
        op.responses
            .responses
            .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));

        let api_op = make_op("get", "/items", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(annotated.features.contains(&ConformanceFeature::Response200));
        assert!(annotated.features.contains(&ConformanceFeature::Response404));
    }

    #[test]
    fn test_generate_spec_driven_script() {
        let config = ConformanceConfig {
            target_url: "http://localhost:3000".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };

        let operations = vec![AnnotatedOperation {
            path: "/users/{id}".to_string(),
            method: "GET".to_string(),
            features: vec![
                ConformanceFeature::MethodGet,
                ConformanceFeature::PathParamString,
            ],
            request_body_content_type: None,
            sample_body: None,
            query_params: vec![],
            header_params: vec![],
            path_params: vec![("id".to_string(), "test-value".to_string())],
            response_schema: None,
            security_schemes: vec![],
        }];

        let gen = SpecDrivenConformanceGenerator::new(config, operations);
        let (script, _check_count) = gen.generate().unwrap();

        assert!(script.contains("import http from 'k6/http'"));
        assert!(script.contains("/users/test-value"));
        assert!(script.contains("param:path:string"));
        assert!(script.contains("method:GET"));
        assert!(script.contains("handleSummary"));
    }

    #[test]
    fn test_generate_with_category_filter() {
        let config = ConformanceConfig {
            target_url: "http://localhost:3000".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: Some(vec!["Parameters".to_string()]),
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };

        let operations = vec![AnnotatedOperation {
            path: "/users/{id}".to_string(),
            method: "GET".to_string(),
            features: vec![
                ConformanceFeature::MethodGet,
                ConformanceFeature::PathParamString,
            ],
            request_body_content_type: None,
            sample_body: None,
            query_params: vec![],
            header_params: vec![],
            path_params: vec![("id".to_string(), "1".to_string())],
            response_schema: None,
            security_schemes: vec![],
        }];

        let gen = SpecDrivenConformanceGenerator::new(config, operations);
        let (script, _check_count) = gen.generate().unwrap();

        assert!(script.contains("group('Parameters'"));
        assert!(!script.contains("group('HTTP Methods'"));
    }

    #[test]
    fn test_annotate_response_validation() {
        use openapiv3::ObjectType;

        // Operation with a 200 response that has a JSON schema
        let mut op = Operation::default();
        let mut response = Response::default();
        let mut media = openapiv3::MediaType::default();
        let mut obj_type = ObjectType::default();
        obj_type.properties.insert(
            "name".to_string(),
            ReferenceOr::Item(Box::new(Schema {
                schema_data: SchemaData::default(),
                schema_kind: SchemaKind::Type(Type::String(StringType::default())),
            })),
        );
        obj_type.required = vec!["name".to_string()];
        media.schema = Some(ReferenceOr::Item(Schema {
            schema_data: SchemaData::default(),
            schema_kind: SchemaKind::Type(Type::Object(obj_type)),
        }));
        response.content.insert("application/json".to_string(), media);
        op.responses
            .responses
            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));

        let api_op = make_op("get", "/users", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(
            annotated.features.contains(&ConformanceFeature::ResponseValidation),
            "Should detect ResponseValidation when response has a JSON schema"
        );
        assert!(annotated.response_schema.is_some(), "Should extract the response schema");

        // Verify generated script includes schema validation with try-catch
        let config = ConformanceConfig {
            target_url: "http://localhost:3000".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
        let (script, _check_count) = gen.generate().unwrap();

        assert!(
            script.contains("response:schema:validation"),
            "Script should contain the validation check name"
        );
        assert!(script.contains("try {"), "Script should wrap validation in try-catch");
        assert!(script.contains("res.json()"), "Script should parse response as JSON");
    }

    #[test]
    fn test_annotate_global_security() {
        // Spec with global security requirement, operation without its own security
        let op = Operation::default();
        let mut spec = OpenAPI::default();
        let mut global_req = openapiv3::SecurityRequirement::new();
        global_req.insert("bearerAuth".to_string(), vec![]);
        spec.security = Some(vec![global_req]);
        // Define the security scheme in components
        let mut components = openapiv3::Components::default();
        components.security_schemes.insert(
            "bearerAuth".to_string(),
            ReferenceOr::Item(SecurityScheme::HTTP {
                scheme: "bearer".to_string(),
                bearer_format: Some("JWT".to_string()),
                description: None,
                extensions: Default::default(),
            }),
        );
        spec.components = Some(components);

        let api_op = make_op("get", "/protected", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);

        assert!(
            annotated.features.contains(&ConformanceFeature::SecurityBearer),
            "Should detect SecurityBearer from global security + components"
        );
    }

    #[test]
    fn test_annotate_security_scheme_resolution() {
        // Test that security scheme type is resolved from components, not just name heuristic
        let mut op = Operation::default();
        // Use a generic name that wouldn't match name heuristics
        let mut req = openapiv3::SecurityRequirement::new();
        req.insert("myAuth".to_string(), vec![]);
        op.security = Some(vec![req]);

        let mut spec = OpenAPI::default();
        let mut components = openapiv3::Components::default();
        components.security_schemes.insert(
            "myAuth".to_string(),
            ReferenceOr::Item(SecurityScheme::APIKey {
                location: openapiv3::APIKeyLocation::Header,
                name: "X-API-Key".to_string(),
                description: None,
                extensions: Default::default(),
            }),
        );
        spec.components = Some(components);

        let api_op = make_op("get", "/data", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);

        assert!(
            annotated.features.contains(&ConformanceFeature::SecurityApiKey),
            "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
        );
    }

    #[test]
    fn test_annotate_content_negotiation() {
        let mut op = Operation::default();
        let mut response = Response::default();
        // Response with multiple content types
        response
            .content
            .insert("application/json".to_string(), openapiv3::MediaType::default());
        response
            .content
            .insert("application/xml".to_string(), openapiv3::MediaType::default());
        op.responses
            .responses
            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));

        let api_op = make_op("get", "/items", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(
            annotated.features.contains(&ConformanceFeature::ContentNegotiation),
            "Should detect ContentNegotiation when response has multiple content types"
        );
    }

    #[test]
    fn test_no_content_negotiation_for_single_type() {
        let mut op = Operation::default();
        let mut response = Response::default();
        response
            .content
            .insert("application/json".to_string(), openapiv3::MediaType::default());
        op.responses
            .responses
            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));

        let api_op = make_op("get", "/items", op);
        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());

        assert!(
            !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
            "Should NOT detect ContentNegotiation for a single content type"
        );
    }

    #[test]
    fn test_spec_driven_with_base_path() {
        let annotated = AnnotatedOperation {
            path: "/users".to_string(),
            method: "GET".to_string(),
            features: vec![ConformanceFeature::MethodGet],
            path_params: vec![],
            query_params: vec![],
            header_params: vec![],
            request_body_content_type: None,
            sample_body: None,
            response_schema: None,
            security_schemes: vec![],
        };
        let config = ConformanceConfig {
            target_url: "https://192.168.2.86/".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: true,
            categories: None,
            base_path: Some("/api".to_string()),
            custom_headers: vec![],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
        let (script, _check_count) = gen.generate().unwrap();

        assert!(
            script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
            "BASE_URL should include the base_path. Got: {}",
            script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
        );
    }

    #[test]
    fn test_spec_driven_with_custom_headers() {
        let annotated = AnnotatedOperation {
            path: "/users".to_string(),
            method: "GET".to_string(),
            features: vec![ConformanceFeature::MethodGet],
            path_params: vec![],
            query_params: vec![],
            header_params: vec![
                ("X-Avi-Tenant".to_string(), "test-value".to_string()),
                ("X-CSRFToken".to_string(), "test-value".to_string()),
            ],
            request_body_content_type: None,
            sample_body: None,
            response_schema: None,
            security_schemes: vec![],
        };
        let config = ConformanceConfig {
            target_url: "https://192.168.2.86/".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: true,
            categories: None,
            base_path: Some("/api".to_string()),
            custom_headers: vec![
                ("X-Avi-Tenant".to_string(), "admin".to_string()),
                ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
                ("Cookie".to_string(), "sessionid=abc123".to_string()),
            ],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
        let (script, _check_count) = gen.generate().unwrap();

        // Custom headers should override spec-derived test-value placeholders
        assert!(
            script.contains("'X-Avi-Tenant': 'admin'"),
            "Should use custom value for X-Avi-Tenant, not test-value"
        );
        assert!(
            script.contains("'X-CSRFToken': 'real-csrf-token'"),
            "Should use custom value for X-CSRFToken, not test-value"
        );
        // Custom headers not in spec should be appended
        assert!(
            script.contains("'Cookie': 'sessionid=abc123'"),
            "Should include Cookie header from custom_headers"
        );
        // test-value should NOT appear
        assert!(
            !script.contains("'test-value'"),
            "test-value placeholders should be replaced by custom values"
        );
    }

    #[test]
    fn test_effective_headers_merging() {
        let config = ConformanceConfig {
            target_url: "http://localhost".to_string(),
            api_key: None,
            basic_auth: None,
            skip_tls_verify: false,
            categories: None,
            base_path: None,
            custom_headers: vec![
                ("X-Auth".to_string(), "real-token".to_string()),
                ("Cookie".to_string(), "session=abc".to_string()),
            ],
            output_dir: None,
            all_operations: false,
            custom_checks_file: None,
            request_delay_ms: 0,
            custom_filter: None,
            export_requests: false,
            validate_requests: false,
        };
        let gen = SpecDrivenConformanceGenerator::new(config, vec![]);

        // Spec headers with a matching custom header
        let spec_headers = vec![
            ("X-Auth".to_string(), "test-value".to_string()),
            ("X-Other".to_string(), "keep-this".to_string()),
        ];
        let effective = gen.effective_headers(&spec_headers);

        // X-Auth should be overridden
        assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
        // X-Other should be kept as-is
        assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
        // Cookie should be appended
        assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
    }
}