mockforge-core 0.3.114

Shared logic for MockForge - routing, validation, latency, proxy
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
//! Contract fitness functions for validating contract changes
//!
//! Fitness functions allow teams to register custom tests that run against each new contract version.
//! These tests can enforce constraints like "response size must not increase by > 25%" or
//! "no new required fields under /v1/mobile/*".

use crate::ai_contract_diff::{ContractDiffResult, MismatchType};
use crate::openapi::OpenApiSpec;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// A fitness function that evaluates contract changes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FitnessFunction {
    /// Unique identifier for this fitness function
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Description of what this fitness function checks
    pub description: String,
    /// Type of fitness function
    pub function_type: FitnessFunctionType,
    /// Additional configuration (JSON)
    pub config: serde_json::Value,
    /// Scope where this function applies
    pub scope: FitnessScope,
    /// Whether this function is enabled
    pub enabled: bool,
    /// Timestamp when this function was created
    #[serde(default)]
    pub created_at: i64,
    /// Timestamp when this function was last updated
    #[serde(default)]
    pub updated_at: i64,
}

/// Scope where a fitness function applies
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FitnessScope {
    /// Applies globally to all endpoints
    Global,
    /// Applies to a specific workspace
    Workspace {
        /// The workspace ID
        workspace_id: String,
    },
    /// Applies to a specific service (by OpenAPI tag or service name)
    Service {
        /// The service name or OpenAPI tag
        service_name: String,
    },
    /// Applies to a specific endpoint pattern (e.g., "/v1/mobile/*")
    Endpoint {
        /// The endpoint pattern (supports * wildcard)
        pattern: String,
    },
}

/// Type of fitness function
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FitnessFunctionType {
    /// Response size must not increase by more than a percentage
    ResponseSize {
        /// Maximum allowed increase percentage (e.g., 25.0 for 25%)
        max_increase_percent: f64,
    },
    /// No new required fields under a path pattern
    RequiredField {
        /// Path pattern to check (e.g., "/v1/mobile/*")
        path_pattern: String,
        /// Whether new required fields are allowed
        allow_new_required: bool,
    },
    /// Field count must not exceed a threshold
    FieldCount {
        /// Maximum number of fields allowed
        max_fields: u32,
    },
    /// Schema complexity (depth) must not exceed a threshold
    SchemaComplexity {
        /// Maximum schema depth allowed
        max_depth: u32,
    },
    /// Custom fitness function (for future plugin support)
    Custom {
        /// Identifier for the custom evaluator
        evaluator: String,
    },
}

/// Result of evaluating a fitness function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FitnessTestResult {
    /// ID of the fitness function that was evaluated
    pub function_id: String,
    /// Name of the fitness function
    pub function_name: String,
    /// Whether the test passed
    pub passed: bool,
    /// Human-readable message about the result
    pub message: String,
    /// Metrics collected during evaluation (e.g., "response_size": 1024.0, "increase_percent": 15.5)
    pub metrics: HashMap<String, f64>,
}

/// Trait for evaluating fitness functions
pub trait FitnessEvaluator: Send + Sync {
    /// Evaluate the fitness function against contract changes (OpenAPI/HTTP)
    ///
    /// # Arguments
    ///
    /// * `old_spec` - The previous contract specification (if available)
    /// * `new_spec` - The new contract specification
    /// * `diff_result` - The contract diff result showing changes
    /// * `endpoint` - The endpoint being evaluated
    /// * `method` - The HTTP method
    /// * `config` - Additional configuration for the fitness function
    ///
    /// # Returns
    ///
    /// A `FitnessTestResult` indicating whether the test passed
    fn evaluate(
        &self,
        old_spec: Option<&OpenApiSpec>,
        new_spec: &OpenApiSpec,
        diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult>;

    /// Evaluate the fitness function against protocol contract changes (gRPC, WebSocket, MQTT, etc.)
    ///
    /// # Arguments
    ///
    /// * `old_contract` - The previous protocol contract (if available)
    /// * `new_contract` - The new protocol contract
    /// * `diff_result` - The contract diff result showing changes
    /// * `operation_id` - The operation identifier (method, topic, etc.)
    /// * `config` - Additional configuration for the fitness function
    ///
    /// # Returns
    ///
    /// A `FitnessTestResult` indicating whether the test passed
    fn evaluate_protocol(
        &self,
        old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        diff_result: &ContractDiffResult,
        operation_id: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Generic protocol evaluation fallback based on schema size drift.
        let max_increase_percent =
            config.get("max_increase_percent").and_then(|v| v.as_f64()).unwrap_or(50.0);
        let old_size = old_contract
            .map(|old| estimate_protocol_schema_size(old, operation_id))
            .unwrap_or_else(|| estimate_size_from_diff(diff_result));
        let new_size = estimate_protocol_schema_size(new_contract, operation_id);
        let increase_percent = if old_size > 0.0 {
            ((new_size - old_size) / old_size) * 100.0
        } else if new_size > 0.0 {
            100.0
        } else {
            0.0
        };
        let passed = increase_percent <= max_increase_percent;

        let mut metrics = HashMap::new();
        metrics.insert("old_schema_size".to_string(), old_size);
        metrics.insert("new_schema_size".to_string(), new_size);
        metrics.insert("increase_percent".to_string(), increase_percent);
        metrics.insert("max_increase_percent".to_string(), max_increase_percent);
        metrics.insert("mismatch_count".to_string(), diff_result.mismatches.len() as f64);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Protocol Contract Evaluation".to_string(),
            passed,
            message: if passed {
                format!(
                    "Protocol schema change ({:.1}%) is within allowed limit ({:.1}%)",
                    increase_percent, max_increase_percent
                )
            } else {
                format!(
                    "Protocol schema change ({:.1}%) exceeds allowed limit ({:.1}%)",
                    increase_percent, max_increase_percent
                )
            },
            metrics,
        })
    }
}

/// Response size fitness evaluator
pub struct ResponseSizeFitnessEvaluator;

impl FitnessEvaluator for ResponseSizeFitnessEvaluator {
    fn evaluate(
        &self,
        old_spec: Option<&OpenApiSpec>,
        _new_spec: &OpenApiSpec,
        diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_increase_percent from config
        let max_increase_percent =
            config.get("max_increase_percent").and_then(|v| v.as_f64()).unwrap_or(25.0);

        // For now, we'll estimate response size based on field count
        // In a real implementation, we might analyze actual response schemas
        let old_field_count = if let Some(old) = old_spec {
            // Estimate based on old spec - count fields in response schema
            estimate_response_field_count(old, endpoint, method)
        } else {
            // No old spec, assume baseline from current mismatches
            diff_result.mismatches.len() as f64
        };

        let new_field_count =
            estimate_response_field_count_from_diff(diff_result, endpoint, method);

        let increase_percent = if old_field_count > 0.0 {
            ((new_field_count - old_field_count) / old_field_count) * 100.0
        } else if new_field_count > 0.0 {
            100.0 // 100% increase from zero
        } else {
            0.0 // No change
        };

        let passed = increase_percent <= max_increase_percent;
        let message = if passed {
            format!(
                "Response size increase ({:.1}%) is within allowed limit ({:.1}%)",
                increase_percent, max_increase_percent
            )
        } else {
            format!(
                "Response size increase ({:.1}%) exceeds allowed limit ({:.1}%)",
                increase_percent, max_increase_percent
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("old_field_count".to_string(), old_field_count);
        metrics.insert("new_field_count".to_string(), new_field_count);
        metrics.insert("increase_percent".to_string(), increase_percent);
        metrics.insert("max_increase_percent".to_string(), max_increase_percent);

        Ok(FitnessTestResult {
            function_id: String::new(), // Will be set by caller
            function_name: "Response Size".to_string(),
            passed,
            message,
            metrics,
        })
    }

    fn evaluate_protocol(
        &self,
        old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        diff_result: &ContractDiffResult,
        operation_id: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_increase_percent from config
        let max_increase_percent =
            config.get("max_increase_percent").and_then(|v| v.as_f64()).unwrap_or(25.0);

        // Estimate response size based on schema complexity from protocol contract
        let old_size = if let Some(old) = old_contract {
            estimate_protocol_schema_size(old, operation_id)
        } else {
            // No old contract, estimate from diff
            estimate_size_from_diff(diff_result)
        };

        let new_size = estimate_protocol_schema_size(new_contract, operation_id);

        let increase_percent = if old_size > 0.0 {
            ((new_size - old_size) / old_size) * 100.0
        } else if new_size > 0.0 {
            100.0 // 100% increase from zero
        } else {
            0.0 // No change
        };

        let passed = increase_percent <= max_increase_percent;
        let message = if passed {
            format!(
                "Protocol contract response size increase ({:.1}%) is within allowed limit ({:.1}%)",
                increase_percent, max_increase_percent
            )
        } else {
            format!(
                "Protocol contract response size increase ({:.1}%) exceeds allowed limit ({:.1}%)",
                increase_percent, max_increase_percent
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("old_size".to_string(), old_size);
        metrics.insert("new_size".to_string(), new_size);
        metrics.insert("increase_percent".to_string(), increase_percent);
        metrics.insert("max_increase_percent".to_string(), max_increase_percent);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Response Size".to_string(),
            passed,
            message,
            metrics,
        })
    }
}

/// Required field fitness evaluator
pub struct RequiredFieldFitnessEvaluator;

impl FitnessEvaluator for RequiredFieldFitnessEvaluator {
    fn evaluate(
        &self,
        _old_spec: Option<&OpenApiSpec>,
        _new_spec: &OpenApiSpec,
        diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract path_pattern and allow_new_required from config
        let path_pattern = config.get("path_pattern").and_then(|v| v.as_str()).unwrap_or("*");
        let allow_new_required =
            config.get("allow_new_required").and_then(|v| v.as_bool()).unwrap_or(false);

        // Check if endpoint matches pattern
        let matches_pattern = matches_pattern(endpoint, path_pattern);

        if !matches_pattern {
            // This fitness function doesn't apply to this endpoint
            return Ok(FitnessTestResult {
                function_id: String::new(),
                function_name: "Required Field".to_string(),
                passed: true,
                message: format!("Endpoint {} does not match pattern {}", endpoint, path_pattern),
                metrics: HashMap::new(),
            });
        }

        // Count new required fields from mismatches
        let new_required_fields = diff_result
            .mismatches
            .iter()
            .filter(|m| {
                m.mismatch_type == MismatchType::MissingRequiredField
                    && m.method.as_deref() == Some(method)
            })
            .count();

        let passed = allow_new_required || new_required_fields == 0;
        let message = if passed {
            if allow_new_required {
                format!("Found {} new required fields, which is allowed", new_required_fields)
            } else {
                "No new required fields detected".to_string()
            }
        } else {
            format!(
                "Found {} new required fields, which violates the fitness function",
                new_required_fields
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("new_required_fields".to_string(), new_required_fields as f64);
        metrics
            .insert("allow_new_required".to_string(), if allow_new_required { 1.0 } else { 0.0 });

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Required Field".to_string(),
            passed,
            message,
            metrics,
        })
    }

    fn evaluate_protocol(
        &self,
        _old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        diff_result: &ContractDiffResult,
        operation_id: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract path_pattern and allow_new_required from config
        let path_pattern = config.get("path_pattern").and_then(|v| v.as_str()).unwrap_or("*");
        let allow_new_required =
            config.get("allow_new_required").and_then(|v| v.as_bool()).unwrap_or(false);

        // For protocol contracts, check if operation ID matches pattern
        // Operation ID format varies by protocol (e.g., "service.method" for gRPC, "topic" for MQTT)
        let matches = matches_pattern(operation_id, path_pattern) || path_pattern == "*";

        if !matches {
            return Ok(FitnessTestResult {
                function_id: String::new(),
                function_name: "Required Field".to_string(),
                passed: true,
                message: format!(
                    "Operation {} does not match pattern {}",
                    operation_id, path_pattern
                ),
                metrics: HashMap::new(),
            });
        }

        // Count new required fields from mismatches
        let new_required_fields = diff_result
            .mismatches
            .iter()
            .filter(|m| m.mismatch_type == MismatchType::MissingRequiredField)
            .count();

        // Also check schema for required fields
        let schema_required_fields = if let Some(schema) = new_contract.get_schema(operation_id) {
            count_required_fields_in_schema(&schema)
        } else {
            0
        };

        let total_new_required = new_required_fields + schema_required_fields;
        let passed = allow_new_required || total_new_required == 0;
        let message = if passed {
            if allow_new_required {
                format!("Found {} new required fields, which is allowed", total_new_required)
            } else {
                "No new required fields detected in protocol contract".to_string()
            }
        } else {
            format!(
                "Found {} new required fields in protocol contract, which violates the fitness function",
                total_new_required
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("new_required_fields".to_string(), total_new_required as f64);
        metrics
            .insert("allow_new_required".to_string(), if allow_new_required { 1.0 } else { 0.0 });

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Required Field".to_string(),
            passed,
            message,
            metrics,
        })
    }
}

/// Field count fitness evaluator
pub struct FieldCountFitnessEvaluator;

impl FitnessEvaluator for FieldCountFitnessEvaluator {
    fn evaluate(
        &self,
        _old_spec: Option<&OpenApiSpec>,
        _new_spec: &OpenApiSpec,
        diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_fields from config
        let max_fields = config
            .get("max_fields")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32)
            .unwrap_or(100);

        // Estimate field count from diff result
        let field_count = estimate_field_count_from_diff(diff_result, endpoint, method);

        let passed = field_count <= max_fields as f64;
        let message = if passed {
            format!("Field count ({}) is within allowed limit ({})", field_count as u32, max_fields)
        } else {
            format!("Field count ({}) exceeds allowed limit ({})", field_count as u32, max_fields)
        };

        let mut metrics = HashMap::new();
        metrics.insert("field_count".to_string(), field_count);
        metrics.insert("max_fields".to_string(), max_fields as f64);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Field Count".to_string(),
            passed,
            message,
            metrics,
        })
    }

    fn evaluate_protocol(
        &self,
        _old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        _diff_result: &ContractDiffResult,
        operation_id: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_fields from config
        let max_fields = config
            .get("max_fields")
            .and_then(|v| v.as_u64())
            .map(|v| v as u32)
            .unwrap_or(100);

        // Count fields in protocol contract schema
        let field_count = if let Some(schema) = new_contract.get_schema(operation_id) {
            count_fields_in_schema(&schema)
        } else {
            0.0
        };

        let passed = field_count <= max_fields as f64;
        let message = if passed {
            format!(
                "Protocol contract field count ({}) is within allowed limit ({})",
                field_count as u32, max_fields
            )
        } else {
            format!(
                "Protocol contract field count ({}) exceeds allowed limit ({})",
                field_count as u32, max_fields
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("field_count".to_string(), field_count);
        metrics.insert("max_fields".to_string(), max_fields as f64);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Field Count".to_string(),
            passed,
            message,
            metrics,
        })
    }
}

/// Schema complexity fitness evaluator
pub struct SchemaComplexityFitnessEvaluator;

impl FitnessEvaluator for SchemaComplexityFitnessEvaluator {
    fn evaluate(
        &self,
        _old_spec: Option<&OpenApiSpec>,
        new_spec: &OpenApiSpec,
        _diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_depth from config
        let max_depth =
            config.get("max_depth").and_then(|v| v.as_u64()).map(|v| v as u32).unwrap_or(10);

        // Calculate schema depth for the endpoint
        let depth = calculate_schema_depth(new_spec, endpoint, method);

        let passed = depth <= max_depth;
        let message = if passed {
            format!("Schema depth ({}) is within allowed limit ({})", depth, max_depth)
        } else {
            format!("Schema depth ({}) exceeds allowed limit ({})", depth, max_depth)
        };

        let mut metrics = HashMap::new();
        metrics.insert("schema_depth".to_string(), depth as f64);
        metrics.insert("max_depth".to_string(), max_depth as f64);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Schema Complexity".to_string(),
            passed,
            message,
            metrics,
        })
    }

    fn evaluate_protocol(
        &self,
        _old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        _diff_result: &ContractDiffResult,
        operation_id: &str,
        config: &serde_json::Value,
    ) -> crate::Result<FitnessTestResult> {
        // Extract max_depth from config
        let max_depth =
            config.get("max_depth").and_then(|v| v.as_u64()).map(|v| v as u32).unwrap_or(10);

        // Calculate schema depth for protocol contract
        let depth = if let Some(schema) = new_contract.get_schema(operation_id) {
            calculate_protocol_schema_depth(&schema)
        } else {
            0
        };

        let passed = depth <= max_depth;
        let message = if passed {
            format!(
                "Protocol contract schema depth ({}) is within allowed limit ({})",
                depth, max_depth
            )
        } else {
            format!(
                "Protocol contract schema depth ({}) exceeds allowed limit ({})",
                depth, max_depth
            )
        };

        let mut metrics = HashMap::new();
        metrics.insert("schema_depth".to_string(), depth as f64);
        metrics.insert("max_depth".to_string(), max_depth as f64);

        Ok(FitnessTestResult {
            function_id: String::new(),
            function_name: "Schema Complexity".to_string(),
            passed,
            message,
            metrics,
        })
    }
}

/// Registry for managing fitness functions
pub struct FitnessFunctionRegistry {
    /// Registered fitness functions
    functions: HashMap<String, FitnessFunction>,
    /// Evaluators for each function type
    evaluators: HashMap<String, Arc<dyn FitnessEvaluator>>,
}

impl std::fmt::Debug for FitnessFunctionRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FitnessFunctionRegistry")
            .field("functions", &self.functions)
            .field("evaluators_count", &self.evaluators.len())
            .finish()
    }
}

impl Default for FitnessFunctionRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl FitnessFunctionRegistry {
    /// Create a new fitness function registry
    pub fn new() -> Self {
        let mut registry = Self {
            functions: HashMap::new(),
            evaluators: HashMap::new(),
        };

        // Register built-in evaluators
        registry.register_evaluator(
            "response_size",
            Arc::new(ResponseSizeFitnessEvaluator) as Arc<dyn FitnessEvaluator>,
        );
        registry.register_evaluator(
            "required_field",
            Arc::new(RequiredFieldFitnessEvaluator) as Arc<dyn FitnessEvaluator>,
        );
        registry.register_evaluator(
            "field_count",
            Arc::new(FieldCountFitnessEvaluator) as Arc<dyn FitnessEvaluator>,
        );
        registry.register_evaluator(
            "schema_complexity",
            Arc::new(SchemaComplexityFitnessEvaluator) as Arc<dyn FitnessEvaluator>,
        );

        registry
    }

    /// Register a fitness function evaluator
    pub fn register_evaluator(&mut self, name: &str, evaluator: Arc<dyn FitnessEvaluator>) {
        self.evaluators.insert(name.to_string(), evaluator);
    }

    /// Add a fitness function to the registry
    pub fn add_function(&mut self, function: FitnessFunction) {
        self.functions.insert(function.id.clone(), function);
    }

    /// Get a fitness function by ID
    pub fn get_function(&self, id: &str) -> Option<&FitnessFunction> {
        self.functions.get(id)
    }

    /// List all fitness functions
    pub fn list_functions(&self) -> Vec<&FitnessFunction> {
        self.functions.values().collect()
    }

    /// Get fitness functions that apply to a given scope
    pub fn get_functions_for_scope(
        &self,
        endpoint: &str,
        method: &str,
        workspace_id: Option<&str>,
        service_name: Option<&str>,
    ) -> Vec<&FitnessFunction> {
        self.functions
            .values()
            .filter(|f| {
                f.enabled && self.matches_scope(f, endpoint, method, workspace_id, service_name)
            })
            .collect()
    }

    /// Evaluate all applicable fitness functions
    #[allow(clippy::too_many_arguments)]
    pub fn evaluate_all(
        &self,
        old_spec: Option<&OpenApiSpec>,
        new_spec: &OpenApiSpec,
        diff_result: &ContractDiffResult,
        endpoint: &str,
        method: &str,
        workspace_id: Option<&str>,
        service_name: Option<&str>,
    ) -> crate::Result<Vec<FitnessTestResult>> {
        let functions = self.get_functions_for_scope(endpoint, method, workspace_id, service_name);
        let mut results = Vec::new();

        for function in functions {
            let evaluator_name = match &function.function_type {
                FitnessFunctionType::ResponseSize { .. } => "response_size",
                FitnessFunctionType::RequiredField { .. } => "required_field",
                FitnessFunctionType::FieldCount { .. } => "field_count",
                FitnessFunctionType::SchemaComplexity { .. } => "schema_complexity",
                FitnessFunctionType::Custom { evaluator } => evaluator.as_str(),
            };

            if let Some(evaluator) = self.evaluators.get(evaluator_name) {
                let mut result = evaluator.evaluate(
                    old_spec,
                    new_spec,
                    diff_result,
                    endpoint,
                    method,
                    &function.config,
                )?;
                result.function_id = function.id.clone();
                result.function_name = function.name.clone();
                results.push(result);
            }
        }

        Ok(results)
    }

    /// Evaluate all applicable fitness functions for a protocol contract
    ///
    /// This method evaluates fitness functions against protocol contracts (gRPC, WebSocket, MQTT, etc.)
    pub fn evaluate_all_protocol(
        &self,
        old_contract: Option<&dyn crate::contract_drift::protocol_contracts::ProtocolContract>,
        new_contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
        diff_result: &ContractDiffResult,
        operation_id: &str,
        workspace_id: Option<&str>,
        service_name: Option<&str>,
    ) -> crate::Result<Vec<FitnessTestResult>> {
        // Get operation to determine endpoint/method for scope matching
        let operation = new_contract.get_operation(operation_id);
        let (endpoint, method) = if let Some(op) = operation {
            match &op.operation_type {
                crate::contract_drift::protocol_contracts::OperationType::HttpEndpoint {
                    path,
                    method,
                } => (path.clone(), method.clone()),
                crate::contract_drift::protocol_contracts::OperationType::GrpcMethod {
                    service,
                    method,
                } => {
                    // For gRPC, use service.method as endpoint
                    (format!("{}.{}", service, method), "grpc".to_string())
                }
                crate::contract_drift::protocol_contracts::OperationType::WebSocketMessage {
                    message_type,
                    ..
                } => (message_type.clone(), "websocket".to_string()),
                crate::contract_drift::protocol_contracts::OperationType::MqttTopic {
                    topic,
                    qos: _,
                } => (topic.clone(), "mqtt".to_string()),
                crate::contract_drift::protocol_contracts::OperationType::KafkaTopic {
                    topic,
                    key_schema: _,
                    value_schema: _,
                } => (topic.clone(), "kafka".to_string()),
            }
        } else {
            (operation_id.to_string(), "unknown".to_string())
        };

        let functions =
            self.get_functions_for_scope(&endpoint, &method, workspace_id, service_name);
        let mut results = Vec::new();

        for function in functions {
            let evaluator_name = match &function.function_type {
                FitnessFunctionType::ResponseSize { .. } => "response_size",
                FitnessFunctionType::RequiredField { .. } => "required_field",
                FitnessFunctionType::FieldCount { .. } => "field_count",
                FitnessFunctionType::SchemaComplexity { .. } => "schema_complexity",
                FitnessFunctionType::Custom { evaluator } => evaluator.as_str(),
            };

            if let Some(evaluator) = self.evaluators.get(evaluator_name) {
                let mut result = evaluator.evaluate_protocol(
                    old_contract,
                    new_contract,
                    diff_result,
                    operation_id,
                    &function.config,
                )?;
                result.function_id = function.id.clone();
                result.function_name = function.name.clone();
                results.push(result);
            }
        }

        Ok(results)
    }

    /// Check if a fitness function's scope matches the given context
    fn matches_scope(
        &self,
        function: &FitnessFunction,
        endpoint: &str,
        _method: &str,
        workspace_id: Option<&str>,
        service_name: Option<&str>,
    ) -> bool {
        match &function.scope {
            FitnessScope::Global => true,
            FitnessScope::Workspace {
                workspace_id: ws_id,
            } => workspace_id.map(|id| id == ws_id).unwrap_or(false),
            FitnessScope::Service {
                service_name: svc_name,
            } => service_name.map(|name| name == svc_name).unwrap_or(false),
            FitnessScope::Endpoint { pattern } => matches_pattern(endpoint, pattern),
        }
    }

    /// Remove a fitness function
    pub fn remove_function(&mut self, id: &str) -> Option<FitnessFunction> {
        self.functions.remove(id)
    }

    /// Update a fitness function
    pub fn update_function(&mut self, function: FitnessFunction) {
        self.functions.insert(function.id.clone(), function);
    }

    /// Load fitness rules from config into the registry
    ///
    /// This converts YAML config fitness rules into FitnessFunction instances
    /// and adds them to the registry.
    ///
    /// Validates that:
    /// - Required fields are present for each rule type
    /// - Unnecessary fields are not provided (warns but doesn't fail)
    /// - Field values are within valid ranges
    pub fn load_from_config(
        &mut self,
        config_rules: &[crate::config::FitnessRuleConfig],
    ) -> crate::Result<()> {
        use crate::config::FitnessRuleType;

        for (idx, rule_config) in config_rules.iter().enumerate() {
            // Generate a stable ID based on index and name
            let id = format!("config-rule-{}", idx);

            // Parse scope string into FitnessScope
            let scope = parse_scope(&rule_config.scope)?;

            // Convert rule type and create function type with validation
            let function_type = match rule_config.rule_type {
                FitnessRuleType::ResponseSizeDelta => {
                    // Validate required field
                    let max_increase = rule_config
                        .max_percent_increase
                        .ok_or_else(|| {
                            crate::Error::validation(format!(
                                "Fitness rule '{}' (type: response_size_delta) requires 'max_percent_increase' field. \
                                Example: max_percent_increase: 25.0",
                                rule_config.name
                            ))
                        })?;

                    // Validate value range
                    if max_increase < 0.0 {
                        return Err(crate::Error::validation(format!(
                            "Fitness rule '{}' (type: response_size_delta): 'max_percent_increase' must be >= 0, got {}",
                            rule_config.name, max_increase
                        )));
                    }

                    // Warn about unnecessary fields
                    if rule_config.max_fields.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: response_size_delta): 'max_fields' is not used for this rule type",
                            rule_config.name
                        );
                    }
                    if rule_config.max_depth.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: response_size_delta): 'max_depth' is not used for this rule type",
                            rule_config.name
                        );
                    }

                    FitnessFunctionType::ResponseSize {
                        max_increase_percent: max_increase,
                    }
                }
                FitnessRuleType::NoNewRequiredFields => {
                    // Extract path pattern from scope if it's an endpoint scope
                    let path_pattern = match &scope {
                        FitnessScope::Endpoint { pattern } => pattern.clone(),
                        _ => "*".to_string(), // Default to all endpoints if scope is global/service
                    };

                    // Warn about unnecessary fields
                    if rule_config.max_percent_increase.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: no_new_required_fields): 'max_percent_increase' is not used for this rule type",
                            rule_config.name
                        );
                    }
                    if rule_config.max_fields.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: no_new_required_fields): 'max_fields' is not used for this rule type",
                            rule_config.name
                        );
                    }
                    if rule_config.max_depth.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: no_new_required_fields): 'max_depth' is not used for this rule type",
                            rule_config.name
                        );
                    }

                    FitnessFunctionType::RequiredField {
                        path_pattern,
                        allow_new_required: false,
                    }
                }
                FitnessRuleType::FieldCount => {
                    // Validate required field
                    let max_fields = rule_config.max_fields.ok_or_else(|| {
                        crate::Error::validation(format!(
                            "Fitness rule '{}' (type: field_count) requires 'max_fields' field. \
                            Example: max_fields: 50",
                            rule_config.name
                        ))
                    })?;

                    // Validate value range
                    if max_fields == 0 {
                        return Err(crate::Error::validation(format!(
                            "Fitness rule '{}' (type: field_count): 'max_fields' must be > 0, got {}",
                            rule_config.name, max_fields
                        )));
                    }

                    // Warn about unnecessary fields
                    if rule_config.max_percent_increase.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: field_count): 'max_percent_increase' is not used for this rule type",
                            rule_config.name
                        );
                    }
                    if rule_config.max_depth.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: field_count): 'max_depth' is not used for this rule type",
                            rule_config.name
                        );
                    }

                    FitnessFunctionType::FieldCount { max_fields }
                }
                FitnessRuleType::SchemaComplexity => {
                    // Validate required field
                    let max_depth = rule_config.max_depth.ok_or_else(|| {
                        crate::Error::validation(format!(
                            "Fitness rule '{}' (type: schema_complexity) requires 'max_depth' field. \
                            Example: max_depth: 5",
                            rule_config.name
                        ))
                    })?;

                    // Validate value range
                    if max_depth == 0 {
                        return Err(crate::Error::validation(format!(
                            "Fitness rule '{}' (type: schema_complexity): 'max_depth' must be > 0, got {}",
                            rule_config.name, max_depth
                        )));
                    }

                    // Warn about unnecessary fields
                    if rule_config.max_percent_increase.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: schema_complexity): 'max_percent_increase' is not used for this rule type",
                            rule_config.name
                        );
                    }
                    if rule_config.max_fields.is_some() {
                        tracing::warn!(
                            "Fitness rule '{}' (type: schema_complexity): 'max_fields' is not used for this rule type",
                            rule_config.name
                        );
                    }

                    FitnessFunctionType::SchemaComplexity { max_depth }
                }
            };

            // Create config JSON
            let config_json = match &function_type {
                FitnessFunctionType::ResponseSize {
                    max_increase_percent,
                } => {
                    serde_json::json!({
                        "max_increase_percent": max_increase_percent
                    })
                }
                FitnessFunctionType::RequiredField {
                    path_pattern,
                    allow_new_required,
                } => {
                    serde_json::json!({
                        "path_pattern": path_pattern,
                        "allow_new_required": allow_new_required
                    })
                }
                FitnessFunctionType::FieldCount { max_fields } => {
                    serde_json::json!({
                        "max_fields": max_fields
                    })
                }
                FitnessFunctionType::SchemaComplexity { max_depth } => {
                    serde_json::json!({
                        "max_depth": max_depth
                    })
                }
                FitnessFunctionType::Custom { .. } => {
                    serde_json::json!({})
                }
            };

            let function = FitnessFunction {
                id,
                name: rule_config.name.clone(),
                description: format!("Fitness rule: {}", rule_config.name),
                function_type,
                config: config_json,
                scope,
                enabled: true,
                created_at: chrono::Utc::now().timestamp(),
                updated_at: chrono::Utc::now().timestamp(),
            };

            self.add_function(function);
        }

        Ok(())
    }
}

/// Parse a scope string into a FitnessScope enum
///
/// Supports:
/// - "global" -> FitnessScope::Global
/// - "/v1/mobile/*" -> FitnessScope::Endpoint { pattern: "/v1/mobile/*" }
/// - "service:user-service" -> FitnessScope::Service { service_name: "user-service" }
/// - "workspace:prod" -> FitnessScope::Workspace { workspace_id: "prod" }
fn parse_scope(scope_str: &str) -> crate::Result<FitnessScope> {
    let scope_str = scope_str.trim();

    if scope_str == "global" {
        return Ok(FitnessScope::Global);
    }

    // Check for workspace: prefix
    if let Some(workspace_id) = scope_str.strip_prefix("workspace:") {
        return Ok(FitnessScope::Workspace {
            workspace_id: workspace_id.to_string(),
        });
    }

    // Check for service: prefix
    if let Some(service_name) = scope_str.strip_prefix("service:") {
        return Ok(FitnessScope::Service {
            service_name: service_name.to_string(),
        });
    }

    // Otherwise, treat as endpoint pattern
    Ok(FitnessScope::Endpoint {
        pattern: scope_str.to_string(),
    })
}

// Helper functions

/// Check if an endpoint matches a pattern (supports * wildcard)
fn matches_pattern(endpoint: &str, pattern: &str) -> bool {
    if pattern == "*" {
        return true;
    }

    // Simple wildcard matching: convert pattern to regex-like matching
    let pattern_parts: Vec<&str> = pattern.split('*').collect();
    if pattern_parts.len() == 1 {
        // No wildcard, exact match
        return endpoint == pattern;
    }

    // Check if endpoint starts with first part and ends with last part
    if let (Some(first), Some(last)) = (pattern_parts.first(), pattern_parts.last()) {
        endpoint.starts_with(first) && endpoint.ends_with(last)
    } else {
        false
    }
}

/// Estimate response field count from OpenAPI spec
fn estimate_response_field_count(spec: &OpenApiSpec, endpoint: &str, method: &str) -> f64 {
    let mut visited = std::collections::HashSet::new();
    extract_response_schema(spec, endpoint, method)
        .map(|schema| count_fields_in_schema_resolved(schema, spec, &mut visited))
        .filter(|count| *count > 0.0)
        .unwrap_or(10.0)
}

/// Estimate response field count from diff result
fn estimate_response_field_count_from_diff(
    diff_result: &ContractDiffResult,
    _endpoint: &str,
    _method: &str,
) -> f64 {
    // Estimate based on number of mismatches and corrections
    // This is a simplified approach
    let base_count = 10.0;
    let mismatch_count = diff_result.mismatches.len() as f64;
    base_count + mismatch_count
}

/// Estimate field count from diff result
fn estimate_field_count_from_diff(
    diff_result: &ContractDiffResult,
    _endpoint: &str,
    _method: &str,
) -> f64 {
    // Count unique paths in mismatches
    let unique_paths: std::collections::HashSet<String> = diff_result
        .mismatches
        .iter()
        .map(|m| {
            // Extract base path (before any array indices or property names)
            m.path.split('.').next().unwrap_or("").to_string()
        })
        .collect();

    unique_paths.len() as f64 + 10.0 // Add base estimate
}

/// Calculate schema depth for an endpoint
fn calculate_schema_depth(spec: &OpenApiSpec, endpoint: &str, method: &str) -> u32 {
    let mut visited = std::collections::HashSet::new();
    extract_response_schema(spec, endpoint, method)
        .map(|schema| schema_depth_resolved(schema, spec, &mut visited))
        .filter(|depth| *depth > 0)
        .unwrap_or(5)
}

/// Resolve endpoint/method response schema from OpenAPI raw document.
fn extract_response_schema<'a>(
    spec: &'a OpenApiSpec,
    endpoint: &str,
    method: &str,
) -> Option<&'a serde_json::Value> {
    let raw = spec.raw_document.as_ref()?;
    let paths = raw.get("paths")?.as_object()?;
    let path_item = paths.get(endpoint)?;
    let operation = path_item.get(method.to_lowercase())?;
    let responses = operation.get("responses")?.as_object()?;

    let response = responses
        .get("200")
        .or_else(|| responses.get("201"))
        .or_else(|| responses.get("default"))
        .or_else(|| responses.values().next())?;

    let content = response.get("content")?.as_object()?;
    let media_type = content.get("application/json").or_else(|| content.values().next())?;
    media_type.get("schema")
}

/// Resolve a local JSON pointer reference from an OpenAPI raw document.
fn resolve_local_ref<'a>(spec: &'a OpenApiSpec, reference: &str) -> Option<&'a serde_json::Value> {
    let pointer = reference.strip_prefix('#')?;
    spec.raw_document.as_ref()?.pointer(pointer)
}

fn count_fields_in_schema_resolved(
    schema: &serde_json::Value,
    spec: &OpenApiSpec,
    visited: &mut std::collections::HashSet<String>,
) -> f64 {
    if let Some(reference) = schema.get("$ref").and_then(|r| r.as_str()) {
        if !visited.insert(reference.to_string()) {
            return 0.0;
        }
        return resolve_local_ref(spec, reference)
            .map(|resolved| count_fields_in_schema_resolved(resolved, spec, visited))
            .unwrap_or(0.0);
    }

    let mut total = 0.0;
    if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
        total += properties.len() as f64;
        for prop in properties.values() {
            total += count_fields_in_schema_resolved(prop, spec, visited);
        }
    }
    if let Some(fields) = schema.get("fields").and_then(|f| f.as_array()) {
        total += fields.len() as f64;
        for field in fields {
            total += count_fields_in_schema_resolved(field, spec, visited);
        }
    }
    if let Some(items) = schema.get("items") {
        total += count_fields_in_schema_resolved(items, spec, visited);
    }
    for key in ["oneOf", "anyOf", "allOf"] {
        if let Some(variants) = schema.get(key).and_then(|v| v.as_array()) {
            for variant in variants {
                total += count_fields_in_schema_resolved(variant, spec, visited);
            }
        }
    }
    total
}

fn schema_depth_resolved(
    schema: &serde_json::Value,
    spec: &OpenApiSpec,
    visited: &mut std::collections::HashSet<String>,
) -> u32 {
    if let Some(reference) = schema.get("$ref").and_then(|r| r.as_str()) {
        if !visited.insert(reference.to_string()) {
            return 0;
        }
        return resolve_local_ref(spec, reference)
            .map(|resolved| schema_depth_resolved(resolved, spec, visited))
            .unwrap_or(0);
    }

    let mut max_child = 0u32;
    if let Some(properties) = schema.get("properties").and_then(|p| p.as_object()) {
        for prop in properties.values() {
            max_child = max_child.max(schema_depth_resolved(prop, spec, visited));
        }
    }
    if let Some(items) = schema.get("items") {
        max_child = max_child.max(schema_depth_resolved(items, spec, visited));
    }
    for key in ["oneOf", "anyOf", "allOf"] {
        if let Some(variants) = schema.get(key).and_then(|v| v.as_array()) {
            for variant in variants {
                max_child = max_child.max(schema_depth_resolved(variant, spec, visited));
            }
        }
    }

    let is_object_like = schema.get("properties").is_some()
        || schema
            .get("type")
            .and_then(|t| t.as_str())
            .map(|t| t == "object" || t == "array")
            .unwrap_or(false);

    if is_object_like {
        1 + max_child
    } else {
        max_child
    }
}

/// Estimate schema size for a protocol contract operation
fn estimate_protocol_schema_size(
    contract: &dyn crate::contract_drift::protocol_contracts::ProtocolContract,
    operation_id: &str,
) -> f64 {
    // Get the operation schema
    if let Some(schema) = contract.get_schema(operation_id) {
        // Estimate size based on schema complexity
        // Count fields in the output schema
        if let Some(output_schema) = schema.get("output_schema") {
            count_fields_in_schema(output_schema)
        } else if let Some(input_schema) = schema.get("input_schema") {
            count_fields_in_schema(input_schema)
        } else {
            // Fallback: estimate based on operation type
            10.0
        }
    } else {
        // No schema available, use default estimate
        10.0
    }
}

/// Count fields in a JSON schema recursively
fn count_fields_in_schema(schema: &serde_json::Value) -> f64 {
    match schema {
        serde_json::Value::Object(map) => {
            let mut count = 0.0;
            // Check for "properties" (JSON Schema)
            if let Some(properties) = map.get("properties") {
                if let Some(props) = properties.as_object() {
                    count += props.len() as f64;
                    // Recursively count nested properties
                    for prop_value in props.values() {
                        count += count_fields_in_schema(prop_value);
                    }
                }
            }
            // Check for "fields" (Avro-style)
            if let Some(fields) = map.get("fields") {
                if let Some(fields_array) = fields.as_array() {
                    count += fields_array.len() as f64;
                    for field in fields_array {
                        if let Some(field_obj) = field.as_object() {
                            if let Some(field_type) = field_obj.get("type") {
                                count += count_fields_in_schema(field_type);
                            }
                        }
                    }
                }
            }
            // Check for nested objects/arrays
            if let Some(item_type) = map.get("items") {
                count += count_fields_in_schema(item_type);
            }
            count
        }
        _ => 0.0,
    }
}

/// Estimate size from diff result
fn estimate_size_from_diff(diff_result: &ContractDiffResult) -> f64 {
    // Estimate based on number of mismatches
    // More mismatches = larger size change
    let base_size = 10.0;
    let mismatch_count = diff_result.mismatches.len() as f64;
    base_size + (mismatch_count * 2.0) // Each mismatch adds ~2 fields
}

/// Count required fields in a schema
fn count_required_fields_in_schema(schema: &serde_json::Value) -> usize {
    match schema {
        serde_json::Value::Object(map) => {
            let mut count = 0;
            // Check for "required" array (JSON Schema)
            if let Some(required) = map.get("required") {
                if let Some(required_array) = required.as_array() {
                    count += required_array.len();
                }
            }
            // Check nested schemas
            if let Some(properties) = map.get("properties") {
                if let Some(props) = properties.as_object() {
                    for prop_value in props.values() {
                        count += count_required_fields_in_schema(prop_value);
                    }
                }
            }
            // Check for "fields" (Avro-style) with required flag
            if let Some(fields) = map.get("fields") {
                if let Some(fields_array) = fields.as_array() {
                    for field in fields_array {
                        if let Some(field_obj) = field.as_object() {
                            // Check if field has "default" - if not, it's required in Avro
                            if !field_obj.contains_key("default") {
                                count += 1;
                            }
                            if let Some(field_type) = field_obj.get("type") {
                                count += count_required_fields_in_schema(field_type);
                            }
                        }
                    }
                }
            }
            count
        }
        _ => 0,
    }
}

/// Calculate schema depth for a protocol contract schema
fn calculate_protocol_schema_depth(schema: &serde_json::Value) -> u32 {
    match schema {
        serde_json::Value::Object(map) => {
            let mut max_depth = 0;
            // Check nested objects
            if let Some(properties) = map.get("properties") {
                if let Some(props) = properties.as_object() {
                    for prop_value in props.values() {
                        let depth = calculate_protocol_schema_depth(prop_value);
                        max_depth = max_depth.max(depth + 1);
                    }
                }
            }
            // Check for "fields" (Avro-style)
            if let Some(fields) = map.get("fields") {
                if let Some(fields_array) = fields.as_array() {
                    for field in fields_array {
                        if let Some(field_obj) = field.as_object() {
                            if let Some(field_type) = field_obj.get("type") {
                                let depth = calculate_protocol_schema_depth(field_type);
                                max_depth = max_depth.max(depth + 1);
                            }
                        }
                    }
                }
            }
            // Check for arrays
            if let Some(items) = map.get("items") {
                let depth = calculate_protocol_schema_depth(items);
                max_depth = max_depth.max(depth + 1);
            }
            max_depth
        }
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_matches_pattern() {
        assert!(matches_pattern("/api/users", "*"));
        assert!(matches_pattern("/api/users", "/api/users"));
        assert!(matches_pattern("/api/users/123", "/api/users/*"));
        assert!(matches_pattern("/v1/mobile/users", "/v1/mobile/*"));
        assert!(!matches_pattern("/api/users", "/api/orders"));
    }

    #[test]
    fn test_fitness_function_registry() {
        let mut registry = FitnessFunctionRegistry::new();

        let function = FitnessFunction {
            id: "test-1".to_string(),
            name: "Test Function".to_string(),
            description: "Test".to_string(),
            function_type: FitnessFunctionType::ResponseSize {
                max_increase_percent: 25.0,
            },
            config: serde_json::json!({"max_increase_percent": 25.0}),
            scope: FitnessScope::Global,
            enabled: true,
            created_at: 0,
            updated_at: 0,
        };

        registry.add_function(function);
        assert_eq!(registry.list_functions().len(), 1);
    }
}