rust_rule_engine/engine/
engine.rs

1use crate::engine::{
2    agenda::{ActivationGroupManager, AgendaManager},
3    analytics::RuleAnalytics,
4    facts::Facts,
5    knowledge_base::KnowledgeBase,
6    plugin::{PluginConfig, PluginHealth, PluginInfo, PluginManager, PluginStats, RulePlugin},
7    workflow::WorkflowEngine,
8};
9use crate::errors::{Result, RuleEngineError};
10use crate::types::{ActionType, Value};
11use chrono::{DateTime, Utc};
12use std::collections::HashMap;
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15
16/// Type for custom function implementations
17pub type CustomFunction = Box<dyn Fn(&[Value], &Facts) -> Result<Value> + Send + Sync>;
18
19/// Type for custom action handlers
20pub type ActionHandler = Box<dyn Fn(&HashMap<String, Value>, &Facts) -> Result<()> + Send + Sync>;
21
22/// Configuration options for the rule engine
23#[derive(Debug, Clone)]
24pub struct EngineConfig {
25    /// Maximum number of execution cycles
26    pub max_cycles: usize,
27    /// Execution timeout
28    pub timeout: Option<Duration>,
29    /// Enable performance statistics collection
30    pub enable_stats: bool,
31    /// Enable debug mode with verbose logging
32    pub debug_mode: bool,
33}
34
35impl Default for EngineConfig {
36    fn default() -> Self {
37        Self {
38            max_cycles: 100,
39            timeout: Some(Duration::from_secs(30)),
40            enable_stats: true,
41            debug_mode: false,
42        }
43    }
44}
45
46/// Result of rule engine execution
47#[derive(Debug, Clone)]
48pub struct GruleExecutionResult {
49    /// Number of execution cycles
50    pub cycle_count: usize,
51    /// Number of rules evaluated
52    pub rules_evaluated: usize,
53    /// Number of rules that fired
54    pub rules_fired: usize,
55    /// Total execution time
56    pub execution_time: Duration,
57}
58
59/// Rust Rule Engine - High-performance rule execution engine
60pub struct RustRuleEngine {
61    knowledge_base: KnowledgeBase,
62    config: EngineConfig,
63    custom_functions: HashMap<String, CustomFunction>,
64    action_handlers: HashMap<String, ActionHandler>,
65    analytics: Option<RuleAnalytics>,
66    agenda_manager: AgendaManager,
67    activation_group_manager: ActivationGroupManager,
68    /// Track rules that have fired globally (for no-loop support)
69    fired_rules_global: std::collections::HashSet<String>,
70    /// Workflow engine for rule chaining and sequential execution
71    workflow_engine: WorkflowEngine,
72    /// Plugin manager for extensible functionality
73    plugin_manager: PluginManager,
74}
75
76impl RustRuleEngine {
77    /// Execute all rules and call callback when a rule is fired
78    pub fn execute_with_callback<F>(&mut self, facts: &Facts, mut on_rule_fired: F) -> Result<GruleExecutionResult>
79    where
80        F: FnMut(&str, &str),
81    {
82        use chrono::Utc;
83        let timestamp = Utc::now();
84        let start_time = std::time::Instant::now();
85        let mut cycle_count = 0;
86        let mut rules_evaluated = 0;
87        let mut rules_fired = 0;
88
89        self.sync_workflow_agenda_activations();
90
91        for cycle in 0..self.config.max_cycles {
92            cycle_count = cycle + 1;
93            let mut any_rule_fired = false;
94            let mut fired_rules_in_cycle = std::collections::HashSet::new();
95            self.activation_group_manager.reset_cycle();
96
97            if let Some(timeout) = self.config.timeout {
98                if start_time.elapsed() > timeout {
99                    return Err(crate::errors::RuleEngineError::EvaluationError {
100                        message: "Execution timeout exceeded".to_string(),
101                    });
102                }
103            }
104
105            let mut rules = self.knowledge_base.get_rules().clone();
106            rules.sort_by(|a, b| b.salience.cmp(&a.salience));
107            let rules: Vec<_> = rules
108                .iter()
109                .filter(|rule| self.agenda_manager.should_evaluate_rule(rule))
110                .collect();
111
112            for rule in &rules {
113                if !rule.enabled {
114                    continue;
115                }
116                if !rule.is_active_at(timestamp) {
117                    continue;
118                }
119                if !self.agenda_manager.can_fire_rule(rule) {
120                    continue;
121                }
122                if !self.activation_group_manager.can_fire(rule) {
123                    continue;
124                }
125                if rule.no_loop && self.fired_rules_global.contains(&rule.name) {
126                    continue;
127                }
128                rules_evaluated += 1;
129                let condition_result = self.evaluate_conditions(&rule.conditions, facts)?;
130                if condition_result {
131                    for action in &rule.actions {
132                        self.execute_action(action, facts)?;
133                    }
134                    rules_fired += 1;
135                    any_rule_fired = true;
136                    fired_rules_in_cycle.insert(rule.name.clone());
137                    if rule.no_loop {
138                        self.fired_rules_global.insert(rule.name.clone());
139                    }
140                    self.agenda_manager.mark_rule_fired(rule);
141                    self.activation_group_manager.mark_fired(rule);
142                    // Gọi callback khi rule fired
143                    on_rule_fired(&rule.name, "facts"); // TODO: truyền id facts thực tế nếu có
144                }
145            }
146            if !any_rule_fired {
147                break;
148            }
149            self.sync_workflow_agenda_activations();
150        }
151        let execution_time = start_time.elapsed();
152        Ok(crate::engine::GruleExecutionResult {
153            cycle_count,
154            rules_evaluated,
155            rules_fired,
156            execution_time,
157        })
158    }
159    /// Create a new RustRuleEngine with default configuration
160    pub fn new(knowledge_base: KnowledgeBase) -> Self {
161        Self {
162            knowledge_base,
163            config: EngineConfig::default(),
164            custom_functions: HashMap::new(),
165            action_handlers: HashMap::new(),
166            analytics: None,
167            agenda_manager: AgendaManager::new(),
168            activation_group_manager: ActivationGroupManager::new(),
169            fired_rules_global: std::collections::HashSet::new(),
170            workflow_engine: WorkflowEngine::new(),
171            plugin_manager: PluginManager::with_default_config(),
172        }
173    }
174
175    /// Create a new RustRuleEngine with custom configuration
176    pub fn with_config(knowledge_base: KnowledgeBase, config: EngineConfig) -> Self {
177        Self {
178            knowledge_base,
179            config,
180            custom_functions: HashMap::new(),
181            action_handlers: HashMap::new(),
182            analytics: None,
183            agenda_manager: AgendaManager::new(),
184            activation_group_manager: ActivationGroupManager::new(),
185            fired_rules_global: std::collections::HashSet::new(),
186            workflow_engine: WorkflowEngine::new(),
187            plugin_manager: PluginManager::with_default_config(),
188        }
189    }
190
191    /// Register a custom function
192    pub fn register_function<F>(&mut self, name: &str, func: F)
193    where
194        F: Fn(&[Value], &Facts) -> Result<Value> + Send + Sync + 'static,
195    {
196        self.custom_functions
197            .insert(name.to_string(), Box::new(func));
198    }
199
200    /// Register a custom action handler
201    pub fn register_action_handler<F>(&mut self, action_type: &str, handler: F)
202    where
203        F: Fn(&HashMap<String, Value>, &Facts) -> Result<()> + Send + Sync + 'static,
204    {
205        self.action_handlers
206            .insert(action_type.to_string(), Box::new(handler));
207    }
208
209    /// Enable analytics with custom configuration
210    pub fn enable_analytics(&mut self, analytics: RuleAnalytics) {
211        self.analytics = Some(analytics);
212    }
213
214    /// Reset global no-loop tracking (useful for testing or when facts change significantly)
215    pub fn reset_no_loop_tracking(&mut self) {
216        self.fired_rules_global.clear();
217    }
218
219    /// Disable analytics
220    pub fn disable_analytics(&mut self) {
221        self.analytics = None;
222    }
223
224    /// Get reference to analytics data
225    pub fn analytics(&self) -> Option<&RuleAnalytics> {
226        self.analytics.as_ref()
227    }
228
229    /// Enable debug mode for detailed execution logging
230    pub fn set_debug_mode(&mut self, enabled: bool) {
231        self.config.debug_mode = enabled;
232    }
233
234    /// Check if a custom function is registered
235    pub fn has_function(&self, name: &str) -> bool {
236        self.custom_functions.contains_key(name)
237    }
238
239    /// Check if a custom action handler is registered
240    pub fn has_action_handler(&self, action_type: &str) -> bool {
241        self.action_handlers.contains_key(action_type)
242    }
243
244    /// Get ready scheduled tasks
245    pub fn get_ready_tasks(&mut self) -> Vec<crate::engine::workflow::ScheduledTask> {
246        self.workflow_engine.get_ready_tasks()
247    }
248
249    /// Execute scheduled tasks that are ready
250    pub fn execute_scheduled_tasks(&mut self, facts: &Facts) -> Result<()> {
251        let ready_tasks = self.get_ready_tasks();
252        for task in ready_tasks {
253            if let Some(rule) = self
254                .knowledge_base
255                .get_rules()
256                .iter()
257                .find(|r| r.name == task.rule_name)
258            {
259                if self.config.debug_mode {
260                    println!("⚡ Executing scheduled task: {}", task.rule_name);
261                }
262
263                // Execute just this one rule if conditions match
264                if self.evaluate_conditions(&rule.conditions, facts)? {
265                    for action in &rule.actions {
266                        self.execute_action(action, facts)?;
267                    }
268                }
269            }
270        }
271        Ok(())
272    }
273
274    /// Activate agenda group
275    pub fn activate_agenda_group(&mut self, group: String) {
276        self.workflow_engine.activate_agenda_group(group.clone());
277        self.agenda_manager.set_focus(&group);
278    }
279
280    /// Get the knowledge base
281    pub fn knowledge_base(&self) -> &KnowledgeBase {
282        &self.knowledge_base
283    }
284
285    /// Get mutable reference to knowledge base
286    pub fn knowledge_base_mut(&mut self) -> &mut KnowledgeBase {
287        &mut self.knowledge_base
288    }
289
290    /// Sync workflow engine agenda activations with agenda manager
291    fn sync_workflow_agenda_activations(&mut self) {
292        // Process any pending agenda activations from workflow engine
293        while let Some(agenda_group) = self.workflow_engine.get_next_pending_agenda_activation() {
294            if self.config.debug_mode {
295                println!("🔄 Syncing workflow agenda activation: {}", agenda_group);
296            }
297            self.agenda_manager.set_focus(&agenda_group);
298        }
299    }
300
301    /// Set focus to a specific agenda group
302    pub fn set_agenda_focus(&mut self, group: &str) {
303        self.agenda_manager.set_focus(group);
304    }
305
306    /// Get the currently active agenda group
307    pub fn get_active_agenda_group(&self) -> &str {
308        self.agenda_manager.get_active_group()
309    }
310
311    /// Pop the agenda focus stack
312    pub fn pop_agenda_focus(&mut self) -> Option<String> {
313        self.agenda_manager.pop_focus()
314    }
315
316    /// Clear all agenda focus and return to MAIN
317    pub fn clear_agenda_focus(&mut self) {
318        self.agenda_manager.clear_focus();
319    }
320
321    /// Get all agenda groups that have rules
322    pub fn get_agenda_groups(&self) -> Vec<String> {
323        self.agenda_manager
324            .get_agenda_groups(&self.knowledge_base.get_rules())
325    }
326
327    /// Get all activation groups that have rules
328    pub fn get_activation_groups(&self) -> Vec<String> {
329        self.activation_group_manager
330            .get_activation_groups(&self.knowledge_base.get_rules())
331    }
332
333    // 🔄 Workflow Engine Methods
334
335    /// Start a new workflow
336    pub fn start_workflow(&mut self, workflow_name: Option<String>) -> String {
337        self.workflow_engine.start_workflow(workflow_name)
338    }
339
340    /// Get workflow statistics
341    pub fn get_workflow_stats(&self) -> crate::engine::workflow::WorkflowStats {
342        self.workflow_engine.get_workflow_stats()
343    }
344
345    /// Get workflow state by ID
346    pub fn get_workflow(
347        &self,
348        workflow_id: &str,
349    ) -> Option<&crate::engine::workflow::WorkflowState> {
350        self.workflow_engine.get_workflow(workflow_id)
351    }
352
353    /// Clean up completed workflows
354    pub fn cleanup_completed_workflows(&mut self, older_than: Duration) {
355        self.workflow_engine.cleanup_completed_workflows(older_than);
356    }
357
358    /// Execute workflow step by activating specific agenda group
359    pub fn execute_workflow_step(
360        &mut self,
361        agenda_group: &str,
362        facts: &Facts,
363    ) -> Result<GruleExecutionResult> {
364        // Set agenda focus to the specific group
365        self.set_agenda_focus(agenda_group);
366
367        // Execute rules in that group
368        let result = self.execute(facts)?;
369
370        // Process any workflow actions that were triggered
371        self.process_workflow_actions(facts)?;
372
373        Ok(result)
374    }
375
376    /// Execute a complete workflow by processing agenda groups sequentially
377    pub fn execute_workflow(
378        &mut self,
379        agenda_groups: Vec<&str>,
380        facts: &Facts,
381    ) -> Result<crate::engine::workflow::WorkflowResult> {
382        let start_time = Instant::now();
383        let mut total_steps = 0;
384
385        if self.config.debug_mode {
386            println!(
387                "🔄 Starting workflow execution with {} steps",
388                agenda_groups.len()
389            );
390        }
391
392        for (i, group) in agenda_groups.iter().enumerate() {
393            if self.config.debug_mode {
394                println!("📋 Executing workflow step {}: {}", i + 1, group);
395            }
396
397            let step_result = self.execute_workflow_step(group, facts)?;
398            total_steps += 1;
399
400            if step_result.rules_fired == 0 {
401                if self.config.debug_mode {
402                    println!("⏸️ No rules fired in step '{}', stopping workflow", group);
403                }
404                break;
405            }
406        }
407
408        let execution_time = start_time.elapsed();
409
410        Ok(crate::engine::workflow::WorkflowResult::success(
411            total_steps,
412            execution_time,
413        ))
414    }
415
416    /// Process workflow-related actions and scheduled tasks
417    fn process_workflow_actions(&mut self, facts: &Facts) -> Result<()> {
418        // Process agenda group activations
419        while let Some(group) = self.workflow_engine.get_next_agenda_group() {
420            self.set_agenda_focus(&group);
421        }
422
423        // Process scheduled tasks
424        let ready_tasks = self.workflow_engine.get_ready_tasks();
425        for task in ready_tasks {
426            if self.config.debug_mode {
427                println!("⚡ Executing scheduled task: {}", task.rule_name);
428            }
429
430            // Find and execute the specific rule
431            if let Some(rule) = self
432                .knowledge_base
433                .get_rules()
434                .iter()
435                .find(|r| r.name == task.rule_name)
436            {
437                // Execute just this one rule
438                if self.evaluate_conditions(&rule.conditions, facts)? {
439                    for action in &rule.actions {
440                        self.execute_action(action, facts)?;
441                    }
442                }
443            }
444        }
445
446        Ok(())
447    }
448
449    /// Execute all rules in the knowledge base against the given facts
450    pub fn execute(&mut self, facts: &Facts) -> Result<GruleExecutionResult> {
451        self.execute_at_time(facts, Utc::now())
452    }
453
454    /// Execute all rules at a specific timestamp (for date-effective/expires testing)
455    pub fn execute_at_time(
456        &mut self,
457        facts: &Facts,
458        timestamp: DateTime<Utc>,
459    ) -> Result<GruleExecutionResult> {
460        let start_time = Instant::now();
461        let mut cycle_count = 0;
462        let mut rules_evaluated = 0;
463        let mut rules_fired = 0;
464
465        // Process any pending agenda group activations from workflow engine
466        self.sync_workflow_agenda_activations();
467
468        if self.config.debug_mode {
469            println!(
470                "🚀 Starting rule execution with {} rules (agenda group: {})",
471                self.knowledge_base.get_rules().len(),
472                self.agenda_manager.get_active_group()
473            );
474        }
475
476        for cycle in 0..self.config.max_cycles {
477            cycle_count = cycle + 1;
478            let mut any_rule_fired = false;
479            let mut fired_rules_in_cycle = std::collections::HashSet::new();
480
481            // Reset activation groups for each cycle
482            self.activation_group_manager.reset_cycle();
483
484            // Check for timeout
485            if let Some(timeout) = self.config.timeout {
486                if start_time.elapsed() > timeout {
487                    return Err(RuleEngineError::EvaluationError {
488                        message: "Execution timeout exceeded".to_string(),
489                    });
490                }
491            }
492
493            // Get rules sorted by salience (highest first)
494            let mut rules = self.knowledge_base.get_rules().clone();
495            rules.sort_by(|a, b| b.salience.cmp(&a.salience));
496
497            // Filter rules by agenda group
498            let rules: Vec<_> = rules
499                .iter()
500                .filter(|rule| self.agenda_manager.should_evaluate_rule(rule))
501                .collect();
502
503            for rule in &rules {
504                if !rule.enabled {
505                    continue;
506                }
507
508                // Check date effective/expires
509                if !rule.is_active_at(timestamp) {
510                    continue;
511                }
512
513                // Check agenda group constraints (lock-on-active)
514                if !self.agenda_manager.can_fire_rule(rule) {
515                    continue;
516                }
517
518                // Check activation group constraints
519                if !self.activation_group_manager.can_fire(rule) {
520                    continue;
521                }
522
523                // Check no-loop: if rule has no_loop=true and already fired globally, skip
524                if rule.no_loop && self.fired_rules_global.contains(&rule.name) {
525                    if self.config.debug_mode {
526                        println!("⛔ Skipping '{}' due to no_loop (already fired)", rule.name);
527                    }
528                    continue;
529                }
530
531                rules_evaluated += 1;
532                let rule_start = Instant::now();
533
534                if self.config.debug_mode {
535                    println!("📝 Evaluating rule: {} (no_loop={})", rule.name, rule.no_loop);
536                }
537
538                // Evaluate rule conditions
539                let condition_result = self.evaluate_conditions(&rule.conditions, facts)?;
540                if self.config.debug_mode {
541                    println!(
542                        "  🔍 Condition result for '{}': {}",
543                        rule.name, condition_result
544                    );
545                }
546
547                if condition_result {
548                    if self.config.debug_mode {
549                        println!(
550                            "🔥 Rule '{}' fired (salience: {})",
551                            rule.name, rule.salience
552                        );
553                    }
554
555                    // Execute actions
556                    for action in &rule.actions {
557                        self.execute_action(action, facts)?;
558                    }
559
560                    let rule_duration = rule_start.elapsed();
561
562                    // Record analytics if enabled
563                    if let Some(analytics) = &mut self.analytics {
564                        analytics.record_execution(&rule.name, rule_duration, true, true, None, 0);
565                    }
566
567                    rules_fired += 1;
568                    any_rule_fired = true;
569
570                    // Track that this rule fired in this cycle (for cycle counting)
571                    fired_rules_in_cycle.insert(rule.name.clone());
572
573                    // Track that this rule fired globally (for no-loop support)
574                    if rule.no_loop {
575                        self.fired_rules_global.insert(rule.name.clone());
576                        if self.config.debug_mode {
577                            println!("  🔒 Marked '{}' as fired (no_loop tracking)", rule.name);
578                        }
579                    }
580
581                    // Mark rule as fired for agenda and activation group management
582                    self.agenda_manager.mark_rule_fired(rule);
583                    self.activation_group_manager.mark_fired(rule);
584                } else {
585                    let rule_duration = rule_start.elapsed();
586
587                    // Record analytics for failed rules too
588                    if let Some(analytics) = &mut self.analytics {
589                        analytics.record_execution(
590                            &rule.name,
591                            rule_duration,
592                            false,
593                            false,
594                            None,
595                            0,
596                        );
597                    }
598                }
599            }
600
601            // If no rules fired in this cycle, we're done
602            if !any_rule_fired {
603                break;
604            }
605
606            // Sync any new workflow agenda activations at the end of each cycle
607            self.sync_workflow_agenda_activations();
608        }
609
610        let execution_time = start_time.elapsed();
611
612        Ok(GruleExecutionResult {
613            cycle_count,
614            rules_evaluated,
615            rules_fired,
616            execution_time,
617        })
618    }
619
620    /// Evaluate conditions against facts
621    fn evaluate_conditions(
622        &self,
623        conditions: &crate::engine::rule::ConditionGroup,
624        facts: &Facts,
625    ) -> Result<bool> {
626        use crate::engine::pattern_matcher::PatternMatcher;
627        use crate::engine::rule::ConditionGroup;
628
629        match conditions {
630            ConditionGroup::Single(condition) => self.evaluate_single_condition(condition, facts),
631            ConditionGroup::Compound {
632                left,
633                operator,
634                right,
635            } => {
636                let left_result = self.evaluate_conditions(left, facts)?;
637                let right_result = self.evaluate_conditions(right, facts)?;
638
639                match operator {
640                    crate::types::LogicalOperator::And => Ok(left_result && right_result),
641                    crate::types::LogicalOperator::Or => Ok(left_result || right_result),
642                    crate::types::LogicalOperator::Not => Err(RuleEngineError::EvaluationError {
643                        message: "NOT operator should not appear in compound conditions"
644                            .to_string(),
645                    }),
646                }
647            }
648            ConditionGroup::Not(condition) => {
649                let result = self.evaluate_conditions(condition, facts)?;
650                Ok(!result)
651            }
652            // Pattern matching conditions
653            ConditionGroup::Exists(condition) => {
654                Ok(PatternMatcher::evaluate_exists(condition, facts))
655            }
656            ConditionGroup::Forall(condition) => {
657                Ok(PatternMatcher::evaluate_forall(condition, facts))
658            }
659            ConditionGroup::Accumulate {
660                result_var,
661                source_pattern,
662                extract_field,
663                source_conditions,
664                function,
665                function_arg,
666            } => {
667                // Evaluate accumulate and inject result into facts
668                self.evaluate_accumulate(
669                    result_var,
670                    source_pattern,
671                    extract_field,
672                    source_conditions,
673                    function,
674                    function_arg,
675                    facts,
676                )?;
677                // After injecting result, return true to continue
678                Ok(true)
679            }
680        }
681    }
682
683    /// Evaluate accumulate condition and inject result into facts
684    fn evaluate_accumulate(
685        &self,
686        result_var: &str,
687        source_pattern: &str,
688        extract_field: &str,
689        source_conditions: &[String],
690        function: &str,
691        function_arg: &str,
692        facts: &Facts,
693    ) -> Result<()> {
694        use crate::rete::accumulate::*;
695
696        // 1. Collect all facts matching the source pattern
697        let all_facts = facts.get_all_facts();
698        let mut matching_values = Vec::new();
699
700        // Find all facts that match the pattern (e.g., "Order.amount", "Order.status")
701        let pattern_prefix = format!("{}.", source_pattern);
702
703        // Group facts by instance (e.g., Order.1.amount, Order.1.status)
704        let mut instances: HashMap<String, HashMap<String, Value>> = HashMap::new();
705
706        for (key, value) in &all_facts {
707            if key.starts_with(&pattern_prefix) {
708                // Extract instance ID if present (e.g., "Order.1.amount" -> "1")
709                let parts: Vec<&str> = key.strip_prefix(&pattern_prefix).unwrap().split('.').collect();
710
711                if parts.len() >= 2 {
712                    // Has instance ID: Order.1.amount
713                    let instance_id = parts[0];
714                    let field_name = parts[1..].join(".");
715
716                    instances
717                        .entry(instance_id.to_string())
718                        .or_insert_with(HashMap::new)
719                        .insert(field_name, value.clone());
720                } else if parts.len() == 1 {
721                    // No instance ID: Order.amount (single instance)
722                    instances
723                        .entry("default".to_string())
724                        .or_insert_with(HashMap::new)
725                        .insert(parts[0].to_string(), value.clone());
726                }
727            }
728        }
729
730        // 2. Filter instances by source conditions
731        for (_instance_id, instance_facts) in instances {
732            // Check if this instance matches all source conditions
733            let mut matches = true;
734
735            for condition_str in source_conditions {
736                // Parse condition: "status == \"completed\""
737                if !self.evaluate_condition_string(condition_str, &instance_facts) {
738                    matches = false;
739                    break;
740                }
741            }
742
743            if matches {
744                // Extract the field value
745                if let Some(value) = instance_facts.get(extract_field) {
746                    matching_values.push(value.clone());
747                }
748            }
749        }
750
751        // 3. Run accumulate function
752        let result = match function {
753            "sum" => {
754                let mut state = SumFunction.init();
755                for value in &matching_values {
756                    state.accumulate(&self.value_to_fact_value(value));
757                }
758                self.fact_value_to_value(&state.get_result())
759            }
760            "count" => {
761                let mut state = CountFunction.init();
762                for value in &matching_values {
763                    state.accumulate(&self.value_to_fact_value(value));
764                }
765                self.fact_value_to_value(&state.get_result())
766            }
767            "average" | "avg" => {
768                let mut state = AverageFunction.init();
769                for value in &matching_values {
770                    state.accumulate(&self.value_to_fact_value(value));
771                }
772                self.fact_value_to_value(&state.get_result())
773            }
774            "min" => {
775                let mut state = MinFunction.init();
776                for value in &matching_values {
777                    state.accumulate(&self.value_to_fact_value(value));
778                }
779                self.fact_value_to_value(&state.get_result())
780            }
781            "max" => {
782                let mut state = MaxFunction.init();
783                for value in &matching_values {
784                    state.accumulate(&self.value_to_fact_value(value));
785                }
786                self.fact_value_to_value(&state.get_result())
787            }
788            _ => {
789                return Err(RuleEngineError::EvaluationError {
790                    message: format!("Unknown accumulate function: {}", function),
791                });
792            }
793        };
794
795        // 4. Inject result into facts
796        // Use pattern.function as key to avoid collision
797        let result_key = format!("{}.{}", source_pattern, function);
798
799        facts.set(&result_key, result);
800
801        if self.config.debug_mode {
802            println!("    🧮 Accumulate result: {} = {:?}", result_key, facts.get(&result_key));
803        }
804
805        Ok(())
806    }
807
808    /// Helper: Convert Value to FactValue
809    fn value_to_fact_value(&self, value: &Value) -> crate::rete::facts::FactValue {
810        use crate::rete::facts::FactValue;
811        match value {
812            Value::Integer(i) => FactValue::Integer(*i),
813            Value::Number(n) => FactValue::Float(*n),
814            Value::String(s) => FactValue::String(s.clone()),
815            Value::Boolean(b) => FactValue::Boolean(*b),
816            _ => FactValue::String(value.to_string()),
817        }
818    }
819
820    /// Helper: Convert FactValue to Value
821    fn fact_value_to_value(&self, fact_value: &crate::rete::facts::FactValue) -> Value {
822        use crate::rete::facts::FactValue;
823        match fact_value {
824            FactValue::Integer(i) => Value::Integer(*i),
825            FactValue::Float(f) => Value::Number(*f),
826            FactValue::String(s) => Value::String(s.clone()),
827            FactValue::Boolean(b) => Value::Boolean(*b),
828            FactValue::Array(_) => Value::String(format!("{:?}", fact_value)),
829            FactValue::Null => Value::String("null".to_string()),
830        }
831    }
832
833    /// Helper: Evaluate a condition string against facts
834    fn evaluate_condition_string(&self, condition: &str, facts: &HashMap<String, Value>) -> bool {
835        // Simple condition parser: "field == value" or "field != value", etc.
836        let condition = condition.trim();
837
838        // Try to parse operator
839        let operators = ["==", "!=", ">=", "<=", ">", "<"];
840
841        for op in &operators {
842            if let Some(pos) = condition.find(op) {
843                let field = condition[..pos].trim();
844                let value_str = condition[pos + op.len()..].trim()
845                    .trim_matches('"')
846                    .trim_matches('\'');
847
848                if let Some(field_value) = facts.get(field) {
849                    return self.compare_values(field_value, op, value_str);
850                } else {
851                    return false;
852                }
853            }
854        }
855
856        false
857    }
858
859    /// Helper: Compare values
860    fn compare_values(&self, field_value: &Value, operator: &str, value_str: &str) -> bool {
861        match field_value {
862            Value::String(s) => {
863                match operator {
864                    "==" => s == value_str,
865                    "!=" => s != value_str,
866                    _ => false,
867                }
868            }
869            Value::Integer(i) => {
870                if let Ok(num) = value_str.parse::<i64>() {
871                    match operator {
872                        "==" => *i == num,
873                        "!=" => *i != num,
874                        ">" => *i > num,
875                        "<" => *i < num,
876                        ">=" => *i >= num,
877                        "<=" => *i <= num,
878                        _ => false,
879                    }
880                } else {
881                    false
882                }
883            }
884            Value::Number(n) => {
885                if let Ok(num) = value_str.parse::<f64>() {
886                    match operator {
887                        "==" => (*n - num).abs() < f64::EPSILON,
888                        "!=" => (*n - num).abs() >= f64::EPSILON,
889                        ">" => *n > num,
890                        "<" => *n < num,
891                        ">=" => *n >= num,
892                        "<=" => *n <= num,
893                        _ => false,
894                    }
895                } else {
896                    false
897                }
898            }
899            Value::Boolean(b) => {
900                if let Ok(bool_val) = value_str.parse::<bool>() {
901                    match operator {
902                        "==" => *b == bool_val,
903                        "!=" => *b != bool_val,
904                        _ => false,
905                    }
906                } else {
907                    false
908                }
909            }
910            _ => false,
911        }
912    }
913
914    /// Evaluate rule conditions - wrapper for evaluate_conditions for compatibility
915    fn evaluate_rule_conditions(
916        &self,
917        rule: &crate::engine::rule::Rule,
918        facts: &Facts,
919    ) -> Result<bool> {
920        self.evaluate_conditions(&rule.conditions, facts)
921    }
922
923    /// Check if a fact object has been retracted
924    fn is_retracted(&self, object_name: &str, facts: &Facts) -> bool {
925        let retract_key = format!("_retracted_{}", object_name);
926        matches!(facts.get(&retract_key), Some(Value::Boolean(true)))
927    }
928
929    /// Evaluate a single condition
930    fn evaluate_single_condition(
931        &self,
932        condition: &crate::engine::rule::Condition,
933        facts: &Facts,
934    ) -> Result<bool> {
935        use crate::engine::rule::ConditionExpression;
936
937        let result = match &condition.expression {
938            ConditionExpression::Field(field_name) => {
939                // Check if the fact object has been retracted
940                // Extract object name from field (e.g., "Session.expired" -> "Session")
941                if let Some(object_name) = field_name.split('.').next() {
942                    if self.is_retracted(object_name, facts) {
943                        if self.config.debug_mode {
944                            println!("    🗑️ Skipping retracted fact: {}", object_name);
945                        }
946                        return Ok(false);
947                    }
948                }
949
950                // Field condition - try nested first, then flat lookup
951                let field_value = facts
952                    .get_nested(field_name)
953                    .or_else(|| facts.get(field_name));
954
955                if self.config.debug_mode {
956                    println!(
957                        "    🔎 Evaluating field condition: {} {} {:?}",
958                        field_name,
959                        format!("{:?}", condition.operator).to_lowercase(),
960                        condition.value
961                    );
962                    println!("      Field value: {:?}", field_value);
963                }
964
965                if let Some(value) = field_value {
966                    // condition.operator.evaluate(&value, &condition.value)
967                    // If the condition's right-hand value is a string that names another fact,
968                    // try to resolve that fact and use its value for comparison. This allows
969                    // rules like `L1 > L1Min` where the parser may have stored "L1Min"
970                    // as a string literal.
971                    let rhs = match &condition.value {
972                        crate::types::Value::String(s) => {
973                            // Try nested lookup first, then flat lookup
974                            facts
975                                .get_nested(s)
976                                .or_else(|| facts.get(s))
977                                .unwrap_or(crate::types::Value::String(s.clone()))
978                        }
979                        _ => condition.value.clone(),
980                    };
981
982                    if self.config.debug_mode {
983                        println!("      Resolved RHS for comparison: {:?}", rhs);
984                    }
985
986                    condition.operator.evaluate(&value, &rhs)
987                } else {
988                    false
989                }
990            }
991            ConditionExpression::FunctionCall { name, args } => {
992                // Function call condition
993                if self.config.debug_mode {
994                    println!(
995                        "    🔎 Evaluating function condition: {}({:?}) {} {:?}",
996                        name,
997                        args,
998                        format!("{:?}", condition.operator).to_lowercase(),
999                        condition.value
1000                    );
1001                }
1002
1003                if let Some(function) = self.custom_functions.get(name) {
1004                    // Resolve arguments from facts
1005                    let arg_values: Vec<Value> = args
1006                        .iter()
1007                        .map(|arg| {
1008                            facts
1009                                .get_nested(arg)
1010                                .or_else(|| facts.get(arg))
1011                                .unwrap_or(Value::String(arg.clone()))
1012                        })
1013                        .collect();
1014
1015                    // Call the function
1016                    match function(&arg_values, facts) {
1017                        Ok(result_value) => {
1018                            if self.config.debug_mode {
1019                                println!("      Function result: {:?}", result_value);
1020                            }
1021                            condition.operator.evaluate(&result_value, &condition.value)
1022                        }
1023                        Err(e) => {
1024                            if self.config.debug_mode {
1025                                println!("      Function error: {}", e);
1026                            }
1027                            false
1028                        }
1029                    }
1030                } else {
1031                    if self.config.debug_mode {
1032                        println!("      Function '{}' not found", name);
1033                    }
1034                    false
1035                }
1036            }
1037            ConditionExpression::Test { name, args } => {
1038                // Test CE condition - expects boolean result
1039                if self.config.debug_mode {
1040                    println!("    🧪 Evaluating test CE: test({}({:?}))", name, args);
1041                }
1042
1043                if let Some(function) = self.custom_functions.get(name) {
1044                    // Resolve arguments from facts
1045                    let arg_values: Vec<Value> = args
1046                        .iter()
1047                        .map(|arg| {
1048                            let resolved = facts
1049                                .get_nested(arg)
1050                                .or_else(|| facts.get(arg))
1051                                .unwrap_or(Value::String(arg.clone()));
1052                            if self.config.debug_mode {
1053                                println!("      Resolving arg '{}' -> {:?}", arg, resolved);
1054                            }
1055                            resolved
1056                        })
1057                        .collect();
1058
1059                    // Call the function
1060                    match function(&arg_values, facts) {
1061                        Ok(result_value) => {
1062                            if self.config.debug_mode {
1063                                println!("      Test result: {:?}", result_value);
1064                            }
1065                            // Test CE expects boolean result directly
1066                            match result_value {
1067                                Value::Boolean(b) => b,
1068                                Value::Integer(i) => i != 0,
1069                                Value::Number(f) => f != 0.0,
1070                                Value::String(s) => !s.is_empty(),
1071                                _ => false,
1072                            }
1073                        }
1074                        Err(e) => {
1075                            if self.config.debug_mode {
1076                                println!("      Test function error: {}", e);
1077                            }
1078                            false
1079                        }
1080                    }
1081                } else {
1082                    if self.config.debug_mode {
1083                        println!("      Test function '{}' not found", name);
1084                    }
1085                    false
1086                }
1087            }
1088        };
1089
1090        if self.config.debug_mode {
1091            println!("      Result: {}", result);
1092        }
1093
1094        Ok(result)
1095    }
1096
1097    /// Execute an action
1098    fn execute_action(&mut self, action: &ActionType, facts: &Facts) -> Result<()> {
1099        match action {
1100            ActionType::Set { field, value } => {
1101                // Evaluate expression if value is an Expression
1102                let evaluated_value = match value {
1103                    Value::Expression(expr) => {
1104                        // Evaluate the expression with current facts
1105                        crate::expression::evaluate_expression(expr, facts)?
1106                    }
1107                    _ => value.clone(),
1108                };
1109
1110                // Try nested first, then fall back to flat key setting
1111                if let Err(_) = facts.set_nested(field, evaluated_value.clone()) {
1112                    // If nested fails, use flat key
1113                    facts.set(field, evaluated_value.clone());
1114                }
1115                if self.config.debug_mode {
1116                    println!("  ✅ Set {field} = {evaluated_value:?}");
1117                }
1118            }
1119            ActionType::Log { message } => {
1120                println!("📋 LOG: {}", message);
1121            }
1122            ActionType::Call { function, args } => {
1123                let result = self.execute_function_call(function, args, facts)?;
1124                if self.config.debug_mode {
1125                    println!("  📞 Called {function}({args:?}) -> {result}");
1126                }
1127            }
1128            ActionType::MethodCall {
1129                object,
1130                method,
1131                args,
1132            } => {
1133                let result = self.execute_method_call(object, method, args, facts)?;
1134                if self.config.debug_mode {
1135                    println!("  🔧 Called {object}.{method}({args:?}) -> {result}");
1136                }
1137            }
1138            ActionType::Update { object } => {
1139                if self.config.debug_mode {
1140                    println!("  🔄 Updated {object}");
1141                }
1142                // Update action is mainly for working memory management
1143                // In this implementation, it's mostly a no-op since we update in place
1144            }
1145            ActionType::Retract { object } => {
1146                if self.config.debug_mode {
1147                    println!("  🗑️ Retracted {object}");
1148                }
1149                // Mark fact as retracted in working memory
1150                facts.set(&format!("_retracted_{}", object), Value::Boolean(true));
1151            }
1152            ActionType::Custom {
1153                action_type,
1154                params,
1155            } => {
1156                if let Some(handler) = self.action_handlers.get(action_type) {
1157                    if self.config.debug_mode {
1158                        println!(
1159                            "  🎯 Executing custom action: {action_type} with params: {params:?}"
1160                        );
1161                    }
1162
1163                    // Resolve parameter values from facts
1164                    let resolved_params = self.resolve_action_parameters(params, facts)?;
1165
1166                    // Execute the registered handler
1167                    handler(&resolved_params, facts)?;
1168                } else {
1169                    if self.config.debug_mode {
1170                        println!("  ⚠️ No handler registered for custom action: {action_type}");
1171                        println!(
1172                            "     Available handlers: {:?}",
1173                            self.action_handlers.keys().collect::<Vec<_>>()
1174                        );
1175                    }
1176
1177                    // Return error if no handler found
1178                    return Err(RuleEngineError::EvaluationError {
1179                        message: format!(
1180                            "No action handler registered for '{action_type}'. Use engine.register_action_handler() to add custom action handlers."
1181                        ),
1182                    });
1183                }
1184            }
1185            // 🔄 Workflow Actions
1186            ActionType::ActivateAgendaGroup { group } => {
1187                if self.config.debug_mode {
1188                    println!("  🎯 Activating agenda group: {}", group);
1189                }
1190                // Sync with both workflow engine and agenda manager immediately
1191                self.workflow_engine.activate_agenda_group(group.clone());
1192                self.agenda_manager.set_focus(group);
1193            }
1194            ActionType::ScheduleRule {
1195                rule_name,
1196                delay_ms,
1197            } => {
1198                if self.config.debug_mode {
1199                    println!(
1200                        "  ⏰ Scheduling rule '{}' to execute in {}ms",
1201                        rule_name, delay_ms
1202                    );
1203                }
1204                self.workflow_engine
1205                    .schedule_rule(rule_name.clone(), *delay_ms, None);
1206            }
1207            ActionType::CompleteWorkflow { workflow_name } => {
1208                if self.config.debug_mode {
1209                    println!("  ✅ Completing workflow: {}", workflow_name);
1210                }
1211                self.workflow_engine
1212                    .complete_workflow(workflow_name.clone());
1213            }
1214            ActionType::SetWorkflowData { key, value } => {
1215                if self.config.debug_mode {
1216                    println!("  💾 Setting workflow data: {} = {:?}", key, value);
1217                }
1218                // For now, we'll use a default workflow ID. Later this could be enhanced
1219                // to track current workflow context
1220                let workflow_id = "default_workflow";
1221                self.workflow_engine
1222                    .set_workflow_data(workflow_id, key.clone(), value.clone());
1223            }
1224        }
1225        Ok(())
1226    }
1227
1228    /// Execute function call
1229    fn execute_function_call(
1230        &self,
1231        function: &str,
1232        args: &[Value],
1233        facts: &Facts,
1234    ) -> Result<String> {
1235        let function_lower = function.to_lowercase();
1236
1237        // Handle built-in utility functions
1238        match function_lower.as_str() {
1239            "log" | "print" | "println" => self.handle_log_function(args),
1240            "update" | "refresh" => self.handle_update_function(args),
1241            "now" | "timestamp" => self.handle_timestamp_function(),
1242            "random" => self.handle_random_function(args),
1243            "format" | "sprintf" => self.handle_format_function(args),
1244            "length" | "size" | "count" => self.handle_length_function(args),
1245            "sum" | "add" => self.handle_sum_function(args),
1246            "max" | "maximum" => self.handle_max_function(args),
1247            "min" | "minimum" => self.handle_min_function(args),
1248            "avg" | "average" => self.handle_average_function(args),
1249            "round" => self.handle_round_function(args),
1250            "floor" => self.handle_floor_function(args),
1251            "ceil" | "ceiling" => self.handle_ceil_function(args),
1252            "abs" | "absolute" => self.handle_abs_function(args),
1253            "contains" | "includes" => self.handle_contains_function(args),
1254            "startswith" | "begins_with" => self.handle_starts_with_function(args),
1255            "endswith" | "ends_with" => self.handle_ends_with_function(args),
1256            "lowercase" | "tolower" => self.handle_lowercase_function(args),
1257            "uppercase" | "toupper" => self.handle_uppercase_function(args),
1258            "trim" | "strip" => self.handle_trim_function(args),
1259            "split" => self.handle_split_function(args),
1260            "join" => self.handle_join_function(args),
1261            _ => {
1262                // Try to call custom user-defined function
1263                self.handle_custom_function(function, args, facts)
1264            }
1265        }
1266    }
1267
1268    /// Handle logging functions (log, print, println)
1269    fn handle_log_function(&self, args: &[Value]) -> Result<String> {
1270        let message = if args.is_empty() {
1271            "".to_string()
1272        } else if args.len() == 1 {
1273            args[0].to_string()
1274        } else {
1275            args.iter()
1276                .map(|v| v.to_string())
1277                .collect::<Vec<_>>()
1278                .join(" ")
1279        };
1280
1281        println!("📋 {}", message);
1282        Ok(message)
1283    }
1284
1285    /// Handle update/refresh functions
1286    fn handle_update_function(&self, args: &[Value]) -> Result<String> {
1287        if let Some(arg) = args.first() {
1288            Ok(format!("Updated: {}", arg.to_string()))
1289        } else {
1290            Ok("Updated".to_string())
1291        }
1292    }
1293
1294    /// Handle timestamp function
1295    fn handle_timestamp_function(&self) -> Result<String> {
1296        use std::time::{SystemTime, UNIX_EPOCH};
1297        let timestamp = SystemTime::now()
1298            .duration_since(UNIX_EPOCH)
1299            .map_err(|e| RuleEngineError::EvaluationError {
1300                message: format!("Failed to get timestamp: {}", e),
1301            })?
1302            .as_secs();
1303        Ok(timestamp.to_string())
1304    }
1305
1306    /// Handle random function
1307    fn handle_random_function(&self, args: &[Value]) -> Result<String> {
1308        use std::collections::hash_map::DefaultHasher;
1309        use std::hash::{Hash, Hasher};
1310
1311        // Simple pseudo-random based on current time (for deterministic behavior in tests)
1312        let mut hasher = DefaultHasher::new();
1313        std::time::SystemTime::now().hash(&mut hasher);
1314        let random_value = hasher.finish();
1315
1316        if args.is_empty() {
1317            Ok((random_value % 100).to_string()) // 0-99
1318        } else if let Some(Value::Number(max)) = args.first() {
1319            let max_val = *max as u64;
1320            Ok((random_value % max_val).to_string())
1321        } else {
1322            Ok(random_value.to_string())
1323        }
1324    }
1325
1326    /// Handle format function (simple sprintf-like)
1327    fn handle_format_function(&self, args: &[Value]) -> Result<String> {
1328        if args.is_empty() {
1329            return Ok("".to_string());
1330        }
1331
1332        let template = args[0].to_string();
1333        let values: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
1334
1335        // Simple placeholder replacement: {0}, {1}, etc.
1336        let mut result = template;
1337        for (i, value) in values.iter().enumerate() {
1338            result = result.replace(&format!("{{{}}}", i), value);
1339        }
1340
1341        Ok(result)
1342    }
1343
1344    /// Handle length/size functions
1345    fn handle_length_function(&self, args: &[Value]) -> Result<String> {
1346        if let Some(arg) = args.first() {
1347            match arg {
1348                Value::String(s) => Ok(s.len().to_string()),
1349                Value::Array(arr) => Ok(arr.len().to_string()),
1350                Value::Object(obj) => Ok(obj.len().to_string()),
1351                _ => Ok("1".to_string()), // Single value has length 1
1352            }
1353        } else {
1354            Ok("0".to_string())
1355        }
1356    }
1357
1358    /// Handle sum function
1359    fn handle_sum_function(&self, args: &[Value]) -> Result<String> {
1360        let sum = args.iter().fold(0.0, |acc, val| match val {
1361            Value::Number(n) => acc + n,
1362            Value::Integer(i) => acc + (*i as f64),
1363            _ => acc,
1364        });
1365        Ok(sum.to_string())
1366    }
1367
1368    /// Handle max function
1369    fn handle_max_function(&self, args: &[Value]) -> Result<String> {
1370        let max = args.iter().fold(f64::NEG_INFINITY, |acc, val| match val {
1371            Value::Number(n) => acc.max(*n),
1372            Value::Integer(i) => acc.max(*i as f64),
1373            _ => acc,
1374        });
1375        Ok(max.to_string())
1376    }
1377
1378    /// Handle min function
1379    fn handle_min_function(&self, args: &[Value]) -> Result<String> {
1380        let min = args.iter().fold(f64::INFINITY, |acc, val| match val {
1381            Value::Number(n) => acc.min(*n),
1382            Value::Integer(i) => acc.min(*i as f64),
1383            _ => acc,
1384        });
1385        Ok(min.to_string())
1386    }
1387
1388    /// Handle average function
1389    fn handle_average_function(&self, args: &[Value]) -> Result<String> {
1390        if args.is_empty() {
1391            return Ok("0".to_string());
1392        }
1393
1394        let (sum, count) = args.iter().fold((0.0, 0), |(sum, count), val| match val {
1395            Value::Number(n) => (sum + n, count + 1),
1396            Value::Integer(i) => (sum + (*i as f64), count + 1),
1397            _ => (sum, count),
1398        });
1399
1400        if count > 0 {
1401            Ok((sum / count as f64).to_string())
1402        } else {
1403            Ok("0".to_string())
1404        }
1405    }
1406
1407    /// Handle mathematical functions
1408    fn handle_round_function(&self, args: &[Value]) -> Result<String> {
1409        if let Some(Value::Number(n)) = args.first() {
1410            Ok(n.round().to_string())
1411        } else if let Some(Value::Integer(i)) = args.first() {
1412            Ok(i.to_string())
1413        } else {
1414            Err(RuleEngineError::EvaluationError {
1415                message: "round() requires a numeric argument".to_string(),
1416            })
1417        }
1418    }
1419
1420    fn handle_floor_function(&self, args: &[Value]) -> Result<String> {
1421        if let Some(Value::Number(n)) = args.first() {
1422            Ok(n.floor().to_string())
1423        } else if let Some(Value::Integer(i)) = args.first() {
1424            Ok(i.to_string())
1425        } else {
1426            Err(RuleEngineError::EvaluationError {
1427                message: "floor() requires a numeric argument".to_string(),
1428            })
1429        }
1430    }
1431
1432    fn handle_ceil_function(&self, args: &[Value]) -> Result<String> {
1433        if let Some(Value::Number(n)) = args.first() {
1434            Ok(n.ceil().to_string())
1435        } else if let Some(Value::Integer(i)) = args.first() {
1436            Ok(i.to_string())
1437        } else {
1438            Err(RuleEngineError::EvaluationError {
1439                message: "ceil() requires a numeric argument".to_string(),
1440            })
1441        }
1442    }
1443
1444    fn handle_abs_function(&self, args: &[Value]) -> Result<String> {
1445        if let Some(Value::Number(n)) = args.first() {
1446            Ok(n.abs().to_string())
1447        } else if let Some(Value::Integer(i)) = args.first() {
1448            Ok(i.abs().to_string())
1449        } else {
1450            Err(RuleEngineError::EvaluationError {
1451                message: "abs() requires a numeric argument".to_string(),
1452            })
1453        }
1454    }
1455
1456    /// Handle string functions
1457    fn handle_contains_function(&self, args: &[Value]) -> Result<String> {
1458        if args.len() >= 2 {
1459            let haystack = args[0].to_string();
1460            let needle = args[1].to_string();
1461            Ok(haystack.contains(&needle).to_string())
1462        } else {
1463            Err(RuleEngineError::EvaluationError {
1464                message: "contains() requires 2 arguments".to_string(),
1465            })
1466        }
1467    }
1468
1469    fn handle_starts_with_function(&self, args: &[Value]) -> Result<String> {
1470        if args.len() >= 2 {
1471            let text = args[0].to_string();
1472            let prefix = args[1].to_string();
1473            Ok(text.starts_with(&prefix).to_string())
1474        } else {
1475            Err(RuleEngineError::EvaluationError {
1476                message: "startswith() requires 2 arguments".to_string(),
1477            })
1478        }
1479    }
1480
1481    fn handle_ends_with_function(&self, args: &[Value]) -> Result<String> {
1482        if args.len() >= 2 {
1483            let text = args[0].to_string();
1484            let suffix = args[1].to_string();
1485            Ok(text.ends_with(&suffix).to_string())
1486        } else {
1487            Err(RuleEngineError::EvaluationError {
1488                message: "endswith() requires 2 arguments".to_string(),
1489            })
1490        }
1491    }
1492
1493    fn handle_lowercase_function(&self, args: &[Value]) -> Result<String> {
1494        if let Some(arg) = args.first() {
1495            Ok(arg.to_string().to_lowercase())
1496        } else {
1497            Err(RuleEngineError::EvaluationError {
1498                message: "lowercase() requires 1 argument".to_string(),
1499            })
1500        }
1501    }
1502
1503    fn handle_uppercase_function(&self, args: &[Value]) -> Result<String> {
1504        if let Some(arg) = args.first() {
1505            Ok(arg.to_string().to_uppercase())
1506        } else {
1507            Err(RuleEngineError::EvaluationError {
1508                message: "uppercase() requires 1 argument".to_string(),
1509            })
1510        }
1511    }
1512
1513    fn handle_trim_function(&self, args: &[Value]) -> Result<String> {
1514        if let Some(arg) = args.first() {
1515            Ok(arg.to_string().trim().to_string())
1516        } else {
1517            Err(RuleEngineError::EvaluationError {
1518                message: "trim() requires 1 argument".to_string(),
1519            })
1520        }
1521    }
1522
1523    fn handle_split_function(&self, args: &[Value]) -> Result<String> {
1524        if args.len() >= 2 {
1525            let text = args[0].to_string();
1526            let delimiter = args[1].to_string();
1527            let parts: Vec<String> = text.split(&delimiter).map(|s| s.to_string()).collect();
1528            Ok(format!("{:?}", parts)) // Return as debug string for now
1529        } else {
1530            Err(RuleEngineError::EvaluationError {
1531                message: "split() requires 2 arguments".to_string(),
1532            })
1533        }
1534    }
1535
1536    fn handle_join_function(&self, args: &[Value]) -> Result<String> {
1537        if args.len() >= 2 {
1538            let delimiter = args[0].to_string();
1539            let parts: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
1540            Ok(parts.join(&delimiter))
1541        } else {
1542            Err(RuleEngineError::EvaluationError {
1543                message: "join() requires at least 2 arguments".to_string(),
1544            })
1545        }
1546    }
1547
1548    /// Handle custom user-defined functions
1549    fn handle_custom_function(
1550        &self,
1551        function: &str,
1552        args: &[Value],
1553        facts: &Facts,
1554    ) -> Result<String> {
1555        // Check if we have a registered custom function
1556        if let Some(custom_func) = self.custom_functions.get(function) {
1557            if self.config.debug_mode {
1558                println!("🎯 Calling registered function: {}({:?})", function, args);
1559            }
1560
1561            match custom_func(args, facts) {
1562                Ok(result) => Ok(result.to_string()),
1563                Err(e) => Err(e),
1564            }
1565        } else {
1566            // Function not found - return error or placeholder
1567            if self.config.debug_mode {
1568                println!("⚠️ Custom function '{}' not registered", function);
1569            }
1570
1571            Err(RuleEngineError::EvaluationError {
1572                message: format!("Function '{}' is not registered. Use engine.register_function() to add custom functions.", function),
1573            })
1574        }
1575    }
1576
1577    /// Execute method call on object
1578    fn execute_method_call(
1579        &self,
1580        object_name: &str,
1581        method: &str,
1582        args: &[Value],
1583        facts: &Facts,
1584    ) -> Result<String> {
1585        // Get the object from facts
1586        let Some(object_value) = facts.get(object_name) else {
1587            return Err(RuleEngineError::EvaluationError {
1588                message: format!("Object '{}' not found in facts", object_name),
1589            });
1590        };
1591
1592        let method_lower = method.to_lowercase();
1593
1594        // Handle setter methods (set + property name)
1595        if method_lower.starts_with("set") && args.len() == 1 {
1596            return self.handle_setter_method(object_name, method, &args[0], object_value, facts);
1597        }
1598
1599        // Handle getter methods (get + property name)
1600        if method_lower.starts_with("get") && args.is_empty() {
1601            return self.handle_getter_method(object_name, method, &object_value);
1602        }
1603
1604        // Handle built-in methods
1605        match method_lower.as_str() {
1606            "tostring" => Ok(object_value.to_string()),
1607            "update" => {
1608                facts.add_value(object_name, object_value)?;
1609                Ok(format!("Updated {}", object_name))
1610            }
1611            "reset" => self.handle_reset_method(object_name, object_value, facts),
1612            _ => self.handle_property_access_or_fallback(
1613                object_name,
1614                method,
1615                args.len(),
1616                &object_value,
1617            ),
1618        }
1619    }
1620
1621    /// Handle setter method calls (setXxx)
1622    fn handle_setter_method(
1623        &self,
1624        object_name: &str,
1625        method: &str,
1626        new_value: &Value,
1627        mut object_value: Value,
1628        facts: &Facts,
1629    ) -> Result<String> {
1630        let property_name = Self::extract_property_name_from_setter(method);
1631
1632        match object_value {
1633            Value::Object(ref mut obj) => {
1634                obj.insert(property_name.clone(), new_value.clone());
1635                facts.add_value(object_name, object_value)?;
1636                Ok(format!(
1637                    "Set {} to {}",
1638                    property_name,
1639                    new_value.to_string()
1640                ))
1641            }
1642            _ => Err(RuleEngineError::EvaluationError {
1643                message: format!("Cannot call setter on non-object type: {}", object_name),
1644            }),
1645        }
1646    }
1647
1648    /// Handle getter method calls (getXxx)
1649    fn handle_getter_method(
1650        &self,
1651        object_name: &str,
1652        method: &str,
1653        object_value: &Value,
1654    ) -> Result<String> {
1655        let property_name = Self::extract_property_name_from_getter(method);
1656
1657        match object_value {
1658            Value::Object(obj) => {
1659                if let Some(value) = obj.get(&property_name) {
1660                    Ok(value.to_string())
1661                } else {
1662                    Err(RuleEngineError::EvaluationError {
1663                        message: format!(
1664                            "Property '{}' not found on object '{}'",
1665                            property_name, object_name
1666                        ),
1667                    })
1668                }
1669            }
1670            _ => Err(RuleEngineError::EvaluationError {
1671                message: format!("Cannot call getter on non-object type: {}", object_name),
1672            }),
1673        }
1674    }
1675
1676    /// Handle reset method call
1677    fn handle_reset_method(
1678        &self,
1679        object_name: &str,
1680        mut object_value: Value,
1681        facts: &Facts,
1682    ) -> Result<String> {
1683        match object_value {
1684            Value::Object(ref mut obj) => {
1685                obj.clear();
1686                facts.add_value(object_name, object_value)?;
1687                Ok(format!("Reset {}", object_name))
1688            }
1689            _ => Err(RuleEngineError::EvaluationError {
1690                message: format!("Cannot reset non-object type: {}", object_name),
1691            }),
1692        }
1693    }
1694
1695    /// Handle property access or fallback to generic method call
1696    fn handle_property_access_or_fallback(
1697        &self,
1698        object_name: &str,
1699        method: &str,
1700        arg_count: usize,
1701        object_value: &Value,
1702    ) -> Result<String> {
1703        if let Value::Object(obj) = object_value {
1704            // Try exact property name match
1705            if let Some(value) = obj.get(method) {
1706                return Ok(value.to_string());
1707            }
1708
1709            // Try capitalized property name
1710            let capitalized_method = Self::capitalize_first_letter(method);
1711            if let Some(value) = obj.get(&capitalized_method) {
1712                return Ok(value.to_string());
1713            }
1714        }
1715
1716        // Fallback to generic response
1717        Ok(format!(
1718            "Called {}.{} with {} args",
1719            object_name, method, arg_count
1720        ))
1721    }
1722
1723    /// Extract property name from setter method (setXxx -> Xxx)
1724    fn extract_property_name_from_setter(method: &str) -> String {
1725        let property_name = &method[3..]; // Remove "set" prefix
1726        Self::capitalize_first_letter(property_name)
1727    }
1728
1729    /// Extract property name from getter method (getXxx -> Xxx)
1730    fn extract_property_name_from_getter(method: &str) -> String {
1731        let property_name = &method[3..]; // Remove "get" prefix
1732        Self::capitalize_first_letter(property_name)
1733    }
1734
1735    /// Helper function to capitalize first letter of a string
1736    fn capitalize_first_letter(s: &str) -> String {
1737        if s.is_empty() {
1738            return String::new();
1739        }
1740        let mut chars = s.chars();
1741        match chars.next() {
1742            None => String::new(),
1743            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1744        }
1745    }
1746
1747    /// Resolve action parameters by replacing fact references with actual values
1748    fn resolve_action_parameters(
1749        &self,
1750        params: &HashMap<String, Value>,
1751        facts: &Facts,
1752    ) -> Result<HashMap<String, Value>> {
1753        let mut resolved = HashMap::new();
1754
1755        for (key, value) in params {
1756            let resolved_value = match value {
1757                Value::String(s) => {
1758                    // Check if string looks like a fact reference (contains dot)
1759                    if s.contains('.') {
1760                        // Try to get the value from facts
1761                        if let Some(fact_value) = facts.get_nested(s) {
1762                            fact_value
1763                        } else {
1764                            // If not found, keep original string
1765                            value.clone()
1766                        }
1767                    } else {
1768                        value.clone()
1769                    }
1770                }
1771                _ => value.clone(),
1772            };
1773            resolved.insert(key.clone(), resolved_value);
1774        }
1775
1776        Ok(resolved)
1777    }
1778
1779    // 🔌 Plugin System Methods
1780
1781    /// Load a plugin into the engine
1782    pub fn load_plugin(
1783        &mut self,
1784        plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
1785    ) -> Result<()> {
1786        // First register the plugin actions with this engine
1787        plugin.register_actions(self)?;
1788        plugin.register_functions(self)?;
1789
1790        // Then store it in the plugin manager
1791        self.plugin_manager.load_plugin(plugin)
1792    }
1793
1794    /// Unload a plugin from the engine
1795    pub fn unload_plugin(&mut self, name: &str) -> Result<()> {
1796        self.plugin_manager.unload_plugin(name)
1797    }
1798
1799    /// Hot reload a plugin
1800    pub fn hot_reload_plugin(
1801        &mut self,
1802        name: &str,
1803        new_plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
1804    ) -> Result<()> {
1805        // Unload old plugin
1806        self.plugin_manager.unload_plugin(name)?;
1807
1808        // Register new plugin actions
1809        new_plugin.register_actions(self)?;
1810        new_plugin.register_functions(self)?;
1811
1812        // Load new plugin
1813        self.plugin_manager.load_plugin(new_plugin)
1814    }
1815
1816    /// Get plugin information
1817    pub fn get_plugin_info(&self, name: &str) -> Option<&crate::engine::plugin::PluginMetadata> {
1818        self.plugin_manager.get_plugin_info(name)
1819    }
1820
1821    /// List all loaded plugins
1822    pub fn list_plugins(&self) -> Vec<PluginInfo> {
1823        self.plugin_manager.list_plugins()
1824    }
1825
1826    /// Get plugin statistics
1827    pub fn get_plugin_stats(&self) -> PluginStats {
1828        self.plugin_manager.get_stats()
1829    }
1830
1831    /// Check health of all plugins
1832    pub fn plugin_health_check(&mut self) -> HashMap<String, crate::engine::plugin::PluginHealth> {
1833        self.plugin_manager.plugin_health_check()
1834    }
1835
1836    /// Configure plugin manager
1837    pub fn configure_plugins(&mut self, config: PluginConfig) {
1838        self.plugin_manager = PluginManager::new(config);
1839    }
1840}