1use crate::engine::rule::{Condition, ConditionGroup, Rule};
2use crate::errors::{Result, RuleEngineError};
3use crate::types::{ActionType, Operator, Value};
4use chrono::{DateTime, Utc};
5use regex::Regex;
6use std::collections::HashMap;
7
8pub struct GRLParser;
11
12#[derive(Debug, Default)]
14struct RuleAttributes {
15    pub no_loop: bool,
16    pub lock_on_active: bool,
17    pub agenda_group: Option<String>,
18    pub activation_group: Option<String>,
19    pub date_effective: Option<DateTime<Utc>>,
20    pub date_expires: Option<DateTime<Utc>>,
21}
22
23impl GRLParser {
24    pub fn parse_rule(grl_text: &str) -> Result<Rule> {
37        let mut parser = GRLParser;
38        parser.parse_single_rule(grl_text)
39    }
40
41    pub fn parse_rules(grl_text: &str) -> Result<Vec<Rule>> {
43        let mut parser = GRLParser;
44        parser.parse_multiple_rules(grl_text)
45    }
46
47    fn parse_single_rule(&mut self, grl_text: &str) -> Result<Rule> {
48        let cleaned = self.clean_text(grl_text);
49
50        let rule_regex = Regex::new(r#"rule\s+(?:"([^"]+)"|([a-zA-Z_]\w*))\s*([^{]*)\{(.+)\}"#)
52            .map_err(|e| RuleEngineError::ParseError {
53                message: format!("Invalid rule regex: {}", e),
54            })?;
55
56        let captures =
57            rule_regex
58                .captures(&cleaned)
59                .ok_or_else(|| RuleEngineError::ParseError {
60                    message: format!("Invalid GRL rule format. Input: {}", cleaned),
61                })?;
62
63        let rule_name = if let Some(quoted_name) = captures.get(1) {
65            quoted_name.as_str().to_string()
66        } else if let Some(unquoted_name) = captures.get(2) {
67            unquoted_name.as_str().to_string()
68        } else {
69            return Err(RuleEngineError::ParseError {
70                message: "Could not extract rule name".to_string(),
71            });
72        };
73
74        let attributes_section = captures.get(3).map(|m| m.as_str()).unwrap_or("");
76
77        let rule_body = captures.get(4).unwrap().as_str();
79
80        let salience = self.extract_salience(attributes_section)?;
82
83        let when_then_regex =
85            Regex::new(r"when\s+(.+?)\s+then\s+(.+)").map_err(|e| RuleEngineError::ParseError {
86                message: format!("Invalid when-then regex: {}", e),
87            })?;
88
89        let when_then_captures =
90            when_then_regex
91                .captures(rule_body)
92                .ok_or_else(|| RuleEngineError::ParseError {
93                    message: "Missing when or then clause".to_string(),
94                })?;
95
96        let when_clause = when_then_captures.get(1).unwrap().as_str().trim();
97        let then_clause = when_then_captures.get(2).unwrap().as_str().trim();
98
99        let conditions = self.parse_when_clause(when_clause)?;
101        let actions = self.parse_then_clause(then_clause)?;
102
103        let attributes = self.parse_rule_attributes(attributes_section)?;
105
106        let mut rule = Rule::new(rule_name, conditions, actions);
108        rule = rule.with_priority(salience);
109
110        if attributes.no_loop {
112            rule = rule.with_no_loop(true);
113        }
114        if attributes.lock_on_active {
115            rule = rule.with_lock_on_active(true);
116        }
117        if let Some(agenda_group) = attributes.agenda_group {
118            rule = rule.with_agenda_group(agenda_group);
119        }
120        if let Some(activation_group) = attributes.activation_group {
121            rule = rule.with_activation_group(activation_group);
122        }
123        if let Some(date_effective) = attributes.date_effective {
124            rule = rule.with_date_effective(date_effective);
125        }
126        if let Some(date_expires) = attributes.date_expires {
127            rule = rule.with_date_expires(date_expires);
128        }
129
130        Ok(rule)
131    }
132
133    fn parse_multiple_rules(&mut self, grl_text: &str) -> Result<Vec<Rule>> {
134        let rule_regex =
137            Regex::new(r#"(?s)rule\s+(?:"[^"]+"|[a-zA-Z_]\w*).*?\}"#).map_err(|e| {
138                RuleEngineError::ParseError {
139                    message: format!("Rule splitting regex error: {}", e),
140                }
141            })?;
142
143        let mut rules = Vec::new();
144
145        for rule_match in rule_regex.find_iter(grl_text) {
146            let rule_text = rule_match.as_str();
147            let rule = self.parse_single_rule(rule_text)?;
148            rules.push(rule);
149        }
150
151        Ok(rules)
152    }
153
154    fn parse_rule_attributes(&self, rule_header: &str) -> Result<RuleAttributes> {
156        let mut attributes = RuleAttributes::default();
157
158        if rule_header.contains("no-loop") {
160            attributes.no_loop = true;
161        }
162        if rule_header.contains("lock-on-active") {
163            attributes.lock_on_active = true;
164        }
165
166        if let Some(agenda_group) = self.extract_quoted_attribute(rule_header, "agenda-group")? {
168            attributes.agenda_group = Some(agenda_group);
169        }
170
171        if let Some(activation_group) =
173            self.extract_quoted_attribute(rule_header, "activation-group")?
174        {
175            attributes.activation_group = Some(activation_group);
176        }
177
178        if let Some(date_str) = self.extract_quoted_attribute(rule_header, "date-effective")? {
180            attributes.date_effective = Some(self.parse_date_string(&date_str)?);
181        }
182
183        if let Some(date_str) = self.extract_quoted_attribute(rule_header, "date-expires")? {
185            attributes.date_expires = Some(self.parse_date_string(&date_str)?);
186        }
187
188        Ok(attributes)
189    }
190
191    fn extract_quoted_attribute(&self, header: &str, attribute: &str) -> Result<Option<String>> {
193        let pattern = format!(r#"{}\s+"([^"]+)""#, attribute);
194        let regex = Regex::new(&pattern).map_err(|e| RuleEngineError::ParseError {
195            message: format!("Invalid attribute regex for {}: {}", attribute, e),
196        })?;
197
198        if let Some(captures) = regex.captures(header) {
199            if let Some(value) = captures.get(1) {
200                return Ok(Some(value.as_str().to_string()));
201            }
202        }
203
204        Ok(None)
205    }
206
207    fn parse_date_string(&self, date_str: &str) -> Result<DateTime<Utc>> {
209        if let Ok(date) = DateTime::parse_from_rfc3339(date_str) {
211            return Ok(date.with_timezone(&Utc));
212        }
213
214        let formats = ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%d-%b-%Y", "%d-%m-%Y"];
216
217        for format in &formats {
218            if let Ok(naive_date) = chrono::NaiveDateTime::parse_from_str(date_str, format) {
219                return Ok(naive_date.and_utc());
220            }
221            if let Ok(naive_date) = chrono::NaiveDate::parse_from_str(date_str, format) {
222                return Ok(naive_date.and_hms_opt(0, 0, 0).unwrap().and_utc());
223            }
224        }
225
226        Err(RuleEngineError::ParseError {
227            message: format!("Unable to parse date: {}", date_str),
228        })
229    }
230
231    fn extract_salience(&self, attributes_section: &str) -> Result<i32> {
233        let salience_regex =
234            Regex::new(r"salience\s+(\d+)").map_err(|e| RuleEngineError::ParseError {
235                message: format!("Invalid salience regex: {}", e),
236            })?;
237
238        if let Some(captures) = salience_regex.captures(attributes_section) {
239            if let Some(salience_match) = captures.get(1) {
240                return salience_match.as_str().parse::<i32>().map_err(|e| {
241                    RuleEngineError::ParseError {
242                        message: format!("Invalid salience value: {}", e),
243                    }
244                });
245            }
246        }
247
248        Ok(0) }
250
251    fn clean_text(&self, text: &str) -> String {
252        text.lines()
253            .map(|line| line.trim())
254            .filter(|line| !line.is_empty() && !line.starts_with("//"))
255            .collect::<Vec<_>>()
256            .join(" ")
257    }
258
259    fn parse_when_clause(&self, when_clause: &str) -> Result<ConditionGroup> {
260        let trimmed = when_clause.trim();
262
263        let clause = if trimmed.starts_with('(') && trimmed.ends_with(')') {
265            let inner = &trimmed[1..trimmed.len() - 1];
267            if self.is_balanced_parentheses(inner) {
268                inner
269            } else {
270                trimmed
271            }
272        } else {
273            trimmed
274        };
275
276        if let Some(parts) = self.split_logical_operator(clause, "||") {
278            return self.parse_or_parts(parts);
279        }
280
281        if let Some(parts) = self.split_logical_operator(clause, "&&") {
283            return self.parse_and_parts(parts);
284        }
285
286        if clause.trim_start().starts_with("!") {
288            return self.parse_not_condition(clause);
289        }
290
291        if clause.trim_start().starts_with("exists(") {
293            return self.parse_exists_condition(clause);
294        }
295
296        if clause.trim_start().starts_with("forall(") {
298            return self.parse_forall_condition(clause);
299        }
300
301        self.parse_single_condition(clause)
303    }
304
305    fn is_balanced_parentheses(&self, text: &str) -> bool {
306        let mut count = 0;
307        for ch in text.chars() {
308            match ch {
309                '(' => count += 1,
310                ')' => {
311                    count -= 1;
312                    if count < 0 {
313                        return false;
314                    }
315                }
316                _ => {}
317            }
318        }
319        count == 0
320    }
321
322    fn split_logical_operator(&self, clause: &str, operator: &str) -> Option<Vec<String>> {
323        let mut parts = Vec::new();
324        let mut current_part = String::new();
325        let mut paren_count = 0;
326        let mut chars = clause.chars().peekable();
327
328        while let Some(ch) = chars.next() {
329            match ch {
330                '(' => {
331                    paren_count += 1;
332                    current_part.push(ch);
333                }
334                ')' => {
335                    paren_count -= 1;
336                    current_part.push(ch);
337                }
338                '&' if operator == "&&" && paren_count == 0 => {
339                    if chars.peek() == Some(&'&') {
340                        chars.next(); parts.push(current_part.trim().to_string());
342                        current_part.clear();
343                    } else {
344                        current_part.push(ch);
345                    }
346                }
347                '|' if operator == "||" && paren_count == 0 => {
348                    if chars.peek() == Some(&'|') {
349                        chars.next(); parts.push(current_part.trim().to_string());
351                        current_part.clear();
352                    } else {
353                        current_part.push(ch);
354                    }
355                }
356                _ => {
357                    current_part.push(ch);
358                }
359            }
360        }
361
362        if !current_part.trim().is_empty() {
363            parts.push(current_part.trim().to_string());
364        }
365
366        if parts.len() > 1 {
367            Some(parts)
368        } else {
369            None
370        }
371    }
372
373    fn parse_or_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
374        let mut conditions = Vec::new();
375        for part in parts {
376            let condition = self.parse_when_clause(&part)?;
377            conditions.push(condition);
378        }
379
380        if conditions.is_empty() {
381            return Err(RuleEngineError::ParseError {
382                message: "No conditions found in OR".to_string(),
383            });
384        }
385
386        let mut iter = conditions.into_iter();
387        let mut result = iter.next().unwrap();
388        for condition in iter {
389            result = ConditionGroup::or(result, condition);
390        }
391
392        Ok(result)
393    }
394
395    fn parse_and_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
396        let mut conditions = Vec::new();
397        for part in parts {
398            let condition = self.parse_when_clause(&part)?;
399            conditions.push(condition);
400        }
401
402        if conditions.is_empty() {
403            return Err(RuleEngineError::ParseError {
404                message: "No conditions found in AND".to_string(),
405            });
406        }
407
408        let mut iter = conditions.into_iter();
409        let mut result = iter.next().unwrap();
410        for condition in iter {
411            result = ConditionGroup::and(result, condition);
412        }
413
414        Ok(result)
415    }
416
417    fn parse_not_condition(&self, clause: &str) -> Result<ConditionGroup> {
418        let inner_clause = clause.strip_prefix("!").unwrap().trim();
419        let inner_condition = self.parse_when_clause(inner_clause)?;
420        Ok(ConditionGroup::not(inner_condition))
421    }
422
423    fn parse_exists_condition(&self, clause: &str) -> Result<ConditionGroup> {
424        let clause = clause.trim_start();
425        if !clause.starts_with("exists(") || !clause.ends_with(")") {
426            return Err(RuleEngineError::ParseError {
427                message: "Invalid exists syntax. Expected: exists(condition)".to_string(),
428            });
429        }
430
431        let inner_clause = &clause[7..clause.len() - 1]; let inner_condition = self.parse_when_clause(inner_clause)?;
434        Ok(ConditionGroup::exists(inner_condition))
435    }
436
437    fn parse_forall_condition(&self, clause: &str) -> Result<ConditionGroup> {
438        let clause = clause.trim_start();
439        if !clause.starts_with("forall(") || !clause.ends_with(")") {
440            return Err(RuleEngineError::ParseError {
441                message: "Invalid forall syntax. Expected: forall(condition)".to_string(),
442            });
443        }
444
445        let inner_clause = &clause[7..clause.len() - 1]; let inner_condition = self.parse_when_clause(inner_clause)?;
448        Ok(ConditionGroup::forall(inner_condition))
449    }
450
451    fn parse_single_condition(&self, clause: &str) -> Result<ConditionGroup> {
452        let trimmed_clause = clause.trim();
454        let clause_to_parse = if trimmed_clause.starts_with('(') && trimmed_clause.ends_with(')') {
455            trimmed_clause[1..trimmed_clause.len() - 1].trim()
456        } else {
457            trimmed_clause
458        };
459
460        let typed_object_regex =
462            Regex::new(r#"\$(\w+)\s*:\s*(\w+)\s*\(\s*(.+?)\s*\)"#).map_err(|e| {
463                RuleEngineError::ParseError {
464                    message: format!("Typed object regex error: {}", e),
465                }
466            })?;
467
468        if let Some(captures) = typed_object_regex.captures(clause_to_parse) {
469            let _object_name = captures.get(1).unwrap().as_str();
470            let _object_type = captures.get(2).unwrap().as_str();
471            let conditions_str = captures.get(3).unwrap().as_str();
472
473            return self.parse_conditions_within_object(conditions_str);
475        }
476
477        let function_regex = Regex::new(
479            r#"([a-zA-Z_]\w*)\s*\(([^)]*)\)\s*(>=|<=|==|!=|>|<|contains|matches)\s*(.+)"#,
480        )
481        .map_err(|e| RuleEngineError::ParseError {
482            message: format!("Function regex error: {}", e),
483        })?;
484
485        if let Some(captures) = function_regex.captures(clause_to_parse) {
486            let function_name = captures.get(1).unwrap().as_str().to_string();
487            let args_str = captures.get(2).unwrap().as_str();
488            let operator_str = captures.get(3).unwrap().as_str();
489            let value_str = captures.get(4).unwrap().as_str().trim();
490
491            let args: Vec<String> = if args_str.trim().is_empty() {
493                Vec::new()
494            } else {
495                args_str
496                    .split(',')
497                    .map(|arg| arg.trim().to_string())
498                    .collect()
499            };
500
501            let operator =
502                Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
503                    operator: operator_str.to_string(),
504                })?;
505
506            let value = self.parse_value(value_str)?;
507
508            let condition = Condition::with_function(function_name, args, operator, value);
509            return Ok(ConditionGroup::single(condition));
510        }
511
512        let condition_regex = Regex::new(
515            r#"([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\s*(>=|<=|==|!=|>|<|contains|matches)\s*(.+)"#,
516        )
517        .map_err(|e| RuleEngineError::ParseError {
518            message: format!("Condition regex error: {}", e),
519        })?;
520
521        let captures = condition_regex.captures(clause_to_parse).ok_or_else(|| {
522            RuleEngineError::ParseError {
523                message: format!("Invalid condition format: {}", clause_to_parse),
524            }
525        })?;
526
527        let field = captures.get(1).unwrap().as_str().to_string();
528        let operator_str = captures.get(2).unwrap().as_str();
529        let value_str = captures.get(3).unwrap().as_str().trim();
530
531        let operator =
532            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
533                operator: operator_str.to_string(),
534            })?;
535
536        let value = self.parse_value(value_str)?;
537
538        let condition = Condition::new(field, operator, value);
539        Ok(ConditionGroup::single(condition))
540    }
541
542    fn parse_conditions_within_object(&self, conditions_str: &str) -> Result<ConditionGroup> {
543        let parts: Vec<&str> = conditions_str.split("&&").collect();
545
546        let mut conditions = Vec::new();
547        for part in parts {
548            let trimmed = part.trim();
549            let condition = self.parse_simple_condition(trimmed)?;
550            conditions.push(condition);
551        }
552
553        if conditions.is_empty() {
555            return Err(RuleEngineError::ParseError {
556                message: "No conditions found".to_string(),
557            });
558        }
559
560        let mut iter = conditions.into_iter();
561        let mut result = iter.next().unwrap();
562        for condition in iter {
563            result = ConditionGroup::and(result, condition);
564        }
565
566        Ok(result)
567    }
568
569    fn parse_simple_condition(&self, clause: &str) -> Result<ConditionGroup> {
570        let condition_regex = Regex::new(r#"(\w+)\s*(>=|<=|==|!=|>|<)\s*(.+)"#).map_err(|e| {
572            RuleEngineError::ParseError {
573                message: format!("Simple condition regex error: {}", e),
574            }
575        })?;
576
577        let captures =
578            condition_regex
579                .captures(clause)
580                .ok_or_else(|| RuleEngineError::ParseError {
581                    message: format!("Invalid simple condition format: {}", clause),
582                })?;
583
584        let field = captures.get(1).unwrap().as_str().to_string();
585        let operator_str = captures.get(2).unwrap().as_str();
586        let value_str = captures.get(3).unwrap().as_str().trim();
587
588        let operator =
589            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
590                operator: operator_str.to_string(),
591            })?;
592
593        let value = self.parse_value(value_str)?;
594
595        let condition = Condition::new(field, operator, value);
596        Ok(ConditionGroup::single(condition))
597    }
598
599    fn parse_value(&self, value_str: &str) -> Result<Value> {
600        let trimmed = value_str.trim();
601
602        if (trimmed.starts_with('"') && trimmed.ends_with('"'))
604            || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
605        {
606            let unquoted = &trimmed[1..trimmed.len() - 1];
607            return Ok(Value::String(unquoted.to_string()));
608        }
609
610        if trimmed.eq_ignore_ascii_case("true") {
612            return Ok(Value::Boolean(true));
613        }
614        if trimmed.eq_ignore_ascii_case("false") {
615            return Ok(Value::Boolean(false));
616        }
617
618        if trimmed.eq_ignore_ascii_case("null") {
620            return Ok(Value::Null);
621        }
622
623        if let Ok(int_val) = trimmed.parse::<i64>() {
625            return Ok(Value::Integer(int_val));
626        }
627
628        if let Ok(float_val) = trimmed.parse::<f64>() {
629            return Ok(Value::Number(float_val));
630        }
631
632        if trimmed.contains('.') {
634            return Ok(Value::String(trimmed.to_string()));
635        }
636
637        Ok(Value::String(trimmed.to_string()))
639    }
640
641    fn parse_then_clause(&self, then_clause: &str) -> Result<Vec<ActionType>> {
642        let statements: Vec<&str> = then_clause
643            .split(';')
644            .map(|s| s.trim())
645            .filter(|s| !s.is_empty())
646            .collect();
647
648        let mut actions = Vec::new();
649
650        for statement in statements {
651            let action = self.parse_action_statement(statement)?;
652            actions.push(action);
653        }
654
655        Ok(actions)
656    }
657
658    fn parse_action_statement(&self, statement: &str) -> Result<ActionType> {
659        let trimmed = statement.trim();
660
661        let method_regex = Regex::new(r#"\$(\w+)\.(\w+)\s*\(([^)]*)\)"#).map_err(|e| {
663            RuleEngineError::ParseError {
664                message: format!("Method regex error: {}", e),
665            }
666        })?;
667
668        if let Some(captures) = method_regex.captures(trimmed) {
669            let object = captures.get(1).unwrap().as_str().to_string();
670            let method = captures.get(2).unwrap().as_str().to_string();
671            let args_str = captures.get(3).unwrap().as_str();
672
673            let args = if args_str.trim().is_empty() {
674                Vec::new()
675            } else {
676                self.parse_method_args(args_str)?
677            };
678
679            return Ok(ActionType::MethodCall {
680                object,
681                method,
682                args,
683            });
684        }
685
686        if let Some(eq_pos) = trimmed.find('=') {
688            let field = trimmed[..eq_pos].trim().to_string();
689            let value_str = trimmed[eq_pos + 1..].trim();
690            let value = self.parse_value(value_str)?;
691
692            return Ok(ActionType::Set { field, value });
693        }
694
695        let func_regex =
697            Regex::new(r#"(\w+)\s*\(\s*(.+?)?\s*\)"#).map_err(|e| RuleEngineError::ParseError {
698                message: format!("Function regex error: {}", e),
699            })?;
700
701        if let Some(captures) = func_regex.captures(trimmed) {
702            let function_name = captures.get(1).unwrap().as_str();
703            let args_str = captures.get(2).map(|m| m.as_str()).unwrap_or("");
704
705            match function_name.to_lowercase().as_str() {
706                "update" => {
707                    let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
709                        stripped.to_string()
710                    } else {
711                        args_str.to_string()
712                    };
713                    Ok(ActionType::Update {
714                        object: object_name,
715                    })
716                }
717                "log" => {
718                    let message = if args_str.is_empty() {
719                        "Log message".to_string()
720                    } else {
721                        let value = self.parse_value(args_str.trim())?;
722                        value.to_string()
723                    };
724                    Ok(ActionType::Log { message })
725                }
726                "activateagendagroup" | "activate_agenda_group" => {
727                    let agenda_group = if args_str.is_empty() {
728                        return Err(RuleEngineError::ParseError {
729                            message: "ActivateAgendaGroup requires agenda group name".to_string(),
730                        });
731                    } else {
732                        let value = self.parse_value(args_str.trim())?;
733                        match value {
734                            Value::String(s) => s,
735                            _ => value.to_string(),
736                        }
737                    };
738                    Ok(ActionType::ActivateAgendaGroup {
739                        group: agenda_group,
740                    })
741                }
742                "schedulerule" | "schedule_rule" => {
743                    let parts: Vec<&str> = args_str.split(',').collect();
745                    if parts.len() != 2 {
746                        return Err(RuleEngineError::ParseError {
747                            message: "ScheduleRule requires delay_ms and rule_name".to_string(),
748                        });
749                    }
750
751                    let delay_ms = self.parse_value(parts[0].trim())?;
752                    let rule_name = self.parse_value(parts[1].trim())?;
753
754                    let delay_ms = match delay_ms {
755                        Value::Integer(i) => i as u64,
756                        Value::Number(f) => f as u64,
757                        _ => {
758                            return Err(RuleEngineError::ParseError {
759                                message: "ScheduleRule delay_ms must be a number".to_string(),
760                            })
761                        }
762                    };
763
764                    let rule_name = match rule_name {
765                        Value::String(s) => s,
766                        _ => rule_name.to_string(),
767                    };
768
769                    Ok(ActionType::ScheduleRule {
770                        delay_ms,
771                        rule_name,
772                    })
773                }
774                "completeworkflow" | "complete_workflow" => {
775                    let workflow_id = if args_str.is_empty() {
776                        return Err(RuleEngineError::ParseError {
777                            message: "CompleteWorkflow requires workflow_id".to_string(),
778                        });
779                    } else {
780                        let value = self.parse_value(args_str.trim())?;
781                        match value {
782                            Value::String(s) => s,
783                            _ => value.to_string(),
784                        }
785                    };
786                    Ok(ActionType::CompleteWorkflow {
787                        workflow_name: workflow_id,
788                    })
789                }
790                "setworkflowdata" | "set_workflow_data" => {
791                    let data_str = args_str.trim();
793
794                    let (key, value) = if let Some(eq_pos) = data_str.find('=') {
796                        let key = data_str[..eq_pos].trim().trim_matches('"');
797                        let value_str = data_str[eq_pos + 1..].trim();
798                        let value = self.parse_value(value_str)?;
799                        (key.to_string(), value)
800                    } else {
801                        return Err(RuleEngineError::ParseError {
802                            message: "SetWorkflowData data must be in key=value format".to_string(),
803                        });
804                    };
805
806                    Ok(ActionType::SetWorkflowData { key, value })
807                }
808                _ => {
809                    let params = if args_str.is_empty() {
811                        HashMap::new()
812                    } else {
813                        self.parse_function_args_as_params(args_str)?
814                    };
815
816                    Ok(ActionType::Custom {
817                        action_type: function_name.to_string(),
818                        params,
819                    })
820                }
821            }
822        } else {
823            Ok(ActionType::Custom {
825                action_type: "statement".to_string(),
826                params: {
827                    let mut params = HashMap::new();
828                    params.insert("statement".to_string(), Value::String(trimmed.to_string()));
829                    params
830                },
831            })
832        }
833    }
834
835    fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
836        if args_str.trim().is_empty() {
837            return Ok(Vec::new());
838        }
839
840        let mut args = Vec::new();
842        let parts: Vec<&str> = args_str.split(',').collect();
843
844        for part in parts {
845            let trimmed = part.trim();
846
847            if trimmed.contains('+')
849                || trimmed.contains('-')
850                || trimmed.contains('*')
851                || trimmed.contains('/')
852            {
853                args.push(Value::String(trimmed.to_string()));
855            } else {
856                args.push(self.parse_value(trimmed)?);
857            }
858        }
859
860        Ok(args)
861    }
862
863    fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
865        let mut params = HashMap::new();
866
867        if args_str.trim().is_empty() {
868            return Ok(params);
869        }
870
871        let parts: Vec<&str> = args_str.split(',').collect();
873        for (i, part) in parts.iter().enumerate() {
874            let trimmed = part.trim();
875            let value = self.parse_value(trimmed)?;
876
877            params.insert(i.to_string(), value);
879        }
880
881        Ok(params)
882    }
883}
884
885#[cfg(test)]
886mod tests {
887    use super::GRLParser;
888
889    #[test]
890    fn test_parse_simple_rule() {
891        let grl = r#"
892        rule "CheckAge" salience 10 {
893            when
894                User.Age >= 18
895            then
896                log("User is adult");
897        }
898        "#;
899
900        let rules = GRLParser::parse_rules(grl).unwrap();
901        assert_eq!(rules.len(), 1);
902        let rule = &rules[0];
903        assert_eq!(rule.name, "CheckAge");
904        assert_eq!(rule.salience, 10);
905        assert_eq!(rule.actions.len(), 1);
906    }
907
908    #[test]
909    fn test_parse_complex_condition() {
910        let grl = r#"
911        rule "ComplexRule" {
912            when
913                User.Age >= 18 && User.Country == "US"
914            then
915                User.Qualified = true;
916        }
917        "#;
918
919        let rules = GRLParser::parse_rules(grl).unwrap();
920        assert_eq!(rules.len(), 1);
921        let rule = &rules[0];
922        assert_eq!(rule.name, "ComplexRule");
923    }
924
925    #[test]
926    fn test_parse_new_syntax_with_parentheses() {
927        let grl = r#"
928        rule "Default Rule" salience 10 {
929            when
930                (user.age >= 18)
931            then
932                set(user.status, "approved");
933        }
934        "#;
935
936        let rules = GRLParser::parse_rules(grl).unwrap();
937        assert_eq!(rules.len(), 1);
938        let rule = &rules[0];
939        assert_eq!(rule.name, "Default Rule");
940        assert_eq!(rule.salience, 10);
941        assert_eq!(rule.actions.len(), 1);
942
943        match &rule.actions[0] {
945            crate::types::ActionType::Custom {
946                action_type,
947                params,
948            } => {
949                assert_eq!(action_type, "set");
950                assert_eq!(
951                    params.get("0"),
952                    Some(&crate::types::Value::String("user.status".to_string()))
953                );
954                assert_eq!(
955                    params.get("1"),
956                    Some(&crate::types::Value::String("approved".to_string()))
957                );
958            }
959            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
960        }
961    }
962
963    #[test]
964    fn test_parse_complex_nested_conditions() {
965        let grl = r#"
966        rule "Complex Business Rule" salience 10 {
967            when
968                (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
969            then
970                apply_discount(20000);
971        }
972        "#;
973
974        let rules = GRLParser::parse_rules(grl).unwrap();
975        assert_eq!(rules.len(), 1);
976        let rule = &rules[0];
977        assert_eq!(rule.name, "Complex Business Rule");
978        assert_eq!(rule.salience, 10);
979        assert_eq!(rule.actions.len(), 1);
980
981        match &rule.actions[0] {
983            crate::types::ActionType::Custom {
984                action_type,
985                params,
986            } => {
987                assert_eq!(action_type, "apply_discount");
988                assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
989            }
990            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
991        }
992    }
993
994    #[test]
995    fn test_parse_no_loop_attribute() {
996        let grl = r#"
997        rule "NoLoopRule" no-loop salience 15 {
998            when
999                User.Score < 100
1000            then
1001                set(User.Score, User.Score + 10);
1002        }
1003        "#;
1004
1005        let rules = GRLParser::parse_rules(grl).unwrap();
1006        assert_eq!(rules.len(), 1);
1007        let rule = &rules[0];
1008        assert_eq!(rule.name, "NoLoopRule");
1009        assert_eq!(rule.salience, 15);
1010        assert!(rule.no_loop, "Rule should have no-loop=true");
1011    }
1012
1013    #[test]
1014    fn test_parse_no_loop_different_positions() {
1015        let grl1 = r#"
1017        rule "Rule1" no-loop salience 10 {
1018            when User.Age >= 18
1019            then log("adult");
1020        }
1021        "#;
1022
1023        let grl2 = r#"
1025        rule "Rule2" salience 10 no-loop {
1026            when User.Age >= 18
1027            then log("adult");
1028        }
1029        "#;
1030
1031        let rules1 = GRLParser::parse_rules(grl1).unwrap();
1032        let rules2 = GRLParser::parse_rules(grl2).unwrap();
1033
1034        assert_eq!(rules1.len(), 1);
1035        assert_eq!(rules2.len(), 1);
1036
1037        assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
1038        assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
1039
1040        assert_eq!(rules1[0].salience, 10);
1041        assert_eq!(rules2[0].salience, 10);
1042    }
1043
1044    #[test]
1045    fn test_parse_without_no_loop() {
1046        let grl = r#"
1047        rule "RegularRule" salience 5 {
1048            when
1049                User.Active == true
1050            then
1051                log("active user");
1052        }
1053        "#;
1054
1055        let rules = GRLParser::parse_rules(grl).unwrap();
1056        assert_eq!(rules.len(), 1);
1057        let rule = &rules[0];
1058        assert_eq!(rule.name, "RegularRule");
1059        assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1060    }
1061
1062    #[test]
1063    fn test_parse_exists_pattern() {
1064        let grl = r#"
1065        rule "ExistsRule" salience 20 {
1066            when
1067                exists(Customer.tier == "VIP")
1068            then
1069                System.premiumActive = true;
1070        }
1071        "#;
1072
1073        let rules = GRLParser::parse_rules(grl).unwrap();
1074        assert_eq!(rules.len(), 1);
1075        let rule = &rules[0];
1076        assert_eq!(rule.name, "ExistsRule");
1077        assert_eq!(rule.salience, 20);
1078
1079        match &rule.conditions {
1081            crate::engine::rule::ConditionGroup::Exists(_) => {
1082                }
1084            _ => panic!(
1085                "Expected EXISTS condition group, got: {:?}",
1086                rule.conditions
1087            ),
1088        }
1089    }
1090
1091    #[test]
1092    fn test_parse_forall_pattern() {
1093        let grl = r#"
1094        rule "ForallRule" salience 15 {
1095            when
1096                forall(Order.status == "processed")
1097            then
1098                Shipping.enabled = true;
1099        }
1100        "#;
1101
1102        let rules = GRLParser::parse_rules(grl).unwrap();
1103        assert_eq!(rules.len(), 1);
1104        let rule = &rules[0];
1105        assert_eq!(rule.name, "ForallRule");
1106
1107        match &rule.conditions {
1109            crate::engine::rule::ConditionGroup::Forall(_) => {
1110                }
1112            _ => panic!(
1113                "Expected FORALL condition group, got: {:?}",
1114                rule.conditions
1115            ),
1116        }
1117    }
1118
1119    #[test]
1120    fn test_parse_combined_patterns() {
1121        let grl = r#"
1122        rule "CombinedRule" salience 25 {
1123            when
1124                exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1125            then
1126                System.vipMode = true;
1127        }
1128        "#;
1129
1130        let rules = GRLParser::parse_rules(grl).unwrap();
1131        assert_eq!(rules.len(), 1);
1132        let rule = &rules[0];
1133        assert_eq!(rule.name, "CombinedRule");
1134
1135        match &rule.conditions {
1137            crate::engine::rule::ConditionGroup::Compound {
1138                left,
1139                operator,
1140                right,
1141            } => {
1142                assert_eq!(*operator, crate::types::LogicalOperator::And);
1143
1144                match left.as_ref() {
1146                    crate::engine::rule::ConditionGroup::Exists(_) => {
1147                        }
1149                    _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1150                }
1151
1152                match right.as_ref() {
1154                    crate::engine::rule::ConditionGroup::Not(inner) => {
1155                        match inner.as_ref() {
1156                            crate::engine::rule::ConditionGroup::Exists(_) => {
1157                                }
1159                            _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1160                        }
1161                    }
1162                    _ => panic!("Expected NOT in right side, got: {:?}", right),
1163                }
1164            }
1165            _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1166        }
1167    }
1168}