oxirs-rule 0.2.4

Forward/backward rule engine for RDFS, OWL, and SWRL reasoning
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
//! Migration Tools for Rule Engines
//!
//! Provides tools to migrate rule sets from other popular rule engines to OxiRS format.
//! Supports Apache Jena, Drools, and CLIPS rule formats.
//!
//! # Supported Formats
//!
//! - **Apache Jena**: Jena rules format (text-based rule syntax)
//! - **Drools**: DRL (Drools Rule Language) format
//! - **CLIPS**: CLIPS rule format
//!
//! # Features
//!
//! - **Syntax Parsing**: Parse rules from various formats
//! - **Semantic Mapping**: Map concepts between rule engines
//! - **Validation**: Validate migrated rules for correctness
//! - **Report Generation**: Generate migration reports with warnings
//! - **Batch Migration**: Migrate entire rule sets
//! - **Incremental Migration**: Support partial migrations
//!
//! # Example
//!
//! ```rust
//! use oxirs_rule::migration::{MigrationTool, SourceFormat};
//!
//! let mut migrator = MigrationTool::new();
//!
//! // Migrate from Jena format
//! let jena_rules = r#"
//! [rule1: (?a rdf:type Person) -> (?a rdf:type Human)]
//! [rule2: (?x parent ?y) -> (?y hasParent ?x)]
//! "#;
//!
//! let result = migrator.migrate(jena_rules, SourceFormat::Jena).expect("should succeed");
//!
//! println!("Migrated {} rules", result.rules.len());
//! println!("Report:\n{}", result.generate_report());
//! # Ok::<(), anyhow::Error>(())
//! ```

use crate::{Rule, RuleAtom, Term};
use anyhow::{anyhow, Context, Result};
use regex::Regex;
use std::collections::HashMap;
use tracing::{info, warn};

/// Source format for migration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceFormat {
    /// Apache Jena rules format
    Jena,
    /// Drools Rule Language (DRL)
    Drools,
    /// CLIPS rule format
    Clips,
}

impl SourceFormat {
    /// Get format name
    pub fn name(&self) -> &str {
        match self {
            Self::Jena => "Apache Jena",
            Self::Drools => "Drools DRL",
            Self::Clips => "CLIPS",
        }
    }
}

/// Migration warning
#[derive(Debug, Clone)]
pub struct MigrationWarning {
    /// Warning message
    pub message: String,
    /// Line number where warning occurred
    pub line: Option<usize>,
    /// Severity (info, warning, error)
    pub severity: WarningSeverity,
}

/// Warning severity
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningSeverity {
    Info,
    Warning,
    Error,
}

/// Migration result
#[derive(Debug)]
pub struct MigrationResult {
    /// Successfully migrated rules
    pub rules: Vec<Rule>,
    /// Warnings encountered during migration
    pub warnings: Vec<MigrationWarning>,
    /// Source format
    pub source_format: SourceFormat,
    /// Original rule count
    pub original_count: usize,
    /// Successfully migrated count
    pub migrated_count: usize,
}

impl MigrationResult {
    /// Generate a detailed migration report
    pub fn generate_report(&self) -> String {
        let mut report = String::new();
        report.push_str("═══════════════════════════════════════════════════════════════\n");
        report.push_str(&format!(
            "   Migration Report: {} → OxiRS\n",
            self.source_format.name()
        ));
        report.push_str("═══════════════════════════════════════════════════════════════\n\n");

        report.push_str(&format!("Original rules:  {}\n", self.original_count));
        report.push_str(&format!("Migrated rules:  {}\n", self.migrated_count));
        report.push_str(&format!(
            "Success rate:    {:.1}%\n\n",
            (self.migrated_count as f64 / self.original_count as f64) * 100.0
        ));

        if !self.warnings.is_empty() {
            report.push_str("Warnings:\n");
            report.push_str("─────────────────────────────────────────────────────────────\n");

            let mut errors = 0;
            let mut warnings = 0;
            let mut infos = 0;

            for warning in &self.warnings {
                let prefix = match warning.severity {
                    WarningSeverity::Error => {
                        errors += 1;
                        "ERROR"
                    }
                    WarningSeverity::Warning => {
                        warnings += 1;
                        "WARN"
                    }
                    WarningSeverity::Info => {
                        infos += 1;
                        "INFO"
                    }
                };

                if let Some(line) = warning.line {
                    report.push_str(&format!(
                        "  [{}] Line {}: {}\n",
                        prefix, line, warning.message
                    ));
                } else {
                    report.push_str(&format!("  [{}] {}\n", prefix, warning.message));
                }
            }

            report.push_str(&format!(
                "\nSummary: {} errors, {} warnings, {} info\n",
                errors, warnings, infos
            ));
        }

        report.push_str("\n═══════════════════════════════════════════════════════════════\n");
        report
    }

    /// Check if migration was successful
    pub fn is_successful(&self) -> bool {
        self.warnings
            .iter()
            .all(|w| w.severity != WarningSeverity::Error)
    }
}

/// Migration tool for converting rules between formats
pub struct MigrationTool {
    /// Enable strict validation
    strict_mode: bool,
    /// Custom namespace mappings
    namespace_mappings: HashMap<String, String>,
}

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

impl MigrationTool {
    /// Create a new migration tool
    pub fn new() -> Self {
        Self {
            strict_mode: false,
            namespace_mappings: HashMap::new(),
        }
    }

    /// Enable strict validation mode
    pub fn with_strict_mode(mut self, strict: bool) -> Self {
        self.strict_mode = strict;
        self
    }

    /// Add namespace mapping
    pub fn add_namespace_mapping(&mut self, from: &str, to: &str) {
        self.namespace_mappings
            .insert(from.to_string(), to.to_string());
    }

    /// Migrate rules from source format to OxiRS
    pub fn migrate(&mut self, source: &str, format: SourceFormat) -> Result<MigrationResult> {
        info!("Starting migration from {}", format.name());

        let mut warnings = Vec::new();
        let rules = match format {
            SourceFormat::Jena => self.migrate_jena(source, &mut warnings)?,
            SourceFormat::Drools => self.migrate_drools(source, &mut warnings)?,
            SourceFormat::Clips => self.migrate_clips(source, &mut warnings)?,
        };

        let original_count = source
            .lines()
            .filter(|line| {
                let trimmed = line.trim();
                !trimmed.is_empty() && !trimmed.starts_with('#') && !trimmed.starts_with("//")
            })
            .count();

        Ok(MigrationResult {
            migrated_count: rules.len(),
            rules,
            warnings,
            source_format: format,
            original_count,
        })
    }

    /// Migrate from Apache Jena format
    fn migrate_jena(
        &mut self,
        source: &str,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<Vec<Rule>> {
        let mut rules = Vec::new();

        // Jena rule format: [ruleName: (body) -> (head)]
        let rule_regex = Regex::new(r"\[(\w+):\s*(.+?)\s*->\s*(.+?)\]")
            .context("Failed to compile Jena rule regex")?;

        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }

            if let Some(captures) = rule_regex.captures(trimmed) {
                let rule_name = captures.get(1).expect("regex capture group 1").as_str();
                let body_str = captures.get(2).expect("regex capture group 2").as_str();
                let head_str = captures.get(3).expect("regex capture group 3").as_str();

                match self.parse_jena_atoms(body_str, head_str, rule_name) {
                    Ok(rule) => rules.push(rule),
                    Err(e) => {
                        warnings.push(MigrationWarning {
                            message: format!("Failed to parse rule '{}': {}", rule_name, e),
                            line: Some(line_num + 1),
                            severity: if self.strict_mode {
                                WarningSeverity::Error
                            } else {
                                WarningSeverity::Warning
                            },
                        });
                    }
                }
            } else {
                warnings.push(MigrationWarning {
                    message: format!("Could not parse Jena rule syntax: {}", trimmed),
                    line: Some(line_num + 1),
                    severity: WarningSeverity::Warning,
                });
            }
        }

        info!("Migrated {} Jena rules", rules.len());
        Ok(rules)
    }

    /// Parse Jena atoms into OxiRS format
    fn parse_jena_atoms(&self, body_str: &str, head_str: &str, rule_name: &str) -> Result<Rule> {
        let body = self.parse_jena_triples(body_str)?;
        let head = self.parse_jena_triples(head_str)?;

        Ok(Rule {
            name: rule_name.to_string(),
            body,
            head,
        })
    }

    /// Parse Jena triple patterns
    fn parse_jena_triples(&self, patterns: &str) -> Result<Vec<RuleAtom>> {
        let mut atoms = Vec::new();

        // Split by comma or conjunction
        for pattern in patterns.split(',') {
            let pattern = pattern.trim();
            if pattern.is_empty() {
                continue;
            }

            // Remove parentheses
            let pattern = pattern.strip_prefix('(').unwrap_or(pattern);
            let pattern = pattern.strip_suffix(')').unwrap_or(pattern);

            // Parse triple pattern: subject predicate object
            let parts: Vec<&str> = pattern.split_whitespace().collect();
            if parts.len() == 3 {
                atoms.push(RuleAtom::Triple {
                    subject: self.parse_jena_term(parts[0])?,
                    predicate: self.parse_jena_term(parts[1])?,
                    object: self.parse_jena_term(parts[2])?,
                });
            } else {
                return Err(anyhow!("Invalid triple pattern: {}", pattern));
            }
        }

        Ok(atoms)
    }

    /// Parse Jena term (variable or constant)
    fn parse_jena_term(&self, term: &str) -> Result<Term> {
        if let Some(var_name) = term.strip_prefix('?') {
            // Variable
            Ok(Term::Variable(var_name.to_string()))
        } else if term.starts_with('"') && term.ends_with('"') {
            // Literal
            Ok(Term::Literal(term[1..term.len() - 1].to_string()))
        } else {
            // Constant (URI or local name)
            let expanded = self.expand_namespace(term);
            Ok(Term::Constant(expanded))
        }
    }

    /// Migrate from Drools DRL format
    fn migrate_drools(
        &mut self,
        source: &str,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<Vec<Rule>> {
        let mut rules = Vec::new();

        // Basic Drools parsing - this is simplified
        // Real Drools has complex syntax including Java code

        let rule_regex = Regex::new(r#"rule\s+"([^"]+)"\s+when\s+(.+?)\s+then\s+(.+?)\s+end"#)
            .context("Failed to compile Drools rule regex")?;

        for (line_num, captures) in rule_regex.captures_iter(source).enumerate() {
            let rule_name = captures.get(1).expect("regex capture group 1").as_str();
            let when_clause = captures.get(2).expect("regex capture group 2").as_str();
            let then_clause = captures.get(3).expect("regex capture group 3").as_str();

            // Create enhanced rule
            match self.parse_drools_rule(rule_name, when_clause, then_clause) {
                Ok(rule) => {
                    if !rule.body.is_empty() || !rule.head.is_empty() {
                        rules.push(rule);
                        warnings.push(MigrationWarning {
                            message: format!(
                                "Drools rule '{}' migrated - complex DRL features (Java code, salience, etc.) not supported",
                                rule_name
                            ),
                            line: Some(line_num + 1),
                            severity: WarningSeverity::Info,
                        });
                    } else {
                        warnings.push(MigrationWarning {
                            message: format!(
                                "Drools rule '{}' skipped - no parseable patterns found",
                                rule_name
                            ),
                            line: Some(line_num + 1),
                            severity: WarningSeverity::Warning,
                        });
                    }
                }
                Err(e) => {
                    warnings.push(MigrationWarning {
                        message: format!("Failed to parse Drools rule '{}': {}", rule_name, e),
                        line: Some(line_num + 1),
                        severity: WarningSeverity::Error,
                    });
                }
            }
        }

        info!("Migrated {} Drools rules", rules.len());
        Ok(rules)
    }

    /// Parse Drools rule
    fn parse_drools_rule(&self, name: &str, when_clause: &str, then_clause: &str) -> Result<Rule> {
        // Parse when clause (conditions/patterns)
        let body = self.parse_drools_when_clause(when_clause)?;

        // Parse then clause (actions/assertions)
        let head = self.parse_drools_then_clause(then_clause)?;

        if body.is_empty() && head.is_empty() {
            warn!(
                "Drools rule '{}' has no parseable conditions or actions",
                name
            );
        }

        Ok(Rule {
            name: name.to_string(),
            body,
            head,
        })
    }

    /// Parse Drools when clause
    fn parse_drools_when_clause(&self, when_clause: &str) -> Result<Vec<RuleAtom>> {
        let mut atoms = Vec::new();

        // Pattern: ClassName(field == value, field2 == value2)
        let pattern_regex =
            Regex::new(r"(\w+)\s*\((.*?)\)").context("Failed to compile Drools pattern regex")?;

        for captures in pattern_regex.captures_iter(when_clause) {
            let class_name = captures.get(1).expect("regex capture group 1").as_str();
            let conditions = captures.get(2).expect("regex capture group 2").as_str();

            // Parse conditions
            for condition in conditions.split(',') {
                let condition = condition.trim();
                if condition.is_empty() {
                    continue;
                }

                // Pattern: field == value or field : value
                if let Some((field, value)) = self.parse_drools_condition(condition) {
                    // Create triple: ?instance field value
                    atoms.push(RuleAtom::Triple {
                        subject: Term::Variable(format!("{}Instance", class_name)),
                        predicate: Term::Constant(field),
                        object: self.parse_drools_value(&value),
                    });
                }
            }

            // Add type triple: ?instance rdf:type ClassName
            atoms.push(RuleAtom::Triple {
                subject: Term::Variable(format!("{}Instance", class_name)),
                predicate: Term::Constant("rdf:type".to_string()),
                object: Term::Constant(class_name.to_string()),
            });
        }

        Ok(atoms)
    }

    /// Parse Drools then clause
    fn parse_drools_then_clause(&self, then_clause: &str) -> Result<Vec<RuleAtom>> {
        let mut atoms = Vec::new();

        // Pattern: insert(new ClassName(field: value))
        let insert_regex = Regex::new(r"insert\s*\(\s*new\s+(\w+)\s*\((.*?)\)\s*\)")
            .context("Failed to compile Drools insert regex")?;

        for captures in insert_regex.captures_iter(then_clause) {
            let class_name = captures.get(1).expect("regex capture group 1").as_str();
            let params = captures.get(2).expect("regex capture group 2").as_str();

            // Add type assertion
            atoms.push(RuleAtom::Triple {
                subject: Term::Variable(format!("new{}", class_name)),
                predicate: Term::Constant("rdf:type".to_string()),
                object: Term::Constant(class_name.to_string()),
            });

            // Parse parameters
            for param in params.split(',') {
                let param = param.trim();
                if let Some((field, value)) = self.parse_drools_condition(param) {
                    atoms.push(RuleAtom::Triple {
                        subject: Term::Variable(format!("new{}", class_name)),
                        predicate: Term::Constant(field),
                        object: self.parse_drools_value(&value),
                    });
                }
            }
        }

        // Pattern: modify(variable) { setField(value) }
        let modify_regex = Regex::new(r"modify\s*\(\s*(\w+)\s*\)\s*\{([^}]+)\}")
            .context("Failed to compile Drools modify regex")?;

        // Parse setter calls: setField(value) - compile regex outside loop
        let setter_regex =
            Regex::new(r"set(\w+)\s*\(([^)]+)\)").context("Failed to compile setter regex")?;

        for captures in modify_regex.captures_iter(then_clause) {
            let var_name = captures.get(1).expect("regex capture group 1").as_str();
            let modifications = captures.get(2).expect("regex capture group 2").as_str();

            for setter_captures in setter_regex.captures_iter(modifications) {
                let field_name = setter_captures
                    .get(1)
                    .expect("regex capture group 1")
                    .as_str();
                let value = setter_captures
                    .get(2)
                    .expect("regex capture group 2")
                    .as_str()
                    .trim();

                atoms.push(RuleAtom::Triple {
                    subject: Term::Variable(var_name.to_string()),
                    predicate: Term::Constant(field_name.to_string()),
                    object: self.parse_drools_value(value),
                });
            }
        }

        Ok(atoms)
    }

    /// Parse Drools condition (field == value or field : value)
    fn parse_drools_condition(&self, condition: &str) -> Option<(String, String)> {
        // Try == operator
        if let Some(eq_pos) = condition.find("==") {
            let field = condition[..eq_pos].trim().to_string();
            let value = condition[eq_pos + 2..].trim().to_string();
            return Some((field, value));
        }

        // Try : operator
        if let Some(colon_pos) = condition.find(':') {
            let field = condition[..colon_pos].trim().to_string();
            let value = condition[colon_pos + 1..].trim().to_string();
            return Some((field, value));
        }

        None
    }

    /// Parse Drools value (string literal, number, or variable)
    fn parse_drools_value(&self, value: &str) -> Term {
        let value = value.trim();

        // String literal
        if (value.starts_with('"') && value.ends_with('"'))
            || (value.starts_with('\'') && value.ends_with('\''))
        {
            return Term::Literal(value[1..value.len() - 1].to_string());
        }

        // Variable (starts with $)
        if let Some(var_name) = value.strip_prefix('$') {
            return Term::Variable(var_name.to_string());
        }

        // Number or identifier
        if value
            .chars()
            .all(|c| c.is_numeric() || c == '.' || c == '-')
        {
            Term::Literal(value.to_string())
        } else {
            Term::Constant(value.to_string())
        }
    }

    /// Migrate from CLIPS format
    fn migrate_clips(
        &mut self,
        source: &str,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<Vec<Rule>> {
        let mut rules = Vec::new();

        // CLIPS rule format: (defrule name (pattern) => (action))
        let rule_regex = Regex::new(r"\(defrule\s+(\S+)\s+(.+?)\s+=>\s+(.+?)\)")
            .context("Failed to compile CLIPS rule regex")?;

        for (line_num, captures) in rule_regex.captures_iter(source).enumerate() {
            let rule_name = captures.get(1).expect("regex capture group 1").as_str();
            let pattern_clause = captures.get(2).expect("regex capture group 2").as_str();
            let action_clause = captures.get(3).expect("regex capture group 3").as_str();

            match self.parse_clips_rule(rule_name, pattern_clause, action_clause) {
                Ok(rule) => {
                    if !rule.body.is_empty() || !rule.head.is_empty() {
                        rules.push(rule);
                        warnings.push(MigrationWarning {
                            message: format!(
                                "CLIPS rule '{}' migrated - procedural attachments and advanced features not supported",
                                rule_name
                            ),
                            line: Some(line_num + 1),
                            severity: WarningSeverity::Info,
                        });
                    } else {
                        warnings.push(MigrationWarning {
                            message: format!(
                                "CLIPS rule '{}' skipped - no parseable patterns found",
                                rule_name
                            ),
                            line: Some(line_num + 1),
                            severity: WarningSeverity::Warning,
                        });
                    }
                }
                Err(e) => {
                    warnings.push(MigrationWarning {
                        message: format!("Failed to parse CLIPS rule '{}': {}", rule_name, e),
                        line: Some(line_num + 1),
                        severity: WarningSeverity::Error,
                    });
                }
            }
        }

        info!("Migrated {} CLIPS rules", rules.len());
        Ok(rules)
    }

    /// Parse CLIPS rule
    fn parse_clips_rule(
        &self,
        name: &str,
        pattern_clause: &str,
        action_clause: &str,
    ) -> Result<Rule> {
        // Parse pattern clause (LHS)
        let body = self.parse_clips_patterns(pattern_clause)?;

        // Parse action clause (RHS)
        let head = self.parse_clips_actions(action_clause)?;

        if body.is_empty() && head.is_empty() {
            warn!("CLIPS rule '{}' has no parseable patterns or actions", name);
        }

        Ok(Rule {
            name: name.to_string(),
            body,
            head,
        })
    }

    /// Parse CLIPS patterns
    fn parse_clips_patterns(&self, patterns: &str) -> Result<Vec<RuleAtom>> {
        let mut atoms = Vec::new();

        // Pattern: (template-name (slot-name value))
        let pattern_regex = Regex::new(r"\((\w+)(?:\s+\(([^)]+)\))*\)")
            .context("Failed to compile CLIPS pattern regex")?;

        for captures in pattern_regex.captures_iter(patterns) {
            let template_name = captures.get(1).expect("regex capture group 1").as_str();

            // Skip control patterns
            if template_name == "test"
                || template_name == "not"
                || template_name == "and"
                || template_name == "or"
            {
                continue;
            }

            // Create type fact
            atoms.push(RuleAtom::Triple {
                subject: Term::Variable(format!("{}Instance", template_name)),
                predicate: Term::Constant("rdf:type".to_string()),
                object: Term::Constant(template_name.to_string()),
            });

            // Parse slot patterns if present
            if let Some(slots) = captures.get(2) {
                let slot_text = slots.as_str();
                // Pattern: (slot value) or slot value
                let slot_parts: Vec<&str> = slot_text.split_whitespace().collect();

                if slot_parts.len() >= 2 {
                    let slot_name = slot_parts[0];
                    let slot_value = slot_parts[1];

                    atoms.push(RuleAtom::Triple {
                        subject: Term::Variable(format!("{}Instance", template_name)),
                        predicate: Term::Constant(slot_name.to_string()),
                        object: self.parse_clips_value(slot_value),
                    });
                }
            }
        }

        Ok(atoms)
    }

    /// Parse CLIPS actions
    fn parse_clips_actions(&self, actions: &str) -> Result<Vec<RuleAtom>> {
        let mut atoms = Vec::new();

        // Pattern: (assert (template-name (slot value)))
        let assert_regex = Regex::new(r"\(assert\s+\((\w+)(?:\s+\(([^)]+)\))*\)\)")
            .context("Failed to compile CLIPS assert regex")?;

        for captures in assert_regex.captures_iter(actions) {
            let template_name = captures.get(1).expect("regex capture group 1").as_str();

            // Create type assertion
            atoms.push(RuleAtom::Triple {
                subject: Term::Variable(format!("new{}", template_name)),
                predicate: Term::Constant("rdf:type".to_string()),
                object: Term::Constant(template_name.to_string()),
            });

            // Parse slot values if present
            if let Some(slots) = captures.get(2) {
                let slot_text = slots.as_str();
                let slot_parts: Vec<&str> = slot_text.split_whitespace().collect();

                if slot_parts.len() >= 2 {
                    let slot_name = slot_parts[0];
                    let slot_value = slot_parts[1];

                    atoms.push(RuleAtom::Triple {
                        subject: Term::Variable(format!("new{}", template_name)),
                        predicate: Term::Constant(slot_name.to_string()),
                        object: self.parse_clips_value(slot_value),
                    });
                }
            }
        }

        // Pattern: (modify ?fact (slot value))
        let modify_regex = Regex::new(r"\(modify\s+\?(\w+)\s+\((\w+)\s+([^)]+)\)\)")
            .context("Failed to compile CLIPS modify regex")?;

        for captures in modify_regex.captures_iter(actions) {
            let var_name = captures.get(1).expect("regex capture group 1").as_str();
            let slot_name = captures.get(2).expect("regex capture group 2").as_str();
            let slot_value = captures.get(3).expect("regex capture group 3").as_str();

            atoms.push(RuleAtom::Triple {
                subject: Term::Variable(var_name.to_string()),
                predicate: Term::Constant(slot_name.to_string()),
                object: self.parse_clips_value(slot_value),
            });
        }

        Ok(atoms)
    }

    /// Parse CLIPS value (variable, string, or literal)
    fn parse_clips_value(&self, value: &str) -> Term {
        let value = value.trim();

        // Variable (starts with ?)
        if let Some(var_name) = value.strip_prefix('?') {
            return Term::Variable(var_name.to_string());
        }

        // String literal
        if (value.starts_with('"') && value.ends_with('"'))
            || (value.starts_with('\'') && value.ends_with('\''))
        {
            return Term::Literal(value[1..value.len() - 1].to_string());
        }

        // Symbol or number
        if value
            .chars()
            .all(|c| c.is_numeric() || c == '.' || c == '-')
        {
            Term::Literal(value.to_string())
        } else {
            Term::Constant(value.to_string())
        }
    }

    /// Expand namespace prefix
    fn expand_namespace(&self, term: &str) -> String {
        if let Some(colon_pos) = term.find(':') {
            let prefix = &term[..colon_pos];
            let local = &term[colon_pos + 1..];

            if let Some(namespace) = self.namespace_mappings.get(prefix) {
                return format!("{}{}", namespace, local);
            }
        }
        term.to_string()
    }
}

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

    #[test]
    fn test_migration_tool_creation() {
        let tool = MigrationTool::new();
        assert!(!tool.strict_mode);
        assert!(tool.namespace_mappings.is_empty());
    }

    #[test]
    fn test_migration_tool_with_strict_mode() {
        let tool = MigrationTool::new().with_strict_mode(true);
        assert!(tool.strict_mode);
    }

    #[test]
    fn test_namespace_mapping() {
        let mut tool = MigrationTool::new();
        tool.add_namespace_mapping("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");

        assert_eq!(
            tool.namespace_mappings.get("rdf"),
            Some(&"http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string())
        );
    }

    #[test]
    fn test_jena_simple_rule_migration() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let jena_rules = r#"
[rule1: (?a rdf:type Person) -> (?a rdf:type Human)]
"#;

        let result = tool.migrate(jena_rules, SourceFormat::Jena)?;

        assert_eq!(result.rules.len(), 1);
        assert_eq!(result.rules[0].name, "rule1");
        assert_eq!(result.source_format, SourceFormat::Jena);
        Ok(())
    }

    #[test]
    fn test_jena_multiple_rules() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let jena_rules = r#"
[rule1: (?x parent ?y) -> (?y hasParent ?x)]
[rule2: (?a knows ?b) -> (?b knows ?a)]
"#;

        let result = tool.migrate(jena_rules, SourceFormat::Jena)?;

        assert_eq!(result.rules.len(), 2);
        assert_eq!(result.rules[0].name, "rule1");
        assert_eq!(result.rules[1].name, "rule2");
        Ok(())
    }

    #[test]
    fn test_jena_with_comments() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let jena_rules = r#"
# This is a comment
[rule1: (?x parent ?y) -> (?y hasParent ?x)]
# Another comment
[rule2: (?a knows ?b) -> (?b knows ?a)]
"#;

        let result = tool.migrate(jena_rules, SourceFormat::Jena)?;

        assert_eq!(result.rules.len(), 2);
        Ok(())
    }

    #[test]
    fn test_parse_jena_term_variable() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        let term = tool.parse_jena_term("?x")?;
        assert!(matches!(term, Term::Variable(v) if v == "x"));
        Ok(())
    }

    #[test]
    fn test_parse_jena_term_constant() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        let term = tool.parse_jena_term("rdf:type")?;
        assert!(matches!(term, Term::Constant(c) if c == "rdf:type"));
        Ok(())
    }

    #[test]
    fn test_parse_jena_term_literal() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        let term = tool.parse_jena_term("\"John\"")?;
        assert!(matches!(term, Term::Literal(l) if l == "John"));
        Ok(())
    }

    #[test]
    fn test_migration_report_generation() {
        let result = MigrationResult {
            rules: vec![],
            warnings: vec![MigrationWarning {
                message: "Test warning".to_string(),
                line: Some(1),
                severity: WarningSeverity::Warning,
            }],
            source_format: SourceFormat::Jena,
            original_count: 10,
            migrated_count: 9,
        };

        let report = result.generate_report();

        assert!(report.contains("Apache Jena"));
        assert!(report.contains("Original rules:  10"));
        assert!(report.contains("Migrated rules:  9"));
        assert!(report.contains("Test warning"));
    }

    #[test]
    fn test_migration_success_check() {
        let result_success = MigrationResult {
            rules: vec![],
            warnings: vec![MigrationWarning {
                message: "Info".to_string(),
                line: None,
                severity: WarningSeverity::Info,
            }],
            source_format: SourceFormat::Jena,
            original_count: 1,
            migrated_count: 1,
        };

        assert!(result_success.is_successful());

        let result_failure = MigrationResult {
            rules: vec![],
            warnings: vec![MigrationWarning {
                message: "Error".to_string(),
                line: None,
                severity: WarningSeverity::Error,
            }],
            source_format: SourceFormat::Jena,
            original_count: 1,
            migrated_count: 0,
        };

        assert!(!result_failure.is_successful());
    }

    #[test]
    fn test_expand_namespace() {
        let mut tool = MigrationTool::new();
        tool.add_namespace_mapping("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");

        let expanded = tool.expand_namespace("rdf:type");
        assert_eq!(expanded, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
    }

    #[test]
    fn test_source_format_names() {
        assert_eq!(SourceFormat::Jena.name(), "Apache Jena");
        assert_eq!(SourceFormat::Drools.name(), "Drools DRL");
        assert_eq!(SourceFormat::Clips.name(), "CLIPS");
    }

    #[test]
    fn test_drools_simple_rule() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let drools_rules = r#"
rule "adult-rule"
when
    Person(age == 25)
then
    insert(new Adult(status: "verified"))
end
"#;

        let result = tool.migrate(drools_rules, SourceFormat::Drools)?;

        assert_eq!(result.rules.len(), 1);
        assert_eq!(result.rules[0].name, "adult-rule");
        assert!(!result.rules[0].body.is_empty());
        assert!(!result.rules[0].head.is_empty());
        Ok(())
    }

    #[test]
    fn test_drools_with_insert() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let drools_rules = r#"
rule "create-employee"
when
    Person(name == "John")
then
    insert(new Employee(name: "John", role: "Developer"))
end
"#;

        let result = tool.migrate(drools_rules, SourceFormat::Drools)?;

        assert_eq!(result.rules.len(), 1);
        let rule = &result.rules[0];

        // Should have head atoms for type and properties
        assert!(rule.head.iter().any(|atom| {
            matches!(atom, RuleAtom::Triple {
                predicate: Term::Constant(p),
                object: Term::Constant(o), ..
            } if p == "rdf:type" && o == "Employee")
        }));
        Ok(())
    }

    #[test]
    fn test_drools_with_modify() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let drools_rules = r#"
rule "update-status"
when
    Person(name == "Alice")
then
    modify(person) { setStatus("active") }
end
"#;

        let result = tool.migrate(drools_rules, SourceFormat::Drools)?;

        assert_eq!(result.rules.len(), 1);
        let rule = &result.rules[0];

        // Should have head atoms for modifications
        assert!(rule.head.iter().any(|atom| {
            matches!(atom, RuleAtom::Triple {
                predicate: Term::Constant(p), ..
            } if p == "Status")
        }));
        Ok(())
    }

    #[test]
    fn test_drools_value_parsing() {
        let tool = MigrationTool::new();

        // Test string literal
        let value1 = tool.parse_drools_value("\"hello\"");
        assert!(matches!(value1, Term::Literal(v) if v == "hello"));

        // Test variable
        let value2 = tool.parse_drools_value("$var");
        assert!(matches!(value2, Term::Variable(v) if v == "var"));

        // Test number
        let value3 = tool.parse_drools_value("42");
        assert!(matches!(value3, Term::Literal(v) if v == "42"));

        // Test identifier
        let value4 = tool.parse_drools_value("active");
        assert!(matches!(value4, Term::Constant(v) if v == "active"));
    }

    #[test]
    fn test_drools_condition_parsing() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        // Test == operator
        let (field, value) = tool
            .parse_drools_condition("age == 18")
            .ok_or("expected Some value")?;
        assert_eq!(field, "age");
        assert_eq!(value, "18");

        // Test : operator
        let (field2, value2) = tool
            .parse_drools_condition("status : active")
            .ok_or("expected Some value")?;
        assert_eq!(field2, "status");
        assert_eq!(value2, "active");
        Ok(())
    }

    #[test]
    fn test_clips_simple_rule() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let clips_rules = r#"
(defrule adult-check (person (age 25)) => (assert (adult (verified yes))))
"#;

        let result = tool.migrate(clips_rules, SourceFormat::Clips)?;

        assert_eq!(result.rules.len(), 1);
        assert_eq!(result.rules[0].name, "adult-check");
        Ok(())
    }

    #[test]
    fn test_clips_with_assert() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let clips_rules = r#"
(defrule make-employee (person (name John)) => (assert (employee (name John))))
"#;

        let result = tool.migrate(clips_rules, SourceFormat::Clips)?;

        // Rule should be created
        assert_eq!(result.rules.len(), 1);
        assert_eq!(result.rules[0].name, "make-employee");

        // Migration should complete successfully
        assert!(result.source_format == SourceFormat::Clips);
        Ok(())
    }

    #[test]
    fn test_clips_with_modify() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let clips_rules = r#"
(defrule update-status (person) => (modify ?person (status active)))
"#;

        let result = tool.migrate(clips_rules, SourceFormat::Clips)?;

        // Rule should be created
        assert_eq!(result.rules.len(), 1);
        assert_eq!(result.rules[0].name, "update-status");

        // Migration should complete successfully
        assert!(result.source_format == SourceFormat::Clips);
        Ok(())
    }

    #[test]
    fn test_clips_value_parsing() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        // Test variable
        let value1 = tool.parse_clips_value("?x");
        assert!(matches!(value1, Term::Variable(v) if v == "x"));

        // Test string literal
        let value2 = tool.parse_clips_value("\"hello\"");
        assert!(matches!(value2, Term::Literal(v) if v == "hello"));

        // Test number
        let value3 = tool.parse_clips_value("42");
        assert!(matches!(value3, Term::Literal(v) if v == "42"));

        // Test symbol
        let value4 = tool.parse_clips_value("active");
        assert!(matches!(value4, Term::Constant(v) if v == "active"));
        Ok(())
    }

    #[test]
    fn test_drools_multiple_conditions() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let drools_rules = r#"
rule "complex-rule"
when
    Person(age == 25, status == "active")
then
    insert(new Adult(verified: true))
end
"#;

        let result = tool.migrate(drools_rules, SourceFormat::Drools)?;

        assert_eq!(result.rules.len(), 1);
        let rule = &result.rules[0];

        // Should have multiple body atoms for multiple conditions
        assert!(rule.body.len() >= 2);
        Ok(())
    }

    #[test]
    fn test_migration_warnings_severity() {
        let result = MigrationResult {
            rules: vec![],
            warnings: vec![
                MigrationWarning {
                    message: "Info".to_string(),
                    line: Some(1),
                    severity: WarningSeverity::Info,
                },
                MigrationWarning {
                    message: "Warning".to_string(),
                    line: Some(2),
                    severity: WarningSeverity::Warning,
                },
                MigrationWarning {
                    message: "Error".to_string(),
                    line: Some(3),
                    severity: WarningSeverity::Error,
                },
            ],
            source_format: SourceFormat::Jena,
            original_count: 3,
            migrated_count: 0,
        };

        let report = result.generate_report();

        assert!(report.contains("[INFO]"));
        assert!(report.contains("[WARN]"));
        assert!(report.contains("[ERROR]"));
    }

    #[test]
    fn test_empty_drools_rule() -> Result<(), Box<dyn std::error::Error>> {
        let mut tool = MigrationTool::new();

        let drools_rules = r#"
rule "empty"
when
then
end
"#;

        let result = tool.migrate(drools_rules, SourceFormat::Drools)?;

        // Empty rules should either be skipped (0 rules) or have no body/head
        // Migration should complete without error
        assert!(result.source_format == SourceFormat::Drools);
        if !result.rules.is_empty() {
            // If rule was created, it should be empty
            assert!(result.rules[0].body.is_empty() && result.rules[0].head.is_empty());
        }
        Ok(())
    }

    #[test]
    fn test_clips_pattern_filtering() -> Result<(), Box<dyn std::error::Error>> {
        let tool = MigrationTool::new();

        // Control patterns should be skipped
        let patterns = "(test (> ?x 5)) (person (age ?x))";
        let atoms = tool.parse_clips_patterns(patterns)?;

        // Should only include person pattern, not test
        assert!(atoms.iter().any(|atom| {
            matches!(atom, RuleAtom::Triple {
                object: Term::Constant(o), ..
            } if o == "person")
        }));
        Ok(())
    }
}