Skip to main content

oxirs_rule/
integration.rs

1//! Integration Bridge with OxiRS Core
2//!
3//! This module provides seamless integration between the oxirs-rule engine
4//! and oxirs-core RDF model, allowing rules to operate directly on core RDF types.
5
6use crate::{Rule, RuleAtom, RuleEngine, Term};
7use anyhow::Result;
8use oxirs_core::model::{GraphName, Literal, NamedNode, Object, Predicate, Quad, Subject, Triple};
9use oxirs_core::{OxirsError, RdfStore};
10use std::collections::HashMap;
11use tracing::{debug, info};
12
13/// Integration bridge for connecting oxirs-rule with oxirs-core
14pub struct RuleIntegration {
15    /// Core rule engine
16    pub rule_engine: RuleEngine,
17    /// Core RDF store
18    pub store: RdfStore,
19    /// Namespace prefix mappings for IRI expansion/compression
20    namespace_prefixes: HashMap<String, String>,
21}
22
23impl Default for RuleIntegration {
24    fn default() -> Self {
25        Self::new()
26    }
27}
28
29impl RuleIntegration {
30    /// Create a new rule integration with an empty store
31    pub fn new() -> Self {
32        let mut prefixes = HashMap::new();
33        // Initialize with common W3C namespaces
34        prefixes.insert(
35            "rdf".to_string(),
36            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
37        );
38        prefixes.insert(
39            "rdfs".to_string(),
40            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
41        );
42        prefixes.insert(
43            "owl".to_string(),
44            "http://www.w3.org/2002/07/owl#".to_string(),
45        );
46        prefixes.insert(
47            "xsd".to_string(),
48            "http://www.w3.org/2001/XMLSchema#".to_string(),
49        );
50
51        Self {
52            rule_engine: RuleEngine::new(),
53            store: oxirs_core::RdfStore::new().expect("RdfStore::new should not fail"),
54            namespace_prefixes: prefixes,
55        }
56    }
57
58    /// Create integration with an existing store
59    pub fn with_store(store: RdfStore) -> Self {
60        let mut prefixes = HashMap::new();
61        // Initialize with common W3C namespaces
62        prefixes.insert(
63            "rdf".to_string(),
64            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
65        );
66        prefixes.insert(
67            "rdfs".to_string(),
68            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
69        );
70        prefixes.insert(
71            "owl".to_string(),
72            "http://www.w3.org/2002/07/owl#".to_string(),
73        );
74        prefixes.insert(
75            "xsd".to_string(),
76            "http://www.w3.org/2001/XMLSchema#".to_string(),
77        );
78
79        Self {
80            rule_engine: RuleEngine::new(),
81            store,
82            namespace_prefixes: prefixes,
83        }
84    }
85
86    /// Add a rule to the engine
87    pub fn add_rule(&mut self, rule: Rule) {
88        self.rule_engine.add_rule(rule);
89    }
90
91    /// Add multiple rules
92    pub fn add_rules(&mut self, rules: Vec<Rule>) {
93        self.rule_engine.add_rules(rules);
94    }
95
96    /// Load facts from the core store into the rule engine
97    pub fn load_facts_from_store(&mut self) -> Result<usize> {
98        let quads = self.store.query_quads(None, None, None, None)?;
99        let rule_atoms: Vec<RuleAtom> = quads
100            .into_iter()
101            .map(|quad| self.quad_to_rule_atom(&quad))
102            .collect();
103
104        let fact_count = rule_atoms.len();
105        self.rule_engine.add_facts(rule_atoms);
106
107        info!("Loaded {} facts from store into rule engine", fact_count);
108        Ok(fact_count)
109    }
110
111    /// Apply rules and store derived facts back to the core store
112    pub fn apply_rules(&mut self) -> Result<usize> {
113        // Load current facts from store
114        self.load_facts_from_store()?;
115
116        // Apply forward chaining
117        let derived_facts = self.rule_engine.forward_chain(&[])?;
118
119        // Convert derived facts back to core model and store them
120        let mut new_fact_count = 0;
121        for rule_atom in derived_facts {
122            if let Ok(triple) = self.rule_atom_to_triple(&rule_atom) {
123                // Convert triple to quad with default graph
124                let quad = Quad::new_default_graph(
125                    triple.subject().clone(),
126                    triple.predicate().clone(),
127                    triple.object().clone(),
128                );
129                if self.store.insert_quad(quad)? {
130                    new_fact_count += 1;
131                }
132            }
133        }
134
135        info!("Applied rules and derived {} new facts", new_fact_count);
136        Ok(new_fact_count)
137    }
138
139    /// Query the rule engine using backward chaining for a goal
140    pub fn prove_goal(&mut self, goal_triple: &Triple) -> Result<bool> {
141        // Convert triple to rule atom
142        let goal_atom = self.triple_to_rule_atom(goal_triple);
143
144        // Load current facts
145        self.load_facts_from_store()?;
146
147        // Attempt to prove the goal
148        self.rule_engine.backward_chain(&goal_atom)
149    }
150
151    /// Find all solutions for a query pattern
152    pub fn query_with_rules(
153        &mut self,
154        subject: Option<&Subject>,
155        predicate: Option<&Predicate>,
156        object: Option<&Object>,
157    ) -> Result<Vec<Triple>> {
158        // First get direct matches from store
159        let quads = self.store.query_quads(subject, predicate, object, None)?;
160        let _direct_matches: Vec<Triple> = quads
161            .into_iter()
162            .map(|quad| {
163                Triple::new(
164                    quad.subject().clone(),
165                    quad.predicate().clone(),
166                    quad.object().clone(),
167                )
168            })
169            .collect();
170
171        // Apply rules to potentially derive more facts
172        self.apply_rules()?;
173
174        // Query again after applying rules
175        let enhanced_quads = self.store.query_quads(subject, predicate, object, None)?;
176        let rule_enhanced_matches: Vec<Triple> = enhanced_quads
177            .into_iter()
178            .map(|quad| {
179                Triple::new(
180                    quad.subject().clone(),
181                    quad.predicate().clone(),
182                    quad.object().clone(),
183                )
184            })
185            .collect();
186
187        Ok(rule_enhanced_matches)
188    }
189
190    /// Get comprehensive statistics about the integration
191    pub fn get_integration_stats(&self) -> Result<IntegrationStats> {
192        let store_quad_count = self.store.len()?;
193        let rule_fact_count = self.rule_engine.get_facts().len();
194        let rule_count = self.rule_engine.rules.len();
195
196        Ok(IntegrationStats {
197            store_quad_count,
198            rule_fact_count,
199            rule_count,
200        })
201    }
202
203    /// Convert a core Triple to a RuleAtom
204    fn triple_to_rule_atom(&self, triple: &Triple) -> RuleAtom {
205        RuleAtom::Triple {
206            subject: self.subject_to_term(triple.subject()),
207            predicate: self.predicate_to_term(triple.predicate()),
208            object: self.object_to_term(triple.object()),
209        }
210    }
211
212    /// Convert a core Quad to a RuleAtom (ignoring graph for now)
213    fn quad_to_rule_atom(&self, quad: &Quad) -> RuleAtom {
214        RuleAtom::Triple {
215            subject: self.subject_to_term(quad.subject()),
216            predicate: self.predicate_to_term(quad.predicate()),
217            object: self.object_to_term(quad.object()),
218        }
219    }
220
221    /// Convert a RuleAtom to a core Triple (if possible)
222    fn rule_atom_to_triple(&self, atom: &RuleAtom) -> Result<Triple> {
223        match atom {
224            RuleAtom::Triple {
225                subject,
226                predicate,
227                object,
228            } => {
229                let core_subject = self.term_to_subject(subject)?;
230                let core_predicate = self.term_to_predicate(predicate)?;
231                let core_object = self.term_to_object(object)?;
232
233                Ok(Triple::new(core_subject, core_predicate, core_object))
234            }
235            RuleAtom::Builtin { .. } => Err(anyhow::anyhow!(
236                "Cannot convert builtin rule atom to triple"
237            )),
238            RuleAtom::NotEqual { .. } => Err(anyhow::anyhow!(
239                "Cannot convert not-equal constraint to triple"
240            )),
241            RuleAtom::GreaterThan { .. } => Err(anyhow::anyhow!(
242                "Cannot convert greater-than constraint to triple"
243            )),
244            RuleAtom::LessThan { .. } => Err(anyhow::anyhow!(
245                "Cannot convert less-than constraint to triple"
246            )),
247        }
248    }
249
250    /// Convert core Subject to rule Term
251    fn subject_to_term(&self, subject: &Subject) -> Term {
252        match subject {
253            Subject::NamedNode(node) => Term::Constant(node.as_str().to_string()),
254            Subject::BlankNode(node) => Term::Constant(format!("_:{}", node.as_str())),
255            Subject::Variable(var) => Term::Variable(var.as_str().to_string()),
256            Subject::QuotedTriple(_) => {
257                // Skip quoted triples for now
258                Term::Constant("_:quoted_triple".to_string())
259            }
260        }
261    }
262
263    /// Convert core Predicate to rule Term
264    fn predicate_to_term(&self, predicate: &Predicate) -> Term {
265        match predicate {
266            Predicate::NamedNode(node) => Term::Constant(node.as_str().to_string()),
267            Predicate::Variable(var) => Term::Variable(var.as_str().to_string()),
268        }
269    }
270
271    /// Convert core Object to rule Term
272    fn object_to_term(&self, object: &Object) -> Term {
273        match object {
274            Object::NamedNode(node) => Term::Constant(node.as_str().to_string()),
275            Object::BlankNode(node) => Term::Constant(format!("_:{}", node.as_str())),
276            Object::Literal(literal) => Term::Literal(literal.value().to_string()),
277            Object::Variable(var) => Term::Variable(var.as_str().to_string()),
278            Object::QuotedTriple(_) => {
279                // Skip quoted triples for now
280                Term::Constant("_:quoted_triple".to_string())
281            }
282        }
283    }
284
285    /// Convert rule Term to core Subject
286    fn term_to_subject(&self, term: &Term) -> Result<Subject> {
287        match term {
288            Term::Constant(value) => {
289                if let Some(stripped) = value.strip_prefix("_:") {
290                    // Blank node
291                    Ok(Subject::BlankNode(oxirs_core::BlankNode::new(stripped)?))
292                } else {
293                    // Named node
294                    Ok(Subject::NamedNode(NamedNode::new(value)?))
295                }
296            }
297            Term::Variable(_) => Err(anyhow::anyhow!(
298                "Cannot convert unbound variable to subject"
299            )),
300            Term::Literal(_) => Err(anyhow::anyhow!("Literals cannot be subjects in RDF")),
301            Term::Function { name, .. } => Err(anyhow::anyhow!(
302                "Cannot convert function term '{}' to subject - function terms are not valid RDF subjects",
303                name
304            )),
305        }
306    }
307
308    /// Convert rule Term to core Predicate
309    fn term_to_predicate(&self, term: &Term) -> Result<Predicate> {
310        match term {
311            Term::Constant(value) => Ok(Predicate::NamedNode(NamedNode::new(value)?)),
312            Term::Variable(_) => Err(anyhow::anyhow!(
313                "Cannot convert unbound variable to predicate"
314            )),
315            Term::Literal(_) => Err(anyhow::anyhow!("Literals cannot be predicates in RDF")),
316            Term::Function { name, .. } => Err(anyhow::anyhow!(
317                "Cannot convert function term '{}' to predicate - function terms are not valid RDF predicates",
318                name
319            )),
320        }
321    }
322
323    /// Convert rule Term to core Object
324    fn term_to_object(&self, term: &Term) -> Result<Object> {
325        match term {
326            Term::Constant(value) => {
327                if let Some(stripped) = value.strip_prefix("_:") {
328                    // Blank node
329                    Ok(Object::BlankNode(oxirs_core::BlankNode::new(stripped)?))
330                } else {
331                    // Named node
332                    Ok(Object::NamedNode(NamedNode::new(value)?))
333                }
334            }
335            Term::Literal(value) => Ok(Object::Literal(Literal::new(value))),
336            Term::Variable(_) => Err(anyhow::anyhow!("Cannot convert unbound variable to object")),
337            Term::Function { name, args } => {
338                // Convert function terms to complex literals for RDF representation
339                let func_repr = format!("{}({})", name, args.len());
340                Ok(Object::Literal(Literal::new_typed_literal(
341                    &func_repr,
342                    NamedNode::new("http://oxirs.org/function")?,
343                )))
344            }
345        }
346    }
347
348    /// Enhanced streaming data processing
349    pub fn process_stream(
350        &mut self,
351        data_stream: impl Iterator<Item = Result<Triple, OxirsError>>,
352    ) -> Result<StreamingStats> {
353        let mut processed = 0;
354        let mut derived = 0;
355        let mut errors = 0;
356
357        for triple_result in data_stream {
358            match triple_result {
359                Ok(triple) => {
360                    // Convert triple to quad with default graph
361                    let quad = Quad::new_default_graph(
362                        triple.subject().clone(),
363                        triple.predicate().clone(),
364                        triple.object().clone(),
365                    );
366                    if self.store.insert_quad(quad)? {
367                        processed += 1;
368
369                        // Apply rules incrementally
370                        if processed % 1000 == 0 {
371                            let new_facts = self.apply_rules()?;
372                            derived += new_facts;
373                            info!("Processed {} triples, derived {} facts", processed, derived);
374                        }
375                    }
376                }
377                Err(_) => {
378                    errors += 1;
379                }
380            }
381        }
382
383        // Final rule application
384        let final_derived = self.apply_rules()?;
385        derived += final_derived;
386
387        Ok(StreamingStats {
388            processed_triples: processed,
389            derived_facts: derived,
390            errors,
391        })
392    }
393
394    /// Enhanced dataset integration with named graphs
395    pub fn process_named_graph(
396        &mut self,
397        graph_name: &GraphName,
398        triples: Vec<Triple>,
399    ) -> Result<ProcessingStats> {
400        let start_time = std::time::Instant::now();
401        let mut processed = 0;
402        #[allow(unused_assignments)]
403        let mut derived = 0;
404
405        // Insert triples into named graph
406        for triple in triples {
407            let quad = Quad::new(
408                triple.subject().clone(),
409                triple.predicate().clone(),
410                triple.object().clone(),
411                graph_name.clone(),
412            );
413
414            if self.store.insert_quad(quad)? {
415                processed += 1;
416            }
417        }
418
419        // Apply rules to the named graph context
420        let before_rules = self.store.len()?;
421        self.apply_rules()?;
422        let after_rules = self.store.len()?;
423        derived = after_rules - before_rules;
424
425        info!(
426            "Processed {} triples in named graph, derived {} new facts",
427            processed, derived
428        );
429
430        Ok(ProcessingStats {
431            processed_count: processed,
432            derived_count: derived,
433            processing_time: start_time.elapsed(),
434        })
435    }
436
437    /// Enhanced IRI validation and normalization
438    pub fn validate_and_normalize_iri(&self, iri_str: &str) -> Result<NamedNode> {
439        // Check for common IRI patterns and normalize
440        let normalized = if iri_str.starts_with('<') && iri_str.ends_with('>') {
441            // Remove angle brackets
442            &iri_str[1..iri_str.len() - 1]
443        } else if iri_str.contains(':') && !iri_str.starts_with("http") {
444            // Might be a prefixed IRI
445            return self.expand_prefixed_iri(iri_str).and_then(|expanded| {
446                NamedNode::new(&expanded).map_err(|e| anyhow::anyhow!("IRI creation failed: {}", e))
447            });
448        } else {
449            iri_str
450        };
451
452        // Validate IRI format
453        if !normalized.starts_with("http://")
454            && !normalized.starts_with("https://")
455            && !normalized.starts_with("urn:")
456        {
457            return Err(anyhow::anyhow!("Invalid IRI format: {}", iri_str));
458        }
459
460        NamedNode::new(normalized).map_err(|e| anyhow::anyhow!("IRI creation failed: {}", e))
461    }
462
463    /// Enhanced datatype validation and conversion
464    pub fn validate_and_convert_literal(
465        &self,
466        value: &str,
467        datatype_iri: Option<&str>,
468    ) -> Result<Literal> {
469        let literal = if let Some(dt_iri) = datatype_iri {
470            let datatype = NamedNode::new(dt_iri)?;
471
472            // Validate value against datatype
473            match dt_iri {
474                "http://www.w3.org/2001/XMLSchema#integer" => {
475                    value
476                        .parse::<i64>()
477                        .map_err(|_| anyhow::anyhow!("Invalid integer value: {}", value))?;
478                }
479                "http://www.w3.org/2001/XMLSchema#decimal" => {
480                    value
481                        .parse::<f64>()
482                        .map_err(|_| anyhow::anyhow!("Invalid decimal value: {}", value))?;
483                }
484                "http://www.w3.org/2001/XMLSchema#boolean" => match value {
485                    "true" | "false" | "1" | "0" => {}
486                    _ => return Err(anyhow::anyhow!("Invalid boolean value: {}", value)),
487                },
488                "http://www.w3.org/2001/XMLSchema#dateTime" => {
489                    // Basic ISO 8601 validation
490                    if !value.contains('T')
491                        || (!value.contains('Z') && !value.contains('+') && !value.contains('-'))
492                    {
493                        return Err(anyhow::anyhow!("Invalid dateTime format: {}", value));
494                    }
495                }
496                _ => {
497                    // For unknown datatypes, just accept the value
498                    debug!("Unknown datatype {}, accepting value as-is", dt_iri);
499                }
500            }
501
502            Literal::new_typed_literal(value, datatype)
503        } else {
504            Literal::new(value)
505        };
506
507        Ok(literal)
508    }
509
510    /// Enhanced bulk processing with transaction support
511    pub fn bulk_process_with_transactions(
512        &mut self,
513        triples: Vec<Triple>,
514        batch_size: usize,
515    ) -> Result<BulkProcessingStats> {
516        let start_time = std::time::Instant::now();
517        let mut total_processed = 0;
518        let mut total_derived = 0;
519        let mut batch_count = 0;
520
521        for triple_batch in triples.chunks(batch_size) {
522            // Begin transaction (conceptual - oxirs-core may not have transactions yet)
523            let _batch_start = self.store.len()?;
524
525            // Process batch
526            for triple in triple_batch {
527                // Convert triple to quad with default graph
528                let quad = Quad::new_default_graph(
529                    triple.subject().clone(),
530                    triple.predicate().clone(),
531                    triple.object().clone(),
532                );
533                if self.store.insert_quad(quad)? {
534                    total_processed += 1;
535                }
536            }
537
538            // Apply rules to batch
539            let derived_count = self.apply_rules()?;
540            total_derived += derived_count;
541            batch_count += 1;
542
543            info!(
544                "Processed batch {}: {} triples, {} derived",
545                batch_count,
546                triple_batch.len(),
547                derived_count
548            );
549        }
550
551        Ok(BulkProcessingStats {
552            total_processed,
553            total_derived,
554            batch_count,
555            processing_time: start_time.elapsed(),
556        })
557    }
558
559    /// Enhanced error recovery and partial processing
560    pub fn process_with_error_recovery(
561        &mut self,
562        triples: Vec<Result<Triple, OxirsError>>,
563    ) -> Result<ErrorRecoveryStats> {
564        let mut successful = 0;
565        let mut failed = 0;
566        let mut derived = 0;
567        let mut error_details = Vec::new();
568
569        for (index, triple_result) in triples.into_iter().enumerate() {
570            match triple_result {
571                Ok(triple) => {
572                    // Convert triple to quad with default graph
573                    let quad = Quad::new_default_graph(
574                        triple.subject().clone(),
575                        triple.predicate().clone(),
576                        triple.object().clone(),
577                    );
578                    match self.store.insert_quad(quad) {
579                        Ok(inserted) => {
580                            if inserted {
581                                successful += 1;
582                            }
583                        }
584                        Err(e) => {
585                            failed += 1;
586                            error_details.push(format!("Triple {index}: {e}"));
587                        }
588                    }
589                }
590                Err(e) => {
591                    failed += 1;
592                    error_details.push(format!("Parse error {index}: {e}"));
593                }
594            }
595        }
596
597        // Apply rules on successfully processed data
598        if successful > 0 {
599            derived = self.apply_rules()?;
600        }
601
602        Ok(ErrorRecoveryStats {
603            successful_triples: successful,
604            failed_triples: failed,
605            derived_facts: derived,
606            error_details,
607        })
608    }
609
610    /// Enhanced namespace management for better IRI handling
611    pub fn add_namespace_prefix(&mut self, prefix: &str, namespace_iri: &str) -> Result<()> {
612        // Store namespace mappings for efficient rule processing
613        info!(
614            "Adding namespace prefix '{}' -> '{}'",
615            prefix, namespace_iri
616        );
617
618        // Store the prefix mapping
619        self.namespace_prefixes
620            .insert(prefix.to_string(), namespace_iri.to_string());
621
622        debug!(
623            "Namespace prefix '{}' mapped to '{}' (total prefixes: {})",
624            prefix,
625            namespace_iri,
626            self.namespace_prefixes.len()
627        );
628
629        Ok(())
630    }
631
632    /// Expand prefixed IRI to full IRI using namespace mappings
633    pub fn expand_prefixed_iri(&self, prefixed_iri: &str) -> Result<String> {
634        if let Some(colon_pos) = prefixed_iri.find(':') {
635            let prefix = &prefixed_iri[..colon_pos];
636            let local_name = &prefixed_iri[colon_pos + 1..];
637
638            // Look up the prefix in stored mappings
639            if let Some(namespace) = self.namespace_prefixes.get(prefix) {
640                let expanded = format!("{}{}", namespace, local_name);
641                debug!("Expanded '{}' to '{}'", prefixed_iri, expanded);
642                Ok(expanded)
643            } else {
644                // Return as-is if prefix not recognized
645                debug!("Unknown prefix '{}', returning prefixed IRI as-is", prefix);
646                Ok(prefixed_iri.to_string())
647            }
648        } else {
649            Ok(prefixed_iri.to_string())
650        }
651    }
652
653    /// Compress full IRI to prefixed form using namespace mappings
654    pub fn compress_to_prefixed_iri(&self, full_iri: &str) -> String {
655        // Try to find a matching namespace prefix
656        for (prefix, namespace) in &self.namespace_prefixes {
657            if full_iri.starts_with(namespace) {
658                let local_name = &full_iri[namespace.len()..];
659                let compressed = format!("{}:{}", prefix, local_name);
660                debug!("Compressed '{}' to '{}'", full_iri, compressed);
661                return compressed;
662            }
663        }
664
665        // Return as-is if no matching prefix found
666        debug!("No matching prefix for '{}', returning as-is", full_iri);
667        full_iri.to_string()
668    }
669
670    /// Get all registered namespace prefixes
671    pub fn get_namespace_prefixes(&self) -> &HashMap<String, String> {
672        &self.namespace_prefixes
673    }
674
675    /// Remove a namespace prefix
676    pub fn remove_namespace_prefix(&mut self, prefix: &str) -> Option<String> {
677        self.namespace_prefixes.remove(prefix)
678    }
679
680    /// Validate RDF data before rule processing
681    ///
682    /// Performs comprehensive validation including:
683    /// - Store size checks
684    /// - Rule engine state validation
685    /// - Basic integrity checks
686    pub fn validate_rdf_data(&self) -> Result<ValidationReport> {
687        let quad_count = self.store.len()?;
688        let mut warnings = Vec::new();
689        let mut errors = Vec::new();
690
691        // 1. Check if store is empty
692        if quad_count == 0 {
693            warnings.push("Store is empty - no data to validate".to_string());
694        } else {
695            debug!("Validating {} quads in store", quad_count);
696        }
697
698        // 2. Check rule engine state
699        let facts = self.rule_engine.get_facts();
700        if facts.is_empty() && quad_count > 0 {
701            warnings.push(
702                "Store contains data but rule engine has no facts - consider calling apply_rules()"
703                    .to_string(),
704            );
705        }
706
707        // 3. Validate that fact count is reasonable compared to quad count
708        if facts.len() > quad_count * 10 {
709            warnings.push(format!(
710                "Rule engine has {} facts but store has only {} quads - possible rule explosion",
711                facts.len(),
712                quad_count
713            ));
714        }
715
716        // 4. Check for very large datasets that might cause performance issues
717        if quad_count > 1_000_000 {
718            warnings.push(format!(
719                "Large dataset ({} quads) - consider chunked processing for better performance",
720                quad_count
721            ));
722        }
723
724        // 5. Validate IRI format in  facts (lightweight check)
725        let mut malformed_iris = 0;
726        for fact in &facts {
727            if let Some(iri) = self.extract_iri_from_fact(fact) {
728                if !self.is_valid_iri(&iri) {
729                    malformed_iris += 1;
730                    if malformed_iris <= 5 {
731                        // Only report first 5
732                        errors.push(format!("Malformed IRI in fact: {}", iri));
733                    }
734                }
735            }
736        }
737
738        if malformed_iris > 5 {
739            errors.push(format!(
740                "Found {} additional malformed IRIs (showing first 5)",
741                malformed_iris - 5
742            ));
743        }
744
745        Ok(ValidationReport {
746            total_triples: quad_count,
747            warnings,
748            errors,
749        })
750    }
751
752    /// Extract IRI from a fact for validation (helper)
753    fn extract_iri_from_fact(&self, fact: &RuleAtom) -> Option<String> {
754        match fact {
755            RuleAtom::Triple {
756                subject,
757                predicate,
758                object,
759            } => {
760                // Check subject
761                if let Term::Constant(s) = subject {
762                    if s.contains("://") {
763                        return Some(s.clone());
764                    }
765                }
766                // Check predicate
767                if let Term::Constant(p) = predicate {
768                    if p.contains("://") {
769                        return Some(p.clone());
770                    }
771                }
772                // Check object
773                if let Term::Constant(o) = object {
774                    if o.contains("://") {
775                        return Some(o.clone());
776                    }
777                }
778                None
779            }
780            _ => None,
781        }
782    }
783
784    /// Check if an IRI is well-formed
785    fn is_valid_iri(&self, iri: &str) -> bool {
786        // Basic IRI validation
787        // 1. Must not be empty
788        if iri.is_empty() {
789            return false;
790        }
791
792        // 2. Must contain a colon (scheme separator)
793        if !iri.contains(':') {
794            return false;
795        }
796
797        // 3. Common schemes should be lowercase
798        let common_schemes = ["http", "https", "urn", "file", "ftp"];
799        for scheme in &common_schemes {
800            if iri.starts_with(&format!("{}:", scheme.to_uppercase())) {
801                return false; // Scheme should be lowercase
802            }
803        }
804
805        // 4. Must not contain illegal characters
806        let illegal_chars = [' ', '<', '>', '{', '}', '|', '\\', '^', '`'];
807        if iri.chars().any(|c| illegal_chars.contains(&c)) {
808            return false;
809        }
810
811        // 5. Fragment identifier validation (if present)
812        if let Some(fragment_pos) = iri.rfind('#') {
813            let fragment = &iri[fragment_pos + 1..];
814            // Fragment should not be empty if # is present
815            if fragment.is_empty() {
816                return false;
817            }
818        }
819
820        true
821    }
822
823    /// Batch process multiple triples with optimized rule application
824    pub fn batch_process(&mut self, triples: Vec<Triple>) -> Result<BatchProcessingStats> {
825        let start_time = std::time::Instant::now();
826        let initial_fact_count = self.store.len()?;
827
828        // Insert all triples first
829        let mut inserted = 0;
830        for triple in triples {
831            // Convert triple to quad with default graph
832            let quad = Quad::new_default_graph(
833                triple.subject().clone(),
834                triple.predicate().clone(),
835                triple.object().clone(),
836            );
837            if self.store.insert_quad(quad)? {
838                inserted += 1;
839            }
840        }
841
842        // Apply rules once after all insertions
843        let derived = self.apply_rules()?;
844        let final_fact_count = self.store.len()?;
845        let duration = start_time.elapsed();
846
847        Ok(BatchProcessingStats {
848            input_triples: inserted,
849            derived_facts: derived,
850            initial_fact_count,
851            final_fact_count,
852            processing_time: duration,
853        })
854    }
855
856    /// Export reasoning results in different formats
857    pub fn export_reasoning_results(&self, format: ExportFormat) -> Result<String> {
858        match format {
859            ExportFormat::NTriples => {
860                let quads = self.store.query_quads(None, None, None, None)?;
861                let mut output = String::new();
862                for quad in quads {
863                    let triple = quad.to_triple();
864                    output.push_str(&format!(
865                        "<{}> <{}> {} .\n",
866                        triple.subject(),
867                        triple.predicate(),
868                        self.format_object_for_ntriples(triple.object())
869                    ));
870                }
871                Ok(output)
872            }
873            ExportFormat::Json => {
874                let stats = self.get_integration_stats()?;
875                Ok(serde_json::to_string_pretty(&stats)?)
876            }
877        }
878    }
879
880    /// Advanced reasoning analysis
881    pub fn analyze_reasoning_coverage(&mut self) -> Result<ReasoningAnalysis> {
882        let initial_facts = self.store.len()?;
883        let derived = self.apply_rules()?;
884        let final_facts = self.store.len()?;
885
886        let coverage_ratio = if initial_facts > 0 {
887            derived as f64 / initial_facts as f64
888        } else {
889            0.0
890        };
891
892        Ok(ReasoningAnalysis {
893            initial_fact_count: initial_facts,
894            derived_fact_count: derived,
895            final_fact_count: final_facts,
896            reasoning_coverage_ratio: coverage_ratio,
897            active_rules: self.rule_engine.rules.len(),
898        })
899    }
900
901    /// Find reasoning bottlenecks and optimization opportunities
902    pub fn performance_analysis(&mut self) -> Result<PerformanceAnalysis> {
903        let start_time = std::time::Instant::now();
904
905        // Measure rule loading time
906        let rule_load_start = std::time::Instant::now();
907        self.load_facts_from_store()?;
908        let rule_load_time = rule_load_start.elapsed();
909
910        // Measure reasoning time
911        let reasoning_start = std::time::Instant::now();
912        let derived = self.apply_rules()?;
913        let reasoning_time = reasoning_start.elapsed();
914
915        let total_time = start_time.elapsed();
916
917        Ok(PerformanceAnalysis {
918            rule_loading_time: rule_load_time,
919            reasoning_time,
920            total_time,
921            facts_per_second: if reasoning_time.as_secs() > 0 {
922                derived as f64 / reasoning_time.as_secs_f64()
923            } else {
924                0.0
925            },
926        })
927    }
928
929    /// Helper method to format objects for N-Triples export
930    fn format_object_for_ntriples(&self, object: &Object) -> String {
931        match object {
932            Object::NamedNode(node) => format!("<{}>", node.as_str()),
933            Object::BlankNode(node) => format!("_:{}", node.as_str()),
934            Object::Literal(literal) => {
935                if let Some(lang) = literal.language() {
936                    format!("\"{}\"@{}", literal.value(), lang)
937                } else {
938                    let datatype = literal.datatype();
939                    if datatype.as_str() == "http://www.w3.org/2001/XMLSchema#string" {
940                        format!("\"{}\"", literal.value())
941                    } else {
942                        format!("\"{}\"^^<{}>", literal.value(), datatype.as_str())
943                    }
944                }
945            }
946            Object::Variable(var) => format!("?{}", var.as_str()),
947            Object::QuotedTriple(_) => {
948                // For N-Triples export, represent quoted triples as blank nodes
949                "_:quoted_triple".to_string()
950            }
951        }
952    }
953}
954
955/// Statistics about the rule-store integration
956#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
957pub struct IntegrationStats {
958    /// Number of quads in the store
959    pub store_quad_count: usize,
960    /// Number of facts in the rule engine
961    pub rule_fact_count: usize,
962    /// Number of rules in the engine
963    pub rule_count: usize,
964}
965
966/// Statistics for streaming data processing
967#[derive(Debug, Clone)]
968pub struct StreamingStats {
969    pub processed_triples: usize,
970    pub derived_facts: usize,
971    pub errors: usize,
972}
973
974/// Statistics for batch processing
975#[derive(Debug, Clone)]
976pub struct BatchProcessingStats {
977    pub input_triples: usize,
978    pub derived_facts: usize,
979    pub initial_fact_count: usize,
980    pub final_fact_count: usize,
981    pub processing_time: std::time::Duration,
982}
983
984/// Statistics for named graph processing
985#[derive(Debug, Clone)]
986pub struct ProcessingStats {
987    pub processed_count: usize,
988    pub derived_count: usize,
989    pub processing_time: std::time::Duration,
990}
991
992/// Statistics for bulk processing with transactions
993#[derive(Debug, Clone)]
994pub struct BulkProcessingStats {
995    pub total_processed: usize,
996    pub total_derived: usize,
997    pub batch_count: usize,
998    pub processing_time: std::time::Duration,
999}
1000
1001/// Statistics for error recovery processing
1002#[derive(Debug, Clone)]
1003pub struct ErrorRecoveryStats {
1004    pub successful_triples: usize,
1005    pub failed_triples: usize,
1006    pub derived_facts: usize,
1007    pub error_details: Vec<String>,
1008}
1009
1010/// Analysis of reasoning coverage and effectiveness
1011#[derive(Debug, Clone)]
1012pub struct ReasoningAnalysis {
1013    pub initial_fact_count: usize,
1014    pub derived_fact_count: usize,
1015    pub final_fact_count: usize,
1016    pub reasoning_coverage_ratio: f64,
1017    pub active_rules: usize,
1018}
1019
1020/// Performance analysis results
1021#[derive(Debug, Clone)]
1022pub struct PerformanceAnalysis {
1023    pub rule_loading_time: std::time::Duration,
1024    pub reasoning_time: std::time::Duration,
1025    pub total_time: std::time::Duration,
1026    pub facts_per_second: f64,
1027}
1028
1029/// Export format options
1030#[derive(Debug, Clone)]
1031pub enum ExportFormat {
1032    NTriples,
1033    Json,
1034}
1035
1036/// RDF data validation report
1037#[derive(Debug, Clone)]
1038pub struct ValidationReport {
1039    pub total_triples: usize,
1040    pub warnings: Vec<String>,
1041    pub errors: Vec<String>,
1042}
1043
1044impl std::fmt::Display for IntegrationStats {
1045    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1046        write!(
1047            f,
1048            "Store: {} quads, Rules: {} facts/{} rules",
1049            self.store_quad_count, self.rule_fact_count, self.rule_count
1050        )
1051    }
1052}
1053
1054impl std::fmt::Display for StreamingStats {
1055    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1056        write!(
1057            f,
1058            "Processed: {} triples, Derived: {} facts, Errors: {}",
1059            self.processed_triples, self.derived_facts, self.errors
1060        )
1061    }
1062}
1063
1064impl std::fmt::Display for BatchProcessingStats {
1065    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1066        write!(
1067            f,
1068            "Batch: {} input -> {} derived in {:?} ({} -> {} total facts)",
1069            self.input_triples,
1070            self.derived_facts,
1071            self.processing_time,
1072            self.initial_fact_count,
1073            self.final_fact_count
1074        )
1075    }
1076}
1077
1078impl std::fmt::Display for ReasoningAnalysis {
1079    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1080        write!(
1081            f,
1082            "Coverage: {:.2}% ({}/{} facts, {} rules)",
1083            self.reasoning_coverage_ratio * 100.0,
1084            self.derived_fact_count,
1085            self.initial_fact_count,
1086            self.active_rules
1087        )
1088    }
1089}
1090
1091impl std::fmt::Display for PerformanceAnalysis {
1092    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1093        write!(
1094            f,
1095            "Performance: {:.2} facts/sec (load: {:?}, reason: {:?}, total: {:?})",
1096            self.facts_per_second, self.rule_loading_time, self.reasoning_time, self.total_time
1097        )
1098    }
1099}
1100
1101impl std::fmt::Display for ValidationReport {
1102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1103        write!(
1104            f,
1105            "Validation: {} triples, {} warnings, {} errors",
1106            self.total_triples,
1107            self.warnings.len(),
1108            self.errors.len()
1109        )
1110    }
1111}
1112
1113/// Convenience functions for creating common rules from RDF patterns
1114pub mod rule_builders {
1115    use super::*;
1116
1117    /// Create an RDFS subClassOf transitivity rule
1118    pub fn rdfs_subclass_transitivity() -> Rule {
1119        Rule {
1120            name: "rdfs_subclass_transitivity".to_string(),
1121            body: vec![
1122                RuleAtom::Triple {
1123                    subject: Term::Variable("X".to_string()),
1124                    predicate: Term::Constant(
1125                        "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
1126                    ),
1127                    object: Term::Variable("Y".to_string()),
1128                },
1129                RuleAtom::Triple {
1130                    subject: Term::Variable("Y".to_string()),
1131                    predicate: Term::Constant(
1132                        "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
1133                    ),
1134                    object: Term::Variable("Z".to_string()),
1135                },
1136            ],
1137            head: vec![RuleAtom::Triple {
1138                subject: Term::Variable("X".to_string()),
1139                predicate: Term::Constant(
1140                    "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
1141                ),
1142                object: Term::Variable("Z".to_string()),
1143            }],
1144        }
1145    }
1146
1147    /// Create an RDFS type inheritance rule
1148    pub fn rdfs_type_inheritance() -> Rule {
1149        Rule {
1150            name: "rdfs_type_inheritance".to_string(),
1151            body: vec![
1152                RuleAtom::Triple {
1153                    subject: Term::Variable("X".to_string()),
1154                    predicate: Term::Constant(
1155                        "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1156                    ),
1157                    object: Term::Variable("C1".to_string()),
1158                },
1159                RuleAtom::Triple {
1160                    subject: Term::Variable("C1".to_string()),
1161                    predicate: Term::Constant(
1162                        "http://www.w3.org/2000/01/rdf-schema#subClassOf".to_string(),
1163                    ),
1164                    object: Term::Variable("C2".to_string()),
1165                },
1166            ],
1167            head: vec![RuleAtom::Triple {
1168                subject: Term::Variable("X".to_string()),
1169                predicate: Term::Constant(
1170                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1171                ),
1172                object: Term::Variable("C2".to_string()),
1173            }],
1174        }
1175    }
1176
1177    /// Create a domain inference rule
1178    pub fn rdfs_domain_inference() -> Rule {
1179        Rule {
1180            name: "rdfs_domain_inference".to_string(),
1181            body: vec![
1182                RuleAtom::Triple {
1183                    subject: Term::Variable("P".to_string()),
1184                    predicate: Term::Constant(
1185                        "http://www.w3.org/2000/01/rdf-schema#domain".to_string(),
1186                    ),
1187                    object: Term::Variable("C".to_string()),
1188                },
1189                RuleAtom::Triple {
1190                    subject: Term::Variable("X".to_string()),
1191                    predicate: Term::Variable("P".to_string()),
1192                    object: Term::Variable("Y".to_string()),
1193                },
1194            ],
1195            head: vec![RuleAtom::Triple {
1196                subject: Term::Variable("X".to_string()),
1197                predicate: Term::Constant(
1198                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1199                ),
1200                object: Term::Variable("C".to_string()),
1201            }],
1202        }
1203    }
1204
1205    /// Create a range inference rule
1206    pub fn rdfs_range_inference() -> Rule {
1207        Rule {
1208            name: "rdfs_range_inference".to_string(),
1209            body: vec![
1210                RuleAtom::Triple {
1211                    subject: Term::Variable("P".to_string()),
1212                    predicate: Term::Constant(
1213                        "http://www.w3.org/2000/01/rdf-schema#range".to_string(),
1214                    ),
1215                    object: Term::Variable("C".to_string()),
1216                },
1217                RuleAtom::Triple {
1218                    subject: Term::Variable("X".to_string()),
1219                    predicate: Term::Variable("P".to_string()),
1220                    object: Term::Variable("Y".to_string()),
1221                },
1222            ],
1223            head: vec![RuleAtom::Triple {
1224                subject: Term::Variable("Y".to_string()),
1225                predicate: Term::Constant(
1226                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1227                ),
1228                object: Term::Variable("C".to_string()),
1229            }],
1230        }
1231    }
1232
1233    /// Create all standard RDFS rules
1234    pub fn all_rdfs_rules() -> Vec<Rule> {
1235        vec![
1236            rdfs_subclass_transitivity(),
1237            rdfs_type_inheritance(),
1238            rdfs_domain_inference(),
1239            rdfs_range_inference(),
1240        ]
1241    }
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246    use super::*;
1247    use oxirs_core::{Literal, NamedNode, Triple};
1248
1249    #[test]
1250    fn test_integration_basic_workflow() -> Result<(), Box<dyn std::error::Error>> {
1251        let mut integration = RuleIntegration::new();
1252
1253        // Add some test data to the store
1254        let subject = NamedNode::new("http://example.org/person")?;
1255        let predicate = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")?;
1256        let object = NamedNode::new("http://example.org/Human")?;
1257
1258        let triple = Triple::new(
1259            subject.clone(),
1260            predicate.clone(),
1261            Object::NamedNode(object),
1262        );
1263
1264        let quad = Quad::new_default_graph(
1265            triple.subject().clone(),
1266            triple.predicate().clone(),
1267            triple.object().clone(),
1268        );
1269        integration.store.insert_quad(quad)?;
1270
1271        // Add a rule: Human -> Mortal
1272        let rule = Rule {
1273            name: "human_mortal".to_string(),
1274            body: vec![RuleAtom::Triple {
1275                subject: Term::Variable("X".to_string()),
1276                predicate: Term::Constant(
1277                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1278                ),
1279                object: Term::Constant("http://example.org/Human".to_string()),
1280            }],
1281            head: vec![RuleAtom::Triple {
1282                subject: Term::Variable("X".to_string()),
1283                predicate: Term::Constant(
1284                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".to_string(),
1285                ),
1286                object: Term::Constant("http://example.org/Mortal".to_string()),
1287            }],
1288        };
1289
1290        integration.add_rule(rule);
1291
1292        // Apply rules
1293        let derived_count = integration.apply_rules()?;
1294        assert!(derived_count > 0);
1295
1296        // Check that the mortal type was derived
1297        let mortal_type = NamedNode::new("http://example.org/Mortal")?;
1298        let all_triples = integration.store.triples()?;
1299        let results: Vec<_> = all_triples
1300            .iter()
1301            .filter(|triple| {
1302                triple.subject() == &Subject::NamedNode(subject.clone())
1303                    && triple.predicate() == &Predicate::NamedNode(predicate.clone())
1304                    && triple.object() == &Object::NamedNode(mortal_type.clone())
1305            })
1306            .collect();
1307
1308        assert!(!results.is_empty());
1309        Ok(())
1310    }
1311
1312    #[test]
1313    fn test_conversion_functions() -> Result<(), Box<dyn std::error::Error>> {
1314        let integration = RuleIntegration::new();
1315
1316        // Test triple to rule atom conversion
1317        let subject = NamedNode::new("http://example.org/subject")?;
1318        let predicate = NamedNode::new("http://example.org/predicate")?;
1319        let object = Literal::new("test");
1320
1321        let triple = Triple::new(subject, predicate, object);
1322        let rule_atom = integration.triple_to_rule_atom(&triple);
1323
1324        match &rule_atom {
1325            RuleAtom::Triple {
1326                subject: s,
1327                predicate: p,
1328                object: o,
1329            } => {
1330                assert!(matches!(s, Term::Constant(_)));
1331                assert!(matches!(p, Term::Constant(_)));
1332                assert!(matches!(o, Term::Literal(_)));
1333            }
1334            _ => panic!("Expected triple rule atom"),
1335        }
1336
1337        // Test rule atom to triple conversion
1338        let converted_triple = integration.rule_atom_to_triple(&rule_atom)?;
1339        // Check subject and predicate types
1340        match converted_triple.subject() {
1341            Subject::NamedNode(node) => assert_eq!(node.as_str(), "http://example.org/subject"),
1342            _ => panic!("Expected NamedNode subject"),
1343        }
1344        match converted_triple.predicate() {
1345            Predicate::NamedNode(node) => assert_eq!(node.as_str(), "http://example.org/predicate"),
1346            _ => panic!("Expected NamedNode predicate"),
1347        }
1348        Ok(())
1349    }
1350
1351    #[test]
1352    fn test_rule_builders() {
1353        let rules = rule_builders::all_rdfs_rules();
1354        assert_eq!(rules.len(), 4);
1355
1356        // Check that all rules have proper names
1357        let rule_names: Vec<String> = rules.iter().map(|r| r.name.clone()).collect();
1358        assert!(rule_names.contains(&"rdfs_subclass_transitivity".to_string()));
1359        assert!(rule_names.contains(&"rdfs_type_inheritance".to_string()));
1360        assert!(rule_names.contains(&"rdfs_domain_inference".to_string()));
1361        assert!(rule_names.contains(&"rdfs_range_inference".to_string()));
1362    }
1363
1364    #[test]
1365    fn test_query_with_rules() -> Result<(), Box<dyn std::error::Error>> {
1366        let mut integration = RuleIntegration::new();
1367
1368        // Add RDFS rules
1369        integration.add_rules(rule_builders::all_rdfs_rules());
1370
1371        // Add some test ontology data
1372        let person = NamedNode::new("http://example.org/Person")?;
1373        let student = NamedNode::new("http://example.org/Student")?;
1374        let subclass_pred = NamedNode::new("http://www.w3.org/2000/01/rdf-schema#subClassOf")?;
1375        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")?;
1376        let alice = NamedNode::new("http://example.org/alice")?;
1377
1378        // Student subClassOf Person
1379        let subclass_triple = Triple::new(
1380            Subject::NamedNode(student.clone()),
1381            Predicate::NamedNode(subclass_pred),
1382            Object::NamedNode(person.clone()),
1383        );
1384
1385        // alice type Student
1386        let alice_type_triple = Triple::new(
1387            Subject::NamedNode(alice.clone()),
1388            Predicate::NamedNode(type_pred.clone()),
1389            Object::NamedNode(student),
1390        );
1391
1392        let subclass_quad = Quad::new_default_graph(
1393            subclass_triple.subject().clone(),
1394            subclass_triple.predicate().clone(),
1395            subclass_triple.object().clone(),
1396        );
1397        let alice_type_quad = Quad::new_default_graph(
1398            alice_type_triple.subject().clone(),
1399            alice_type_triple.predicate().clone(),
1400            alice_type_triple.object().clone(),
1401        );
1402        integration.store.insert_quad(subclass_quad)?;
1403        integration.store.insert_quad(alice_type_quad)?;
1404
1405        // Query for all types of alice (should include both Student and Person via inference)
1406        let results = integration.query_with_rules(
1407            Some(&Subject::NamedNode(alice)),
1408            Some(&Predicate::NamedNode(type_pred)),
1409            None,
1410        )?;
1411
1412        // Should find at least 2 results (Student and Person)
1413        assert!(results.len() >= 2);
1414
1415        let has_person_type = results.iter().any(|triple| {
1416            if let Object::NamedNode(node) = triple.object() {
1417                node.as_str() == "http://example.org/Person"
1418            } else {
1419                false
1420            }
1421        });
1422
1423        assert!(has_person_type, "Should infer that alice is a Person");
1424        Ok(())
1425    }
1426
1427    #[test]
1428    fn test_statistics() -> Result<(), Box<dyn std::error::Error>> {
1429        let mut integration = RuleIntegration::new();
1430
1431        // Add some data
1432        let triple = Triple::new(
1433            NamedNode::new("http://example.org/s")?,
1434            NamedNode::new("http://example.org/p")?,
1435            Literal::new("o"),
1436        );
1437        let quad = Quad::new_default_graph(
1438            triple.subject().clone(),
1439            triple.predicate().clone(),
1440            triple.object().clone(),
1441        );
1442        integration.store.insert_quad(quad)?;
1443
1444        // Add a rule
1445        integration.add_rule(rule_builders::rdfs_type_inheritance());
1446
1447        let stats = integration.get_integration_stats()?;
1448        assert_eq!(stats.store_quad_count, 1);
1449        assert_eq!(stats.rule_count, 1);
1450        Ok(())
1451    }
1452
1453    #[test]
1454    fn test_namespace_management() -> Result<(), Box<dyn std::error::Error>> {
1455        let mut integration = RuleIntegration::new();
1456
1457        // Test namespace prefix addition
1458        integration.add_namespace_prefix("ex", "http://example.org/")?;
1459
1460        // Test IRI expansion
1461        let expanded = integration.expand_prefixed_iri("rdf:type")?;
1462        assert_eq!(expanded, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1463
1464        let expanded = integration.expand_prefixed_iri("rdfs:Class")?;
1465        assert_eq!(expanded, "http://www.w3.org/2000/01/rdf-schema#Class");
1466
1467        let expanded = integration.expand_prefixed_iri("owl:Class")?;
1468        assert_eq!(expanded, "http://www.w3.org/2002/07/owl#Class");
1469
1470        let expanded = integration.expand_prefixed_iri("ex:Person")?;
1471        assert_eq!(expanded, "http://example.org/Person");
1472
1473        // Test non-prefixed IRI
1474        let unchanged = integration.expand_prefixed_iri("http://example.org/full")?;
1475        assert_eq!(unchanged, "http://example.org/full");
1476
1477        // Test IRI compression
1478        let compressed =
1479            integration.compress_to_prefixed_iri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1480        assert_eq!(compressed, "rdf:type");
1481
1482        let compressed =
1483            integration.compress_to_prefixed_iri("http://www.w3.org/2000/01/rdf-schema#Class");
1484        assert_eq!(compressed, "rdfs:Class");
1485
1486        let compressed = integration.compress_to_prefixed_iri("http://example.org/Person");
1487        assert_eq!(compressed, "ex:Person");
1488
1489        // Test non-matching IRI (should return as-is)
1490        let unchanged = integration.compress_to_prefixed_iri("http://unknown.org/resource");
1491        assert_eq!(unchanged, "http://unknown.org/resource");
1492
1493        // Test get all prefixes
1494        let prefixes = integration.get_namespace_prefixes();
1495        assert!(prefixes.contains_key("rdf"));
1496        assert!(prefixes.contains_key("rdfs"));
1497        assert!(prefixes.contains_key("owl"));
1498        assert!(prefixes.contains_key("xsd"));
1499        assert!(prefixes.contains_key("ex"));
1500        assert_eq!(prefixes.len(), 5);
1501
1502        // Test remove prefix
1503        let removed = integration.remove_namespace_prefix("ex");
1504        assert_eq!(removed, Some("http://example.org/".to_string()));
1505        assert_eq!(integration.get_namespace_prefixes().len(), 4);
1506
1507        // Try to remove non-existent prefix
1508        let not_found = integration.remove_namespace_prefix("nonexistent");
1509        assert_eq!(not_found, None);
1510        Ok(())
1511    }
1512
1513    #[test]
1514    fn test_data_validation() -> Result<(), Box<dyn std::error::Error>> {
1515        let integration = RuleIntegration::new();
1516
1517        // Test validation on empty store
1518        let report = integration.validate_rdf_data()?;
1519        assert_eq!(report.total_triples, 0);
1520        assert!(!report.warnings.is_empty()); // Should warn about empty store
1521        assert!(report.errors.is_empty());
1522
1523        println!("Validation report: {report}");
1524        Ok(())
1525    }
1526}