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            ConditionExpression::MultiField { field, operation, variable: _ } => {
1089                // Multi-field operation condition
1090                if self.config.debug_mode {
1091                    println!("    📦 Evaluating multi-field: {}.{}", field, operation);
1092                }
1093
1094                // Get the field value
1095                let field_value = facts.get_nested(field).or_else(|| facts.get(field));
1096
1097                if let Some(value) = field_value {
1098                    match operation.as_str() {
1099                        "empty" => {
1100                            matches!(value, Value::Array(arr) if arr.is_empty())
1101                        }
1102                        "not_empty" => {
1103                            matches!(value, Value::Array(arr) if !arr.is_empty())
1104                        }
1105                        "count" => {
1106                            if let Value::Array(arr) = value {
1107                                let count = Value::Integer(arr.len() as i64);
1108                                condition.operator.evaluate(&count, &condition.value)
1109                            } else {
1110                                false
1111                            }
1112                        }
1113                        "contains" => {
1114                            // Use existing contains operator
1115                            condition.operator.evaluate(&value, &condition.value)
1116                        }
1117                        _ => {
1118                            // Other operations (collect, first, last) not fully supported yet
1119                            // Return true to not block rule evaluation
1120                            if self.config.debug_mode {
1121                                println!("      ⚠️ Operation '{}' not fully implemented yet", operation);
1122                            }
1123                            true
1124                        }
1125                    }
1126                } else {
1127                    false
1128                }
1129            }
1130        };
1131
1132        if self.config.debug_mode {
1133            println!("      Result: {}", result);
1134        }
1135
1136        Ok(result)
1137    }
1138
1139    /// Execute an action
1140    fn execute_action(&mut self, action: &ActionType, facts: &Facts) -> Result<()> {
1141        match action {
1142            ActionType::Set { field, value } => {
1143                // Evaluate expression if value is an Expression
1144                let evaluated_value = match value {
1145                    Value::Expression(expr) => {
1146                        // Evaluate the expression with current facts
1147                        crate::expression::evaluate_expression(expr, facts)?
1148                    }
1149                    _ => value.clone(),
1150                };
1151
1152                // Try nested first, then fall back to flat key setting
1153                if let Err(_) = facts.set_nested(field, evaluated_value.clone()) {
1154                    // If nested fails, use flat key
1155                    facts.set(field, evaluated_value.clone());
1156                }
1157                if self.config.debug_mode {
1158                    println!("  ✅ Set {field} = {evaluated_value:?}");
1159                }
1160            }
1161            ActionType::Log { message } => {
1162                println!("📋 LOG: {}", message);
1163            }
1164            ActionType::Call { function, args } => {
1165                let result = self.execute_function_call(function, args, facts)?;
1166                if self.config.debug_mode {
1167                    println!("  📞 Called {function}({args:?}) -> {result}");
1168                }
1169            }
1170            ActionType::MethodCall {
1171                object,
1172                method,
1173                args,
1174            } => {
1175                let result = self.execute_method_call(object, method, args, facts)?;
1176                if self.config.debug_mode {
1177                    println!("  🔧 Called {object}.{method}({args:?}) -> {result}");
1178                }
1179            }
1180            ActionType::Update { object } => {
1181                if self.config.debug_mode {
1182                    println!("  🔄 Updated {object}");
1183                }
1184                // Update action is mainly for working memory management
1185                // In this implementation, it's mostly a no-op since we update in place
1186            }
1187            ActionType::Retract { object } => {
1188                if self.config.debug_mode {
1189                    println!("  🗑️ Retracted {object}");
1190                }
1191                // Mark fact as retracted in working memory
1192                facts.set(&format!("_retracted_{}", object), Value::Boolean(true));
1193            }
1194            ActionType::Custom {
1195                action_type,
1196                params,
1197            } => {
1198                if let Some(handler) = self.action_handlers.get(action_type) {
1199                    if self.config.debug_mode {
1200                        println!(
1201                            "  🎯 Executing custom action: {action_type} with params: {params:?}"
1202                        );
1203                    }
1204
1205                    // Resolve parameter values from facts
1206                    let resolved_params = self.resolve_action_parameters(params, facts)?;
1207
1208                    // Execute the registered handler
1209                    handler(&resolved_params, facts)?;
1210                } else {
1211                    if self.config.debug_mode {
1212                        println!("  ⚠️ No handler registered for custom action: {action_type}");
1213                        println!(
1214                            "     Available handlers: {:?}",
1215                            self.action_handlers.keys().collect::<Vec<_>>()
1216                        );
1217                    }
1218
1219                    // Return error if no handler found
1220                    return Err(RuleEngineError::EvaluationError {
1221                        message: format!(
1222                            "No action handler registered for '{action_type}'. Use engine.register_action_handler() to add custom action handlers."
1223                        ),
1224                    });
1225                }
1226            }
1227            // 🔄 Workflow Actions
1228            ActionType::ActivateAgendaGroup { group } => {
1229                if self.config.debug_mode {
1230                    println!("  🎯 Activating agenda group: {}", group);
1231                }
1232                // Sync with both workflow engine and agenda manager immediately
1233                self.workflow_engine.activate_agenda_group(group.clone());
1234                self.agenda_manager.set_focus(group);
1235            }
1236            ActionType::ScheduleRule {
1237                rule_name,
1238                delay_ms,
1239            } => {
1240                if self.config.debug_mode {
1241                    println!(
1242                        "  ⏰ Scheduling rule '{}' to execute in {}ms",
1243                        rule_name, delay_ms
1244                    );
1245                }
1246                self.workflow_engine
1247                    .schedule_rule(rule_name.clone(), *delay_ms, None);
1248            }
1249            ActionType::CompleteWorkflow { workflow_name } => {
1250                if self.config.debug_mode {
1251                    println!("  ✅ Completing workflow: {}", workflow_name);
1252                }
1253                self.workflow_engine
1254                    .complete_workflow(workflow_name.clone());
1255            }
1256            ActionType::SetWorkflowData { key, value } => {
1257                if self.config.debug_mode {
1258                    println!("  💾 Setting workflow data: {} = {:?}", key, value);
1259                }
1260                // For now, we'll use a default workflow ID. Later this could be enhanced
1261                // to track current workflow context
1262                let workflow_id = "default_workflow";
1263                self.workflow_engine
1264                    .set_workflow_data(workflow_id, key.clone(), value.clone());
1265            }
1266        }
1267        Ok(())
1268    }
1269
1270    /// Execute function call
1271    fn execute_function_call(
1272        &self,
1273        function: &str,
1274        args: &[Value],
1275        facts: &Facts,
1276    ) -> Result<String> {
1277        let function_lower = function.to_lowercase();
1278
1279        // Handle built-in utility functions
1280        match function_lower.as_str() {
1281            "log" | "print" | "println" => self.handle_log_function(args),
1282            "update" | "refresh" => self.handle_update_function(args),
1283            "now" | "timestamp" => self.handle_timestamp_function(),
1284            "random" => self.handle_random_function(args),
1285            "format" | "sprintf" => self.handle_format_function(args),
1286            "length" | "size" | "count" => self.handle_length_function(args),
1287            "sum" | "add" => self.handle_sum_function(args),
1288            "max" | "maximum" => self.handle_max_function(args),
1289            "min" | "minimum" => self.handle_min_function(args),
1290            "avg" | "average" => self.handle_average_function(args),
1291            "round" => self.handle_round_function(args),
1292            "floor" => self.handle_floor_function(args),
1293            "ceil" | "ceiling" => self.handle_ceil_function(args),
1294            "abs" | "absolute" => self.handle_abs_function(args),
1295            "contains" | "includes" => self.handle_contains_function(args),
1296            "startswith" | "begins_with" => self.handle_starts_with_function(args),
1297            "endswith" | "ends_with" => self.handle_ends_with_function(args),
1298            "lowercase" | "tolower" => self.handle_lowercase_function(args),
1299            "uppercase" | "toupper" => self.handle_uppercase_function(args),
1300            "trim" | "strip" => self.handle_trim_function(args),
1301            "split" => self.handle_split_function(args),
1302            "join" => self.handle_join_function(args),
1303            _ => {
1304                // Try to call custom user-defined function
1305                self.handle_custom_function(function, args, facts)
1306            }
1307        }
1308    }
1309
1310    /// Handle logging functions (log, print, println)
1311    fn handle_log_function(&self, args: &[Value]) -> Result<String> {
1312        let message = if args.is_empty() {
1313            "".to_string()
1314        } else if args.len() == 1 {
1315            args[0].to_string()
1316        } else {
1317            args.iter()
1318                .map(|v| v.to_string())
1319                .collect::<Vec<_>>()
1320                .join(" ")
1321        };
1322
1323        println!("📋 {}", message);
1324        Ok(message)
1325    }
1326
1327    /// Handle update/refresh functions
1328    fn handle_update_function(&self, args: &[Value]) -> Result<String> {
1329        if let Some(arg) = args.first() {
1330            Ok(format!("Updated: {}", arg.to_string()))
1331        } else {
1332            Ok("Updated".to_string())
1333        }
1334    }
1335
1336    /// Handle timestamp function
1337    fn handle_timestamp_function(&self) -> Result<String> {
1338        use std::time::{SystemTime, UNIX_EPOCH};
1339        let timestamp = SystemTime::now()
1340            .duration_since(UNIX_EPOCH)
1341            .map_err(|e| RuleEngineError::EvaluationError {
1342                message: format!("Failed to get timestamp: {}", e),
1343            })?
1344            .as_secs();
1345        Ok(timestamp.to_string())
1346    }
1347
1348    /// Handle random function
1349    fn handle_random_function(&self, args: &[Value]) -> Result<String> {
1350        use std::collections::hash_map::DefaultHasher;
1351        use std::hash::{Hash, Hasher};
1352
1353        // Simple pseudo-random based on current time (for deterministic behavior in tests)
1354        let mut hasher = DefaultHasher::new();
1355        std::time::SystemTime::now().hash(&mut hasher);
1356        let random_value = hasher.finish();
1357
1358        if args.is_empty() {
1359            Ok((random_value % 100).to_string()) // 0-99
1360        } else if let Some(Value::Number(max)) = args.first() {
1361            let max_val = *max as u64;
1362            Ok((random_value % max_val).to_string())
1363        } else {
1364            Ok(random_value.to_string())
1365        }
1366    }
1367
1368    /// Handle format function (simple sprintf-like)
1369    fn handle_format_function(&self, args: &[Value]) -> Result<String> {
1370        if args.is_empty() {
1371            return Ok("".to_string());
1372        }
1373
1374        let template = args[0].to_string();
1375        let values: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
1376
1377        // Simple placeholder replacement: {0}, {1}, etc.
1378        let mut result = template;
1379        for (i, value) in values.iter().enumerate() {
1380            result = result.replace(&format!("{{{}}}", i), value);
1381        }
1382
1383        Ok(result)
1384    }
1385
1386    /// Handle length/size functions
1387    fn handle_length_function(&self, args: &[Value]) -> Result<String> {
1388        if let Some(arg) = args.first() {
1389            match arg {
1390                Value::String(s) => Ok(s.len().to_string()),
1391                Value::Array(arr) => Ok(arr.len().to_string()),
1392                Value::Object(obj) => Ok(obj.len().to_string()),
1393                _ => Ok("1".to_string()), // Single value has length 1
1394            }
1395        } else {
1396            Ok("0".to_string())
1397        }
1398    }
1399
1400    /// Handle sum function
1401    fn handle_sum_function(&self, args: &[Value]) -> Result<String> {
1402        let sum = args.iter().fold(0.0, |acc, val| match val {
1403            Value::Number(n) => acc + n,
1404            Value::Integer(i) => acc + (*i as f64),
1405            _ => acc,
1406        });
1407        Ok(sum.to_string())
1408    }
1409
1410    /// Handle max function
1411    fn handle_max_function(&self, args: &[Value]) -> Result<String> {
1412        let max = args.iter().fold(f64::NEG_INFINITY, |acc, val| match val {
1413            Value::Number(n) => acc.max(*n),
1414            Value::Integer(i) => acc.max(*i as f64),
1415            _ => acc,
1416        });
1417        Ok(max.to_string())
1418    }
1419
1420    /// Handle min function
1421    fn handle_min_function(&self, args: &[Value]) -> Result<String> {
1422        let min = args.iter().fold(f64::INFINITY, |acc, val| match val {
1423            Value::Number(n) => acc.min(*n),
1424            Value::Integer(i) => acc.min(*i as f64),
1425            _ => acc,
1426        });
1427        Ok(min.to_string())
1428    }
1429
1430    /// Handle average function
1431    fn handle_average_function(&self, args: &[Value]) -> Result<String> {
1432        if args.is_empty() {
1433            return Ok("0".to_string());
1434        }
1435
1436        let (sum, count) = args.iter().fold((0.0, 0), |(sum, count), val| match val {
1437            Value::Number(n) => (sum + n, count + 1),
1438            Value::Integer(i) => (sum + (*i as f64), count + 1),
1439            _ => (sum, count),
1440        });
1441
1442        if count > 0 {
1443            Ok((sum / count as f64).to_string())
1444        } else {
1445            Ok("0".to_string())
1446        }
1447    }
1448
1449    /// Handle mathematical functions
1450    fn handle_round_function(&self, args: &[Value]) -> Result<String> {
1451        if let Some(Value::Number(n)) = args.first() {
1452            Ok(n.round().to_string())
1453        } else if let Some(Value::Integer(i)) = args.first() {
1454            Ok(i.to_string())
1455        } else {
1456            Err(RuleEngineError::EvaluationError {
1457                message: "round() requires a numeric argument".to_string(),
1458            })
1459        }
1460    }
1461
1462    fn handle_floor_function(&self, args: &[Value]) -> Result<String> {
1463        if let Some(Value::Number(n)) = args.first() {
1464            Ok(n.floor().to_string())
1465        } else if let Some(Value::Integer(i)) = args.first() {
1466            Ok(i.to_string())
1467        } else {
1468            Err(RuleEngineError::EvaluationError {
1469                message: "floor() requires a numeric argument".to_string(),
1470            })
1471        }
1472    }
1473
1474    fn handle_ceil_function(&self, args: &[Value]) -> Result<String> {
1475        if let Some(Value::Number(n)) = args.first() {
1476            Ok(n.ceil().to_string())
1477        } else if let Some(Value::Integer(i)) = args.first() {
1478            Ok(i.to_string())
1479        } else {
1480            Err(RuleEngineError::EvaluationError {
1481                message: "ceil() requires a numeric argument".to_string(),
1482            })
1483        }
1484    }
1485
1486    fn handle_abs_function(&self, args: &[Value]) -> Result<String> {
1487        if let Some(Value::Number(n)) = args.first() {
1488            Ok(n.abs().to_string())
1489        } else if let Some(Value::Integer(i)) = args.first() {
1490            Ok(i.abs().to_string())
1491        } else {
1492            Err(RuleEngineError::EvaluationError {
1493                message: "abs() requires a numeric argument".to_string(),
1494            })
1495        }
1496    }
1497
1498    /// Handle string functions
1499    fn handle_contains_function(&self, args: &[Value]) -> Result<String> {
1500        if args.len() >= 2 {
1501            let haystack = args[0].to_string();
1502            let needle = args[1].to_string();
1503            Ok(haystack.contains(&needle).to_string())
1504        } else {
1505            Err(RuleEngineError::EvaluationError {
1506                message: "contains() requires 2 arguments".to_string(),
1507            })
1508        }
1509    }
1510
1511    fn handle_starts_with_function(&self, args: &[Value]) -> Result<String> {
1512        if args.len() >= 2 {
1513            let text = args[0].to_string();
1514            let prefix = args[1].to_string();
1515            Ok(text.starts_with(&prefix).to_string())
1516        } else {
1517            Err(RuleEngineError::EvaluationError {
1518                message: "startswith() requires 2 arguments".to_string(),
1519            })
1520        }
1521    }
1522
1523    fn handle_ends_with_function(&self, args: &[Value]) -> Result<String> {
1524        if args.len() >= 2 {
1525            let text = args[0].to_string();
1526            let suffix = args[1].to_string();
1527            Ok(text.ends_with(&suffix).to_string())
1528        } else {
1529            Err(RuleEngineError::EvaluationError {
1530                message: "endswith() requires 2 arguments".to_string(),
1531            })
1532        }
1533    }
1534
1535    fn handle_lowercase_function(&self, args: &[Value]) -> Result<String> {
1536        if let Some(arg) = args.first() {
1537            Ok(arg.to_string().to_lowercase())
1538        } else {
1539            Err(RuleEngineError::EvaluationError {
1540                message: "lowercase() requires 1 argument".to_string(),
1541            })
1542        }
1543    }
1544
1545    fn handle_uppercase_function(&self, args: &[Value]) -> Result<String> {
1546        if let Some(arg) = args.first() {
1547            Ok(arg.to_string().to_uppercase())
1548        } else {
1549            Err(RuleEngineError::EvaluationError {
1550                message: "uppercase() requires 1 argument".to_string(),
1551            })
1552        }
1553    }
1554
1555    fn handle_trim_function(&self, args: &[Value]) -> Result<String> {
1556        if let Some(arg) = args.first() {
1557            Ok(arg.to_string().trim().to_string())
1558        } else {
1559            Err(RuleEngineError::EvaluationError {
1560                message: "trim() requires 1 argument".to_string(),
1561            })
1562        }
1563    }
1564
1565    fn handle_split_function(&self, args: &[Value]) -> Result<String> {
1566        if args.len() >= 2 {
1567            let text = args[0].to_string();
1568            let delimiter = args[1].to_string();
1569            let parts: Vec<String> = text.split(&delimiter).map(|s| s.to_string()).collect();
1570            Ok(format!("{:?}", parts)) // Return as debug string for now
1571        } else {
1572            Err(RuleEngineError::EvaluationError {
1573                message: "split() requires 2 arguments".to_string(),
1574            })
1575        }
1576    }
1577
1578    fn handle_join_function(&self, args: &[Value]) -> Result<String> {
1579        if args.len() >= 2 {
1580            let delimiter = args[0].to_string();
1581            let parts: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
1582            Ok(parts.join(&delimiter))
1583        } else {
1584            Err(RuleEngineError::EvaluationError {
1585                message: "join() requires at least 2 arguments".to_string(),
1586            })
1587        }
1588    }
1589
1590    /// Handle custom user-defined functions
1591    fn handle_custom_function(
1592        &self,
1593        function: &str,
1594        args: &[Value],
1595        facts: &Facts,
1596    ) -> Result<String> {
1597        // Check if we have a registered custom function
1598        if let Some(custom_func) = self.custom_functions.get(function) {
1599            if self.config.debug_mode {
1600                println!("🎯 Calling registered function: {}({:?})", function, args);
1601            }
1602
1603            match custom_func(args, facts) {
1604                Ok(result) => Ok(result.to_string()),
1605                Err(e) => Err(e),
1606            }
1607        } else {
1608            // Function not found - return error or placeholder
1609            if self.config.debug_mode {
1610                println!("⚠️ Custom function '{}' not registered", function);
1611            }
1612
1613            Err(RuleEngineError::EvaluationError {
1614                message: format!("Function '{}' is not registered. Use engine.register_function() to add custom functions.", function),
1615            })
1616        }
1617    }
1618
1619    /// Execute method call on object
1620    fn execute_method_call(
1621        &self,
1622        object_name: &str,
1623        method: &str,
1624        args: &[Value],
1625        facts: &Facts,
1626    ) -> Result<String> {
1627        // Get the object from facts
1628        let Some(object_value) = facts.get(object_name) else {
1629            return Err(RuleEngineError::EvaluationError {
1630                message: format!("Object '{}' not found in facts", object_name),
1631            });
1632        };
1633
1634        let method_lower = method.to_lowercase();
1635
1636        // Handle setter methods (set + property name)
1637        if method_lower.starts_with("set") && args.len() == 1 {
1638            return self.handle_setter_method(object_name, method, &args[0], object_value, facts);
1639        }
1640
1641        // Handle getter methods (get + property name)
1642        if method_lower.starts_with("get") && args.is_empty() {
1643            return self.handle_getter_method(object_name, method, &object_value);
1644        }
1645
1646        // Handle built-in methods
1647        match method_lower.as_str() {
1648            "tostring" => Ok(object_value.to_string()),
1649            "update" => {
1650                facts.add_value(object_name, object_value)?;
1651                Ok(format!("Updated {}", object_name))
1652            }
1653            "reset" => self.handle_reset_method(object_name, object_value, facts),
1654            _ => self.handle_property_access_or_fallback(
1655                object_name,
1656                method,
1657                args.len(),
1658                &object_value,
1659            ),
1660        }
1661    }
1662
1663    /// Handle setter method calls (setXxx)
1664    fn handle_setter_method(
1665        &self,
1666        object_name: &str,
1667        method: &str,
1668        new_value: &Value,
1669        mut object_value: Value,
1670        facts: &Facts,
1671    ) -> Result<String> {
1672        let property_name = Self::extract_property_name_from_setter(method);
1673
1674        match object_value {
1675            Value::Object(ref mut obj) => {
1676                obj.insert(property_name.clone(), new_value.clone());
1677                facts.add_value(object_name, object_value)?;
1678                Ok(format!(
1679                    "Set {} to {}",
1680                    property_name,
1681                    new_value.to_string()
1682                ))
1683            }
1684            _ => Err(RuleEngineError::EvaluationError {
1685                message: format!("Cannot call setter on non-object type: {}", object_name),
1686            }),
1687        }
1688    }
1689
1690    /// Handle getter method calls (getXxx)
1691    fn handle_getter_method(
1692        &self,
1693        object_name: &str,
1694        method: &str,
1695        object_value: &Value,
1696    ) -> Result<String> {
1697        let property_name = Self::extract_property_name_from_getter(method);
1698
1699        match object_value {
1700            Value::Object(obj) => {
1701                if let Some(value) = obj.get(&property_name) {
1702                    Ok(value.to_string())
1703                } else {
1704                    Err(RuleEngineError::EvaluationError {
1705                        message: format!(
1706                            "Property '{}' not found on object '{}'",
1707                            property_name, object_name
1708                        ),
1709                    })
1710                }
1711            }
1712            _ => Err(RuleEngineError::EvaluationError {
1713                message: format!("Cannot call getter on non-object type: {}", object_name),
1714            }),
1715        }
1716    }
1717
1718    /// Handle reset method call
1719    fn handle_reset_method(
1720        &self,
1721        object_name: &str,
1722        mut object_value: Value,
1723        facts: &Facts,
1724    ) -> Result<String> {
1725        match object_value {
1726            Value::Object(ref mut obj) => {
1727                obj.clear();
1728                facts.add_value(object_name, object_value)?;
1729                Ok(format!("Reset {}", object_name))
1730            }
1731            _ => Err(RuleEngineError::EvaluationError {
1732                message: format!("Cannot reset non-object type: {}", object_name),
1733            }),
1734        }
1735    }
1736
1737    /// Handle property access or fallback to generic method call
1738    fn handle_property_access_or_fallback(
1739        &self,
1740        object_name: &str,
1741        method: &str,
1742        arg_count: usize,
1743        object_value: &Value,
1744    ) -> Result<String> {
1745        if let Value::Object(obj) = object_value {
1746            // Try exact property name match
1747            if let Some(value) = obj.get(method) {
1748                return Ok(value.to_string());
1749            }
1750
1751            // Try capitalized property name
1752            let capitalized_method = Self::capitalize_first_letter(method);
1753            if let Some(value) = obj.get(&capitalized_method) {
1754                return Ok(value.to_string());
1755            }
1756        }
1757
1758        // Fallback to generic response
1759        Ok(format!(
1760            "Called {}.{} with {} args",
1761            object_name, method, arg_count
1762        ))
1763    }
1764
1765    /// Extract property name from setter method (setXxx -> Xxx)
1766    fn extract_property_name_from_setter(method: &str) -> String {
1767        let property_name = &method[3..]; // Remove "set" prefix
1768        Self::capitalize_first_letter(property_name)
1769    }
1770
1771    /// Extract property name from getter method (getXxx -> Xxx)
1772    fn extract_property_name_from_getter(method: &str) -> String {
1773        let property_name = &method[3..]; // Remove "get" prefix
1774        Self::capitalize_first_letter(property_name)
1775    }
1776
1777    /// Helper function to capitalize first letter of a string
1778    fn capitalize_first_letter(s: &str) -> String {
1779        if s.is_empty() {
1780            return String::new();
1781        }
1782        let mut chars = s.chars();
1783        match chars.next() {
1784            None => String::new(),
1785            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1786        }
1787    }
1788
1789    /// Resolve action parameters by replacing fact references with actual values
1790    fn resolve_action_parameters(
1791        &self,
1792        params: &HashMap<String, Value>,
1793        facts: &Facts,
1794    ) -> Result<HashMap<String, Value>> {
1795        let mut resolved = HashMap::new();
1796
1797        for (key, value) in params {
1798            let resolved_value = match value {
1799                Value::String(s) => {
1800                    // Check if string looks like a fact reference (contains dot)
1801                    if s.contains('.') {
1802                        // Try to get the value from facts
1803                        if let Some(fact_value) = facts.get_nested(s) {
1804                            fact_value
1805                        } else {
1806                            // If not found, keep original string
1807                            value.clone()
1808                        }
1809                    } else {
1810                        value.clone()
1811                    }
1812                }
1813                _ => value.clone(),
1814            };
1815            resolved.insert(key.clone(), resolved_value);
1816        }
1817
1818        Ok(resolved)
1819    }
1820
1821    // 🔌 Plugin System Methods
1822
1823    /// Load a plugin into the engine
1824    pub fn load_plugin(
1825        &mut self,
1826        plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
1827    ) -> Result<()> {
1828        // First register the plugin actions with this engine
1829        plugin.register_actions(self)?;
1830        plugin.register_functions(self)?;
1831
1832        // Then store it in the plugin manager
1833        self.plugin_manager.load_plugin(plugin)
1834    }
1835
1836    /// Unload a plugin from the engine
1837    pub fn unload_plugin(&mut self, name: &str) -> Result<()> {
1838        self.plugin_manager.unload_plugin(name)
1839    }
1840
1841    /// Hot reload a plugin
1842    pub fn hot_reload_plugin(
1843        &mut self,
1844        name: &str,
1845        new_plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
1846    ) -> Result<()> {
1847        // Unload old plugin
1848        self.plugin_manager.unload_plugin(name)?;
1849
1850        // Register new plugin actions
1851        new_plugin.register_actions(self)?;
1852        new_plugin.register_functions(self)?;
1853
1854        // Load new plugin
1855        self.plugin_manager.load_plugin(new_plugin)
1856    }
1857
1858    /// Get plugin information
1859    pub fn get_plugin_info(&self, name: &str) -> Option<&crate::engine::plugin::PluginMetadata> {
1860        self.plugin_manager.get_plugin_info(name)
1861    }
1862
1863    /// List all loaded plugins
1864    pub fn list_plugins(&self) -> Vec<PluginInfo> {
1865        self.plugin_manager.list_plugins()
1866    }
1867
1868    /// Get plugin statistics
1869    pub fn get_plugin_stats(&self) -> PluginStats {
1870        self.plugin_manager.get_stats()
1871    }
1872
1873    /// Check health of all plugins
1874    pub fn plugin_health_check(&mut self) -> HashMap<String, crate::engine::plugin::PluginHealth> {
1875        self.plugin_manager.plugin_health_check()
1876    }
1877
1878    /// Configure plugin manager
1879    pub fn configure_plugins(&mut self, config: PluginConfig) {
1880        self.plugin_manager = PluginManager::new(config);
1881    }
1882}