mockforge-intelligence 0.3.142

AI-powered behavior, response generation, and behavioral cloning 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
//! Rule auto-generation engine for MockAI
//!
//! This module analyzes example request/response pairs and OpenAPI specifications
//! to automatically generate behavioral rules, validation rules, pagination patterns,
//! and state machines.

use super::config::BehaviorModelConfig;
use super::llm_client::LlmClient;
use super::rules::{ConsistencyRule, RuleAction, StateMachine, StateTransition};
use super::types::{BehaviorRules, LlmGenerationRequest};
use mockforge_foundation::Result;
// Data types re-exported from foundation so consumers can use them without
// depending on deprecated core modules.
pub use mockforge_foundation::intelligent_behavior::rule_types::{
    CrudExample, ErrorExample, ExamplePair, PaginatedResponse, PaginationRule, PatternMatch,
    RuleExplanation, RuleType, ValidationRule,
};
use serde_json::Value;
use std::collections::HashMap;

/// Rule generator that learns from examples
pub struct RuleGenerator {
    /// LLM client for intelligent rule generation
    llm_client: Option<LlmClient>,
    /// Configuration
    #[allow(dead_code)]
    config: BehaviorModelConfig,
}

impl RuleGenerator {
    /// Create a new rule generator
    pub fn new(config: BehaviorModelConfig) -> Self {
        let llm_client = if config.llm_provider != "disabled" {
            Some(LlmClient::new(config.clone()))
        } else {
            None
        };

        Self { llm_client, config }
    }

    /// Generate behavioral rules from example pairs
    ///
    /// Analyzes request/response examples to infer:
    /// - Consistency rules
    /// - Resource schemas
    /// - State machines
    /// - System prompts
    pub async fn generate_rules_from_examples(
        &self,
        examples: Vec<ExamplePair>,
    ) -> Result<BehaviorRules> {
        if examples.is_empty() {
            return Ok(BehaviorRules::default());
        }

        // Group examples by path pattern
        let path_groups = self.group_by_path_pattern(&examples);

        // Generate consistency rules from patterns
        let consistency_rules = self.infer_consistency_rules(&examples, &path_groups).await?;

        // Extract schemas from responses
        let schemas = self.extract_schemas_from_examples(&examples).await?;

        // Generate state machines from CRUD patterns
        let state_machines = self.infer_state_machines(&examples).await?;

        // Generate system prompt
        let system_prompt = self.generate_system_prompt(&examples).await?;

        Ok(BehaviorRules {
            system_prompt,
            schemas,
            consistency_rules,
            state_transitions: state_machines,
            max_context_interactions: 10,
            enable_semantic_search: true,
        })
    }

    /// Generate behavioral rules with explanations from example pairs
    ///
    /// Similar to `generate_rules_from_examples`, but also returns
    /// detailed explanations for each generated rule.
    pub async fn generate_rules_with_explanations(
        &self,
        examples: Vec<ExamplePair>,
    ) -> Result<(BehaviorRules, Vec<RuleExplanation>)> {
        if examples.is_empty() {
            return Ok((BehaviorRules::default(), Vec::new()));
        }

        // Generate rules first
        let rules = self.generate_rules_from_examples(examples.clone()).await?;

        // Generate explanations for each rule
        let mut explanations = Vec::new();

        // Explain consistency rules
        for (idx, rule) in rules.consistency_rules.iter().enumerate() {
            let rule_id = format!("consistency_rule_{}", idx);
            let explanation = RuleExplanation::new(
                rule_id,
                RuleType::Consistency,
                0.8, // Default confidence for consistency rules
                format!(
                    "Inferred from {} examples matching pattern: {}",
                    examples.len(),
                    rule.condition
                ),
            )
            .with_source_example(format!("example_{}", idx));
            explanations.push(explanation);
        }

        // Explain state machines
        for (resource_type, state_machine) in &rules.state_transitions {
            let rule_id = format!("state_machine_{}", resource_type);
            let explanation = RuleExplanation::new(
                rule_id,
                RuleType::StateTransition,
                0.85, // Higher confidence for state machines
                format!(
                    "State machine for {} with {} states and {} transitions inferred from CRUD patterns",
                    resource_type,
                    state_machine.states.len(),
                    state_machine.transitions.len()
                ),
            );
            explanations.push(explanation);
        }

        // Explain schemas
        for resource_name in rules.schemas.keys() {
            let rule_id = format!("schema_{}", resource_name);
            let explanation = RuleExplanation::new(
                rule_id,
                RuleType::Other,
                0.75, // Moderate confidence for inferred schemas
                format!("Schema for {} resource inferred from response examples", resource_name),
            );
            explanations.push(explanation);
        }

        Ok((rules, explanations))
    }

    /// Infer validation rules from error examples
    pub async fn infer_validation_rules(
        &self,
        error_examples: Vec<ErrorExample>,
    ) -> Result<Vec<ValidationRule>> {
        if error_examples.is_empty() {
            return Ok(Vec::new());
        }

        let mut rules = Vec::new();

        // Group errors by field and type
        let mut field_errors: HashMap<String, Vec<&ErrorExample>> = HashMap::new();
        for error in &error_examples {
            if let Some(ref field) = error.field {
                field_errors.entry(field.clone()).or_default().push(error);
            }
        }

        // Analyze each field's error patterns
        for (field, errors) in field_errors {
            // Determine validation type from error patterns
            let validation_type = self.determine_validation_type(&errors)?;
            let error_message = self.extract_error_message_template(&errors)?;
            let status_code = errors[0].status;

            let mut parameters = HashMap::new();
            match validation_type.as_str() {
                "required" => {
                    parameters.insert("required".to_string(), Value::Bool(true));
                }
                "format" => {
                    // Try to infer format from error message
                    if let Some(format) = self.infer_format_from_errors(&errors) {
                        parameters.insert("format".to_string(), Value::String(format));
                    }
                }
                "min_length" | "max_length" => {
                    // Try to infer length constraints
                    if let Some(length) = self.infer_length_constraint(&errors, &validation_type) {
                        parameters.insert(validation_type.clone(), Value::Number(length));
                    }
                }
                _ => {}
            }

            rules.push(ValidationRule {
                field,
                validation_type,
                parameters,
                error_message,
                status_code,
            });
        }

        Ok(rules)
    }

    /// Extract pagination pattern from examples
    pub async fn extract_pagination_pattern(
        &self,
        examples: Vec<PaginatedResponse>,
    ) -> Result<PaginationRule> {
        if examples.is_empty() {
            return Ok(PaginationRule {
                default_page_size: 20,
                max_page_size: 100,
                min_page_size: 1,
                parameter_names: HashMap::new(),
                format: "page-based".to_string(),
            });
        }

        // Analyze pagination parameters
        let mut parameter_names = HashMap::new();
        let mut page_sizes = Vec::new();
        let mut formats = Vec::new();

        for example in &examples {
            // Detect pagination parameters
            for key in example.query_params.keys() {
                match key.to_lowercase().as_str() {
                    "page" | "p" => {
                        parameter_names.insert("page".to_string(), key.clone());
                    }
                    "limit" | "per_page" | "size" => {
                        parameter_names.insert("limit".to_string(), key.clone());
                    }
                    "offset" => {
                        parameter_names.insert("offset".to_string(), key.clone());
                        formats.push("offset-based".to_string());
                    }
                    "cursor" => {
                        parameter_names.insert("cursor".to_string(), key.clone());
                        formats.push("cursor-based".to_string());
                    }
                    _ => {}
                }
            }

            if let Some(size) = example.page_size {
                page_sizes.push(size);
            }
        }

        // Determine format (default to page-based if not detected)
        let format = formats.first().cloned().unwrap_or_else(|| "page-based".to_string());

        // Calculate page size statistics
        let default_page_size = page_sizes.iter().copied().min().unwrap_or(20);
        let max_page_size = page_sizes.iter().copied().max().unwrap_or(100);
        let min_page_size = 1;

        Ok(PaginationRule {
            default_page_size,
            max_page_size,
            min_page_size,
            parameter_names,
            format,
        })
    }

    /// Analyze CRUD patterns to generate state machines
    pub async fn analyze_crud_pattern(
        &self,
        examples: Vec<CrudExample>,
    ) -> Result<HashMap<String, StateMachine>> {
        let mut machines: HashMap<String, StateMachine> = HashMap::new();

        // Group by resource type
        let mut resource_groups: HashMap<String, Vec<&CrudExample>> = HashMap::new();
        for example in &examples {
            resource_groups.entry(example.resource_type.clone()).or_default().push(example);
        }

        // Generate state machine for each resource type
        for (resource_type, resource_examples) in resource_groups {
            let states = self.infer_states_from_crud(&resource_examples)?;
            let initial_state = states.first().cloned().unwrap_or_else(|| "created".to_string());
            let transitions = self.infer_transitions_from_crud(&resource_examples, &states)?;

            let machine = StateMachine::new(resource_type.clone(), states, initial_state)
                .add_transitions(transitions);

            machines.insert(resource_type, machine);
        }

        Ok(machines)
    }

    // ===== Private helper methods =====

    /// Group examples by path pattern
    fn group_by_path_pattern<'a>(
        &self,
        examples: &'a [ExamplePair],
    ) -> HashMap<String, Vec<&'a ExamplePair>> {
        let mut groups: HashMap<String, Vec<&'a ExamplePair>> = HashMap::new();

        for example in examples {
            // Extract base path (remove IDs)
            let base_path = self.normalize_path(&example.path);
            groups.entry(base_path).or_default().push(example);
        }

        groups
    }

    /// Normalize path by replacing IDs with placeholders
    fn normalize_path(&self, path: &str) -> String {
        // Simple heuristic: replace UUIDs and numeric IDs with placeholders
        path.split('/')
            .map(|segment| {
                if segment.parse::<u64>().is_ok() || segment.len() == 36 {
                    // Likely an ID
                    "{id}"
                } else {
                    segment
                }
            })
            .collect::<Vec<_>>()
            .join("/")
    }

    /// Infer consistency rules from examples
    async fn infer_consistency_rules<'a>(
        &self,
        examples: &'a [ExamplePair],
        _path_groups: &HashMap<String, Vec<&'a ExamplePair>>,
    ) -> Result<Vec<ConsistencyRule>> {
        let mut rules = Vec::new();

        // Rule 1: POST creates resources (status 201)
        for example in examples {
            if example.method == "POST" && example.status == 201 {
                let path_pattern = self.normalize_path(&example.path);
                rules.push(ConsistencyRule::new(
                    format!("create_{}", path_pattern.replace('/', "_")),
                    format!("method == 'POST' AND path starts_with '{}'", path_pattern),
                    RuleAction::Transform {
                        description: format!("Create new resource at {}", path_pattern),
                    },
                ));
            }
        }

        // Rule 2: GET retrieves resources (status 200)
        for example in examples {
            if example.method == "GET" && example.status == 200 {
                let path_pattern = self.normalize_path(&example.path);
                rules.push(ConsistencyRule::new(
                    format!("get_{}", path_pattern.replace('/', "_")),
                    format!("method == 'GET' AND path starts_with '{}'", path_pattern),
                    RuleAction::Transform {
                        description: format!("Retrieve resource from {}", path_pattern),
                    },
                ));
            }
        }

        // Rule 3: PUT/PATCH updates resources (status 200)
        for example in examples {
            if (example.method == "PUT" || example.method == "PATCH") && example.status == 200 {
                let path_pattern = self.normalize_path(&example.path);
                rules.push(ConsistencyRule::new(
                    format!("update_{}", path_pattern.replace('/', "_")),
                    format!("method IN ['PUT', 'PATCH'] AND path starts_with '{}'", path_pattern),
                    RuleAction::Transform {
                        description: format!("Update resource at {}", path_pattern),
                    },
                ));
            }
        }

        // Rule 4: DELETE removes resources (status 204 or 200)
        for example in examples {
            if example.method == "DELETE" && (example.status == 204 || example.status == 200) {
                let path_pattern = self.normalize_path(&example.path);
                rules.push(ConsistencyRule::new(
                    format!("delete_{}", path_pattern.replace('/', "_")),
                    format!("method == 'DELETE' AND path starts_with '{}'", path_pattern),
                    RuleAction::Transform {
                        description: format!("Delete resource from {}", path_pattern),
                    },
                ));
            }
        }

        // Use LLM to generate additional rules if available
        if let Some(ref _llm_client) = self.llm_client {
            let additional_rules = self.generate_rules_with_llm(examples).await?;
            rules.extend(additional_rules);
        }

        Ok(rules)
    }

    /// Extract schemas from example responses
    async fn extract_schemas_from_examples(
        &self,
        examples: &[ExamplePair],
    ) -> Result<HashMap<String, Value>> {
        let mut schemas: HashMap<String, Value> = HashMap::new();

        for example in examples {
            if let Some(ref response) = example.response {
                // Extract resource name from path
                let resource_name = self.extract_resource_name(&example.path);

                // Generate JSON Schema from response
                if let Some(schema) = self.infer_schema_from_value(response) {
                    schemas.insert(resource_name, schema);
                }
            }
        }

        Ok(schemas)
    }

    /// Infer JSON Schema from a JSON value
    #[allow(clippy::only_used_in_recursion)]
    fn infer_schema_from_value(&self, value: &Value) -> Option<Value> {
        match value {
            Value::Object(obj) => {
                let mut properties = serde_json::Map::new();
                let mut required = Vec::new();

                for (key, val) in obj {
                    if let Some(prop_schema) = self.infer_schema_from_value(val) {
                        properties.insert(key.clone(), prop_schema);
                        required.push(key.clone());
                    }
                }

                Some(serde_json::json!({
                    "type": "object",
                    "properties": properties,
                    "required": required
                }))
            }
            Value::Array(arr) => {
                if let Some(first) = arr.first() {
                    if let Some(item_schema) = self.infer_schema_from_value(first) {
                        Some(serde_json::json!({
                            "type": "array",
                            "items": item_schema
                        }))
                    } else {
                        Some(serde_json::json!({"type": "array"}))
                    }
                } else {
                    Some(serde_json::json!({"type": "array"}))
                }
            }
            Value::String(_) => Some(serde_json::json!({"type": "string"})),
            Value::Number(n) => {
                if n.is_i64() {
                    Some(serde_json::json!({"type": "integer"}))
                } else {
                    Some(serde_json::json!({"type": "number"}))
                }
            }
            Value::Bool(_) => Some(serde_json::json!({"type": "boolean"})),
            Value::Null => None,
        }
    }

    /// Extract resource name from path
    fn extract_resource_name(&self, path: &str) -> String {
        // Extract last meaningful segment, skipping numeric IDs
        let segments: Vec<&str> =
            path.split('/').filter(|s| !s.is_empty() && !s.starts_with('{')).collect();

        // Find the last non-numeric segment (resource name, not ID)
        for segment in segments.iter().rev() {
            if !segment.chars().all(|c| c.is_ascii_digit()) {
                return segment.to_string();
            }
        }

        // Fallback to last segment if all are numeric
        segments.last().map(|s| s.to_string()).unwrap_or_else(|| "Resource".to_string())
    }

    /// Infer state machines from examples
    async fn infer_state_machines(
        &self,
        examples: &[ExamplePair],
    ) -> Result<HashMap<String, StateMachine>> {
        // Convert examples to CRUD examples
        let crud_examples: Vec<CrudExample> = examples
            .iter()
            .filter_map(|ex| {
                let operation = match ex.method.as_str() {
                    "POST" => Some("create"),
                    "GET" => Some("read"),
                    "PUT" | "PATCH" => Some("update"),
                    "DELETE" => Some("delete"),
                    _ => None,
                }?;

                let resource_type = self.extract_resource_name(&ex.path);

                Some(CrudExample {
                    operation: operation.to_string(),
                    resource_type,
                    path: ex.path.clone(),
                    request: ex.request.clone(),
                    status: ex.status,
                    response: ex.response.clone(),
                    resource_state: None,
                })
            })
            .collect();

        self.analyze_crud_pattern(crud_examples).await
    }

    /// Infer states from CRUD examples
    fn infer_states_from_crud(&self, examples: &[&CrudExample]) -> Result<Vec<String>> {
        // Default states for CRUD operations
        let mut states = vec!["created".to_string(), "active".to_string()];

        // Check for delete operations (add deleted state)
        if examples.iter().any(|e| e.operation == "delete") {
            states.push("deleted".to_string());
        }

        // Check for update operations (add updated state)
        if examples.iter().any(|e| e.operation == "update") {
            states.push("updated".to_string());
        }

        Ok(states)
    }

    /// Infer transitions from CRUD examples
    fn infer_transitions_from_crud(
        &self,
        _examples: &[&CrudExample],
        states: &[String],
    ) -> Result<Vec<StateTransition>> {
        let mut transitions = Vec::new();

        // Create -> Active
        if states.contains(&"created".to_string()) && states.contains(&"active".to_string()) {
            transitions.push(StateTransition::new("created", "active").with_probability(1.0));
        }

        // Active -> Updated
        if states.contains(&"active".to_string()) && states.contains(&"updated".to_string()) {
            transitions.push(StateTransition::new("active", "updated").with_probability(0.8));
        }

        // Updated -> Active (can revert)
        if states.contains(&"updated".to_string()) && states.contains(&"active".to_string()) {
            transitions.push(StateTransition::new("updated", "active").with_probability(0.5));
        }

        // Active -> Deleted
        if states.contains(&"active".to_string()) && states.contains(&"deleted".to_string()) {
            transitions.push(StateTransition::new("active", "deleted").with_probability(0.3));
        }

        Ok(transitions)
    }

    /// Generate system prompt from examples
    async fn generate_system_prompt(&self, examples: &[ExamplePair]) -> Result<String> {
        // Analyze examples to understand API domain
        let mut methods = std::collections::HashSet::new();
        let mut paths = std::collections::HashSet::new();

        for example in examples {
            methods.insert(example.method.clone());
            paths.insert(self.normalize_path(&example.path));
        }

        let mut prompt = String::from("You are simulating a realistic REST API. ");

        // Add method information
        if !methods.is_empty() {
            let methods_vec: Vec<&str> = methods.iter().map(|s| s.as_str()).collect();
            prompt.push_str(&format!("Supported methods: {}. ", methods_vec.join(", ")));
        }

        // Add path information
        if !paths.is_empty() {
            let paths_vec: Vec<&str> = paths.iter().take(5).map(|s| s.as_str()).collect();
            prompt.push_str(&format!("Available endpoints: {}. ", paths_vec.join(", ")));
        }

        prompt.push_str("Maintain consistency across requests and follow REST conventions.");

        // Use LLM to enhance prompt if available
        if let Some(ref _llm_client) = self.llm_client {
            let enhanced = self.enhance_prompt_with_llm(&prompt, examples).await?;
            return Ok(enhanced);
        }

        Ok(prompt)
    }

    /// Generate additional rules using LLM
    async fn generate_rules_with_llm(
        &self,
        examples: &[ExamplePair],
    ) -> Result<Vec<ConsistencyRule>> {
        let llm_client = self
            .llm_client
            .as_ref()
            .ok_or_else(|| mockforge_foundation::Error::internal("LLM client not available"))?;

        // Build prompt with examples
        let examples_json = serde_json::to_string(examples)?;
        let system_prompt = "You are a rule generation system. Analyze API examples and generate consistency rules.";
        let user_prompt = format!(
            "Analyze these API examples and suggest additional consistency rules:\n\n{}",
            examples_json
        );

        let request = LlmGenerationRequest {
            system_prompt: system_prompt.to_string(),
            user_prompt,
            temperature: 0.3, // Lower temperature for more consistent rules
            max_tokens: 2000,
            schema: None,
        };

        let response = llm_client.generate(&request).await?;

        // Parse rules from LLM response
        // The LLM returns JSON with a "rules" array of ConsistencyRule objects
        let rules = if let Some(rules_array) = response.get("rules").and_then(|v| v.as_array()) {
            rules_array
                .iter()
                .filter_map(|rule_value| {
                    match serde_json::from_value::<ConsistencyRule>(rule_value.clone()) {
                        Ok(rule) => Some(rule),
                        Err(e) => {
                            tracing::warn!(
                                error = %e,
                                "Failed to parse LLM-generated rule, skipping"
                            );
                            None
                        }
                    }
                })
                .collect()
        } else if let Some(text) = response.as_str() {
            // Try to extract JSON from a text response
            if let Some(start) = text.find('[') {
                if let Some(end) = text.rfind(']') {
                    match serde_json::from_str::<Vec<ConsistencyRule>>(&text[start..=end]) {
                        Ok(rules) => rules,
                        Err(e) => {
                            tracing::warn!(
                                error = %e,
                                "Failed to parse LLM text response as rules array"
                            );
                            Vec::new()
                        }
                    }
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        Ok(rules)
    }

    /// Enhance system prompt using LLM
    async fn enhance_prompt_with_llm(
        &self,
        base_prompt: &str,
        examples: &[ExamplePair],
    ) -> Result<String> {
        let llm_client = self
            .llm_client
            .as_ref()
            .ok_or_else(|| mockforge_foundation::Error::internal("LLM client not available"))?;

        let examples_summary: Vec<String> = examples
            .iter()
            .take(10)
            .map(|e| format!("{} {} -> {}", e.method, e.path, e.status))
            .collect();

        let user_prompt = format!(
            "Based on this base prompt and API examples, generate an enhanced system prompt:\n\nBase: {}\n\nExamples:\n{}\n\nGenerate a comprehensive system prompt that describes the API behavior.",
            base_prompt,
            examples_summary.join("\n")
        );

        let request = LlmGenerationRequest {
            system_prompt: "You are a system prompt generator for API simulation.".to_string(),
            user_prompt,
            temperature: 0.7,
            max_tokens: 500,
            schema: None,
        };

        let response = llm_client.generate(&request).await?;

        // Extract text from response
        if let Some(text) = response.as_str() {
            Ok(text.to_string())
        } else {
            Ok(base_prompt.to_string())
        }
    }

    /// Determine validation type from error examples
    fn determine_validation_type(&self, errors: &[&ErrorExample]) -> Result<String> {
        // Analyze error messages and status codes
        for error in errors {
            let error_str =
                serde_json::to_string(&error.error_response).unwrap_or_default().to_lowercase();

            if error_str.contains("required") || error_str.contains("missing") {
                return Ok("required".to_string());
            }
            if error_str.contains("format") || error_str.contains("invalid format") {
                return Ok("format".to_string());
            }
            if error_str.contains("too short") || error_str.contains("minimum") {
                return Ok("min_length".to_string());
            }
            if error_str.contains("too long") || error_str.contains("maximum") {
                return Ok("max_length".to_string());
            }
            if error_str.contains("pattern") || error_str.contains("regex") {
                return Ok("pattern".to_string());
            }
        }

        // Default to required if status is 400
        if errors[0].status == 400 {
            Ok("required".to_string())
        } else {
            Ok("validation_error".to_string())
        }
    }

    /// Extract error message template
    fn extract_error_message_template(&self, errors: &[&ErrorExample]) -> Result<String> {
        // Use first error's message as template
        if let Some(error) = errors.first() {
            if let Some(message) = error.error_response.get("message").and_then(|m| m.as_str()) {
                return Ok(message.to_string());
            }
            if let Some(error_field) = error.error_response.get("error").and_then(|e| e.as_str()) {
                return Ok(error_field.to_string());
            }
        }

        Ok("Validation error".to_string())
    }

    /// Infer format from error messages
    fn infer_format_from_errors(&self, errors: &[&ErrorExample]) -> Option<String> {
        for error in errors {
            let error_str =
                serde_json::to_string(&error.error_response).unwrap_or_default().to_lowercase();

            if error_str.contains("email") {
                return Some("email".to_string());
            }
            if error_str.contains("url") {
                return Some("uri".to_string());
            }
            if error_str.contains("date") {
                return Some("date-time".to_string());
            }
            if error_str.contains("uuid") {
                return Some("uuid".to_string());
            }
        }

        None
    }

    /// Infer length constraint from errors
    fn infer_length_constraint(
        &self,
        errors: &[&ErrorExample],
        _validation_type: &str,
    ) -> Option<serde_json::Number> {
        for error in errors {
            let error_str =
                serde_json::to_string(&error.error_response).unwrap_or_default().to_lowercase();

            // Try to extract number from error message
            if let Some(num_str) =
                error_str.split_whitespace().find_map(|word| word.parse::<u64>().ok())
            {
                return Some(serde_json::Number::from(num_str));
            }
        }

        None
    }
}

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

    #[tokio::test]
    async fn test_normalize_path() {
        let config = BehaviorModelConfig::default();
        let generator = RuleGenerator::new(config);

        assert_eq!(generator.normalize_path("/api/users/123"), "/api/users/{id}");
        assert_eq!(generator.normalize_path("/api/users"), "/api/users");
    }

    #[tokio::test]
    async fn test_infer_schema_from_value() {
        let config = BehaviorModelConfig::default();
        let generator = RuleGenerator::new(config);

        let value = json!({
            "id": "123",
            "name": "Alice",
            "age": 30,
            "active": true
        });

        let schema = generator.infer_schema_from_value(&value).unwrap();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"].is_object());
    }

    #[tokio::test]
    async fn test_extract_resource_name() {
        let config = BehaviorModelConfig::default();
        let generator = RuleGenerator::new(config);

        assert_eq!(generator.extract_resource_name("/api/users"), "users");
        assert_eq!(generator.extract_resource_name("/api/users/123"), "users");
    }

    #[tokio::test]
    async fn test_determine_validation_type() {
        let config = BehaviorModelConfig::default();
        let generator = RuleGenerator::new(config);

        let errors = [ErrorExample {
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            request: Some(json!({"name": ""})),
            status: 400,
            error_response: json!({"message": "Field is required"}),
            field: Some("email".to_string()),
        }];

        let validation_type =
            generator.determine_validation_type(&errors.iter().collect::<Vec<_>>()).unwrap();
        assert_eq!(validation_type, "required");
    }

    #[test]
    fn test_example_pair_creation() {
        let mut query_params = HashMap::new();
        query_params.insert("page".to_string(), "1".to_string());

        let mut headers = HashMap::new();
        headers.insert("Content-Type".to_string(), "application/json".to_string());

        let pair = ExamplePair {
            method: "GET".to_string(),
            path: "/api/users".to_string(),
            request: None,
            status: 200,
            response: Some(json!({"users": []})),
            query_params,
            headers,
            metadata: HashMap::new(),
        };

        assert_eq!(pair.method, "GET");
        assert_eq!(pair.path, "/api/users");
        assert_eq!(pair.status, 200);
    }

    #[test]
    fn test_example_pair_serialization() {
        let pair = ExamplePair {
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            request: Some(json!({"name": "Alice"})),
            status: 201,
            response: Some(json!({"id": 1, "name": "Alice"})),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            metadata: HashMap::new(),
        };

        let json = serde_json::to_string(&pair).unwrap();
        assert!(json.contains("POST"));
        assert!(json.contains("/api/users"));
    }

    #[test]
    fn test_error_example_creation() {
        let error = ErrorExample {
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            request: Some(json!({"email": "invalid"})),
            status: 400,
            error_response: json!({"error": "Invalid email"}),
            field: Some("email".to_string()),
        };

        assert_eq!(error.method, "POST");
        assert_eq!(error.status, 400);
        assert_eq!(error.field, Some("email".to_string()));
    }

    #[test]
    fn test_error_example_serialization() {
        let error = ErrorExample {
            method: "PUT".to_string(),
            path: "/api/users/1".to_string(),
            request: None,
            status: 404,
            error_response: json!({"error": "Not found"}),
            field: None,
        };

        let json = serde_json::to_string(&error).unwrap();
        assert!(json.contains("404"));
    }

    #[test]
    fn test_paginated_response_creation() {
        let mut query_params = HashMap::new();
        query_params.insert("page".to_string(), "1".to_string());
        query_params.insert("limit".to_string(), "10".to_string());

        let response = PaginatedResponse {
            path: "/api/users".to_string(),
            query_params,
            response: json!({"data": [], "page": 1, "total": 100}),
            page: Some(1),
            page_size: Some(10),
            total: Some(100),
        };

        assert_eq!(response.path, "/api/users");
        assert_eq!(response.page, Some(1));
        assert_eq!(response.total, Some(100));
    }

    #[test]
    fn test_crud_example_creation() {
        let crud = CrudExample {
            operation: "create".to_string(),
            resource_type: "user".to_string(),
            path: "/api/users".to_string(),
            request: Some(json!({"name": "Alice"})),
            status: 201,
            response: Some(json!({"id": 1, "name": "Alice"})),
            resource_state: Some("active".to_string()),
        };

        assert_eq!(crud.operation, "create");
        assert_eq!(crud.resource_type, "user");
        assert_eq!(crud.status, 201);
    }

    #[test]
    fn test_validation_rule_creation() {
        let mut parameters = HashMap::new();
        parameters.insert("min_length".to_string(), json!(3));
        parameters.insert("max_length".to_string(), json!(50));

        let rule = ValidationRule {
            field: "username".to_string(),
            validation_type: "length".to_string(),
            parameters,
            error_message: "Username must be between 3 and 50 characters".to_string(),
            status_code: 400,
        };

        assert_eq!(rule.field, "username");
        assert_eq!(rule.validation_type, "length");
        assert_eq!(rule.status_code, 400);
    }

    #[test]
    fn test_pagination_rule_creation() {
        let mut parameter_names = HashMap::new();
        parameter_names.insert("page".to_string(), "page".to_string());
        parameter_names.insert("limit".to_string(), "limit".to_string());

        let rule = PaginationRule {
            default_page_size: 20,
            max_page_size: 100,
            min_page_size: 1,
            parameter_names,
            format: "page-based".to_string(),
        };

        assert_eq!(rule.default_page_size, 20);
        assert_eq!(rule.max_page_size, 100);
        assert_eq!(rule.format, "page-based");
    }

    #[test]
    fn test_rule_type_serialization() {
        let rule_types = vec![
            RuleType::Crud,
            RuleType::Validation,
            RuleType::Pagination,
            RuleType::Consistency,
            RuleType::StateTransition,
            RuleType::Other,
        ];

        for rule_type in rule_types {
            let json = serde_json::to_string(&rule_type).unwrap();
            assert!(!json.is_empty());
            let deserialized: RuleType = serde_json::from_str(&json).unwrap();
            assert_eq!(rule_type, deserialized);
        }
    }

    #[test]
    fn test_pattern_match_creation() {
        let pattern = PatternMatch {
            pattern: "/api/users/*".to_string(),
            match_count: 5,
            example_ids: vec!["ex1".to_string(), "ex2".to_string()],
        };

        assert_eq!(pattern.pattern, "/api/users/*");
        assert_eq!(pattern.match_count, 5);
        assert_eq!(pattern.example_ids.len(), 2);
    }

    #[test]
    fn test_rule_explanation_new() {
        let explanation = RuleExplanation::new(
            "rule-1".to_string(),
            RuleType::Consistency,
            0.85,
            "Inferred from examples".to_string(),
        );

        assert_eq!(explanation.rule_id, "rule-1");
        assert_eq!(explanation.rule_type, RuleType::Consistency);
        assert_eq!(explanation.confidence, 0.85);
        assert!(explanation.source_examples.is_empty());
    }

    #[test]
    fn test_rule_explanation_with_source_example() {
        let explanation = RuleExplanation::new(
            "rule-1".to_string(),
            RuleType::Validation,
            0.9,
            "Test reasoning".to_string(),
        )
        .with_source_example("example-1".to_string())
        .with_source_example("example-2".to_string());

        assert_eq!(explanation.source_examples.len(), 2);
        assert_eq!(explanation.source_examples[0], "example-1");
    }

    #[test]
    fn test_rule_explanation_with_pattern_match() {
        let pattern_match = PatternMatch {
            pattern: "/api/*".to_string(),
            match_count: 3,
            example_ids: vec!["ex1".to_string()],
        };

        let explanation = RuleExplanation::new(
            "rule-1".to_string(),
            RuleType::Pagination,
            0.75,
            "Test".to_string(),
        )
        .with_pattern_match(pattern_match.clone());

        assert_eq!(explanation.pattern_matches.len(), 1);
        assert_eq!(explanation.pattern_matches[0].pattern, "/api/*");
    }

    #[test]
    fn test_rule_generator_new() {
        let config = BehaviorModelConfig::default();
        let generator = RuleGenerator::new(config);
        // Just verify it can be created
        let _ = generator;
    }

    #[test]
    fn test_rule_generator_new_with_disabled_llm() {
        let config = BehaviorModelConfig {
            llm_provider: "disabled".to_string(),
            ..Default::default()
        };
        let generator = RuleGenerator::new(config);
        // Just verify it can be created
        let _ = generator;
    }

    #[test]
    fn test_paginated_response_serialization() {
        let mut query_params = HashMap::new();
        query_params.insert("page".to_string(), "2".to_string());
        let response = PaginatedResponse {
            path: "/api/items".to_string(),
            query_params: query_params.clone(),
            response: json!({"items": []}),
            page: Some(2),
            page_size: Some(20),
            total: Some(50),
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("/api/items"));
        assert!(json.contains("2"));
    }

    #[test]
    fn test_crud_example_serialization() {
        let crud = CrudExample {
            operation: "update".to_string(),
            resource_type: "order".to_string(),
            path: "/api/orders/123".to_string(),
            request: Some(json!({"status": "shipped"})),
            status: 200,
            response: Some(json!({"id": 123, "status": "shipped"})),
            resource_state: Some("shipped".to_string()),
        };

        let json = serde_json::to_string(&crud).unwrap();
        assert!(json.contains("update"));
        assert!(json.contains("order"));
    }

    #[test]
    fn test_validation_rule_serialization() {
        let mut parameters = HashMap::new();
        parameters.insert("pattern".to_string(), json!("^[a-z]+$"));
        let rule = ValidationRule {
            field: "username".to_string(),
            validation_type: "pattern".to_string(),
            parameters: parameters.clone(),
            error_message: "Invalid format".to_string(),
            status_code: 422,
        };

        let json = serde_json::to_string(&rule).unwrap();
        assert!(json.contains("username"));
        assert!(json.contains("pattern"));
    }

    #[test]
    fn test_pagination_rule_serialization() {
        let mut parameter_names = HashMap::new();
        parameter_names.insert("offset".to_string(), "offset".to_string());
        parameter_names.insert("limit".to_string(), "limit".to_string());
        let rule = PaginationRule {
            default_page_size: 25,
            max_page_size: 200,
            min_page_size: 5,
            parameter_names: parameter_names.clone(),
            format: "offset-based".to_string(),
        };

        let json = serde_json::to_string(&rule).unwrap();
        assert!(json.contains("offset-based"));
        assert!(json.contains("25"));
    }

    #[test]
    fn test_rule_type_variants() {
        assert_eq!(RuleType::Crud, RuleType::Crud);
        assert_eq!(RuleType::Validation, RuleType::Validation);
        assert_eq!(RuleType::Pagination, RuleType::Pagination);
        assert_eq!(RuleType::Consistency, RuleType::Consistency);
        assert_eq!(RuleType::StateTransition, RuleType::StateTransition);
        assert_eq!(RuleType::Other, RuleType::Other);
    }

    #[test]
    fn test_pattern_match_serialization() {
        let pattern = PatternMatch {
            pattern: "/api/v1/*".to_string(),
            match_count: 10,
            example_ids: vec!["ex1".to_string(), "ex2".to_string(), "ex3".to_string()],
        };

        let json = serde_json::to_string(&pattern).unwrap();
        assert!(json.contains("/api/v1/*"));
        assert!(json.contains("10"));
    }

    #[test]
    fn test_rule_explanation_serialization() {
        let explanation = RuleExplanation::new(
            "rule-123".to_string(),
            RuleType::Consistency,
            0.92,
            "High confidence rule".to_string(),
        )
        .with_source_example("ex1".to_string())
        .with_pattern_match(PatternMatch {
            pattern: "/api/*".to_string(),
            match_count: 5,
            example_ids: vec!["ex1".to_string()],
        });

        let json = serde_json::to_string(&explanation).unwrap();
        assert!(json.contains("rule-123"));
        assert!(json.contains("0.92"));
        assert!(json.contains("High confidence"));
    }

    #[test]
    fn test_error_example_with_field() {
        let error = ErrorExample {
            method: "PATCH".to_string(),
            path: "/api/users/1".to_string(),
            request: Some(json!({"email": "invalid-email"})),
            status: 422,
            error_response: json!({"field": "email", "message": "Invalid email format"}),
            field: Some("email".to_string()),
        };

        assert_eq!(error.field, Some("email".to_string()));
        assert_eq!(error.status, 422);
    }

    #[test]
    fn test_error_example_without_field() {
        let error = ErrorExample {
            method: "DELETE".to_string(),
            path: "/api/users/999".to_string(),
            request: None,
            status: 404,
            error_response: json!({"error": "Resource not found"}),
            field: None,
        };

        assert!(error.field.is_none());
        assert_eq!(error.status, 404);
    }

    #[test]
    fn test_paginated_response_without_pagination_info() {
        let response = PaginatedResponse {
            path: "/api/data".to_string(),
            query_params: HashMap::new(),
            response: json!({"data": []}),
            page: None,
            page_size: None,
            total: None,
        };

        assert!(response.page.is_none());
        assert!(response.page_size.is_none());
        assert!(response.total.is_none());
    }

    #[test]
    fn test_crud_example_without_state() {
        let crud = CrudExample {
            operation: "read".to_string(),
            resource_type: "product".to_string(),
            path: "/api/products/1".to_string(),
            request: None,
            status: 200,
            response: Some(json!({"id": 1, "name": "Product"})),
            resource_state: None,
        };

        assert!(crud.resource_state.is_none());
        assert_eq!(crud.operation, "read");
    }

    #[test]
    fn test_validation_rule_without_parameters() {
        let rule = ValidationRule {
            field: "required_field".to_string(),
            validation_type: "required".to_string(),
            parameters: HashMap::new(),
            error_message: "Field is required".to_string(),
            status_code: 400,
        };

        assert!(rule.parameters.is_empty());
        assert_eq!(rule.validation_type, "required");
    }

    #[test]
    fn test_rule_explanation_with_multiple_pattern_matches() {
        let explanation = RuleExplanation::new(
            "rule-456".to_string(),
            RuleType::StateTransition,
            0.88,
            "Complex rule".to_string(),
        )
        .with_pattern_match(PatternMatch {
            pattern: "/api/v1/*".to_string(),
            match_count: 3,
            example_ids: vec![],
        })
        .with_pattern_match(PatternMatch {
            pattern: "/api/v2/*".to_string(),
            match_count: 2,
            example_ids: vec![],
        });

        assert_eq!(explanation.pattern_matches.len(), 2);
    }

    #[test]
    fn test_example_pair_clone() {
        let pair1 = ExamplePair {
            method: "GET".to_string(),
            path: "/test".to_string(),
            request: None,
            status: 200,
            response: Some(json!({})),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            metadata: HashMap::new(),
        };
        let pair2 = pair1.clone();
        assert_eq!(pair1.method, pair2.method);
    }

    #[test]
    fn test_example_pair_debug() {
        let pair = ExamplePair {
            method: "POST".to_string(),
            path: "/api/test".to_string(),
            request: Some(json!({"data": "test"})),
            status: 201,
            response: Some(json!({"id": 1})),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            metadata: HashMap::new(),
        };
        let debug_str = format!("{:?}", pair);
        assert!(debug_str.contains("ExamplePair"));
    }

    #[test]
    fn test_error_example_clone() {
        let error1 = ErrorExample {
            method: "PATCH".to_string(),
            path: "/test".to_string(),
            request: None,
            status: 400,
            error_response: json!({"error": "Bad request"}),
            field: None,
        };
        let error2 = error1.clone();
        assert_eq!(error1.status, error2.status);
    }

    #[test]
    fn test_error_example_debug() {
        let error = ErrorExample {
            method: "PUT".to_string(),
            path: "/api/users/1".to_string(),
            request: Some(json!({"email": "invalid"})),
            status: 422,
            error_response: json!({"field": "email", "message": "Invalid"}),
            field: Some("email".to_string()),
        };
        let debug_str = format!("{:?}", error);
        assert!(debug_str.contains("ErrorExample"));
    }

    #[test]
    fn test_paginated_response_clone() {
        let response1 = PaginatedResponse {
            path: "/api/data".to_string(),
            query_params: HashMap::new(),
            response: json!({}),
            page: Some(1),
            page_size: Some(10),
            total: Some(100),
        };
        let response2 = response1.clone();
        assert_eq!(response1.page, response2.page);
    }

    #[test]
    fn test_paginated_response_debug() {
        let response = PaginatedResponse {
            path: "/api/users".to_string(),
            query_params: HashMap::from([("page".to_string(), "1".to_string())]),
            response: json!({"data": []}),
            page: Some(1),
            page_size: Some(20),
            total: Some(50),
        };
        let debug_str = format!("{:?}", response);
        assert!(debug_str.contains("PaginatedResponse"));
    }

    #[test]
    fn test_crud_example_clone() {
        let crud1 = CrudExample {
            operation: "create".to_string(),
            resource_type: "user".to_string(),
            path: "/api/users".to_string(),
            request: None,
            status: 201,
            response: None,
            resource_state: None,
        };
        let crud2 = crud1.clone();
        assert_eq!(crud1.operation, crud2.operation);
    }

    #[test]
    fn test_crud_example_debug() {
        let crud = CrudExample {
            operation: "update".to_string(),
            resource_type: "product".to_string(),
            path: "/api/products/1".to_string(),
            request: Some(json!({"name": "New Name"})),
            status: 200,
            response: Some(json!({"id": 1, "name": "New Name"})),
            resource_state: Some("updated".to_string()),
        };
        let debug_str = format!("{:?}", crud);
        assert!(debug_str.contains("CrudExample"));
    }

    #[test]
    fn test_validation_rule_clone() {
        let rule1 = ValidationRule {
            field: "email".to_string(),
            validation_type: "format".to_string(),
            parameters: HashMap::new(),
            error_message: "Invalid format".to_string(),
            status_code: 400,
        };
        let rule2 = rule1.clone();
        assert_eq!(rule1.field, rule2.field);
    }

    #[test]
    fn test_validation_rule_debug() {
        let mut parameters = HashMap::new();
        parameters.insert("pattern".to_string(), json!(r"^[a-z]+$"));
        let rule = ValidationRule {
            field: "username".to_string(),
            validation_type: "pattern".to_string(),
            parameters,
            error_message: "Invalid pattern".to_string(),
            status_code: 422,
        };
        let debug_str = format!("{:?}", rule);
        assert!(debug_str.contains("ValidationRule"));
    }

    #[test]
    fn test_pagination_rule_clone() {
        let rule1 = PaginationRule {
            default_page_size: 20,
            max_page_size: 100,
            min_page_size: 1,
            parameter_names: HashMap::new(),
            format: "page-based".to_string(),
        };
        let rule2 = rule1.clone();
        assert_eq!(rule1.default_page_size, rule2.default_page_size);
    }

    #[test]
    fn test_pagination_rule_debug() {
        let mut parameter_names = HashMap::new();
        parameter_names.insert("page".to_string(), "page".to_string());
        parameter_names.insert("size".to_string(), "limit".to_string());
        let rule = PaginationRule {
            default_page_size: 25,
            max_page_size: 200,
            min_page_size: 5,
            parameter_names,
            format: "offset-based".to_string(),
        };
        let debug_str = format!("{:?}", rule);
        assert!(debug_str.contains("PaginationRule"));
    }

    #[test]
    fn test_rule_type_clone() {
        let rule_type1 = RuleType::Validation;
        let rule_type2 = rule_type1;
        assert_eq!(rule_type1, rule_type2);
    }

    #[test]
    fn test_rule_type_debug() {
        let rule_type = RuleType::StateTransition;
        let debug_str = format!("{:?}", rule_type);
        assert!(debug_str.contains("StateTransition") || debug_str.contains("RuleType"));
    }

    #[test]
    fn test_pattern_match_clone() {
        let pattern1 = PatternMatch {
            pattern: "/api/*".to_string(),
            match_count: 10,
            example_ids: vec!["ex1".to_string()],
        };
        let pattern2 = pattern1.clone();
        assert_eq!(pattern1.pattern, pattern2.pattern);
    }

    #[test]
    fn test_pattern_match_debug() {
        let pattern = PatternMatch {
            pattern: "/api/v1/users/*".to_string(),
            match_count: 15,
            example_ids: vec!["ex1".to_string(), "ex2".to_string(), "ex3".to_string()],
        };
        let debug_str = format!("{:?}", pattern);
        assert!(debug_str.contains("PatternMatch"));
    }

    #[test]
    fn test_rule_explanation_clone() {
        let explanation1 = RuleExplanation::new(
            "rule-1".to_string(),
            RuleType::Consistency,
            0.95,
            "Test rule".to_string(),
        );
        let explanation2 = explanation1.clone();
        assert_eq!(explanation1.rule_id, explanation2.rule_id);
    }

    #[test]
    fn test_rule_explanation_debug() {
        let explanation = RuleExplanation::new(
            "rule-123".to_string(),
            RuleType::Validation,
            0.88,
            "Validation rule".to_string(),
        )
        .with_source_example("ex-1".to_string())
        .with_pattern_match(PatternMatch {
            pattern: "/api/*".to_string(),
            match_count: 5,
            example_ids: vec![],
        });
        let debug_str = format!("{:?}", explanation);
        assert!(debug_str.contains("RuleExplanation"));
    }
}