szal 1.2.0

Workflow engine — step/flow execution with branching, retry, rollback, and parallel stages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! Lightweight condition expression evaluator for workflow step conditions.
//!
//! Evaluates predicate expressions against a JSON context built from step results.
//!
//! ## Grammar
//!
//! ```text
//! expr     = or_expr
//! or_expr  = and_expr ("||" and_expr)*
//! and_expr = cmp_expr ("&&" cmp_expr)*
//! cmp_expr = value (("==" | "!=" | ">" | ">=" | "<" | "<=") value)?
//! value    = "!" value | path | string_lit | number_lit | bool_lit | "(" expr ")"
//! path     = ident ("." ident)*
//! ident    = [a-zA-Z_][a-zA-Z0-9_-]*
//! string_lit = "'" [^']* "'"
//! number_lit = [0-9]+ ("." [0-9]+)?
//! bool_lit = "true" | "false"
//! ```
//!
//! ## Example
//!
//! ```
//! use szal::condition::evaluate;
//! use serde_json::json;
//!
//! let ctx = json!({
//!     "steps": {
//!         "build": { "status": "completed" }
//!     }
//! });
//!
//! assert!(evaluate("steps.build.status == 'completed'", &ctx).unwrap());
//! assert!(!evaluate("steps.build.status == 'failed'", &ctx).unwrap());
//! ```

use serde_json::Value;

// ---------------------------------------------------------------------------
// Tokens
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
enum Token {
    Path(String),
    StringLit(String),
    NumberLit(f64),
    BoolLit(bool),
    Eq,
    NotEq,
    Gt,
    Gte,
    Lt,
    Lte,
    Not,
    And,
    Or,
    LParen,
    RParen,
}

// ---------------------------------------------------------------------------
// Tokenizer
// ---------------------------------------------------------------------------

fn tokenize(input: &str) -> Result<Vec<Token>, String> {
    let mut tokens = Vec::new();
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        let b = bytes[i];

        // Skip whitespace
        if b.is_ascii_whitespace() {
            i += 1;
            continue;
        }

        // Two-char operators
        if i + 1 < len {
            match (b, bytes[i + 1]) {
                (b'=', b'=') => {
                    tokens.push(Token::Eq);
                    i += 2;
                    continue;
                }
                (b'!', b'=') => {
                    tokens.push(Token::NotEq);
                    i += 2;
                    continue;
                }
                (b'>', b'=') => {
                    tokens.push(Token::Gte);
                    i += 2;
                    continue;
                }
                (b'<', b'=') => {
                    tokens.push(Token::Lte);
                    i += 2;
                    continue;
                }
                (b'&', b'&') => {
                    tokens.push(Token::And);
                    i += 2;
                    continue;
                }
                (b'|', b'|') => {
                    tokens.push(Token::Or);
                    i += 2;
                    continue;
                }
                _ => {}
            }
        }

        // Single-char operators: >, <, !
        if b == b'>' {
            tokens.push(Token::Gt);
            i += 1;
            continue;
        }
        if b == b'<' {
            tokens.push(Token::Lt);
            i += 1;
            continue;
        }
        if b == b'!' {
            tokens.push(Token::Not);
            i += 1;
            continue;
        }

        // Parentheses
        if b == b'(' {
            tokens.push(Token::LParen);
            i += 1;
            continue;
        }
        if b == b')' {
            tokens.push(Token::RParen);
            i += 1;
            continue;
        }

        // String literal (single-quoted)
        if b == b'\'' {
            i += 1;
            let start = i;
            while i < len && bytes[i] != b'\'' {
                i += 1;
            }
            if i >= len {
                return Err("unterminated string literal".into());
            }
            let s = &input[start..i];
            tokens.push(Token::StringLit(s.to_owned()));
            i += 1; // skip closing quote
            continue;
        }

        // Number literal
        if b.is_ascii_digit() {
            let start = i;
            while i < len && bytes[i].is_ascii_digit() {
                i += 1;
            }
            if i < len && bytes[i] == b'.' && i + 1 < len && bytes[i + 1].is_ascii_digit() {
                i += 1; // skip dot
                while i < len && bytes[i].is_ascii_digit() {
                    i += 1;
                }
            }
            let num_str = &input[start..i];
            let val: f64 = num_str
                .parse()
                .map_err(|e| format!("invalid number '{num_str}': {e}"))?;
            tokens.push(Token::NumberLit(val));
            continue;
        }

        // Identifier / path / bool literal
        if b.is_ascii_alphabetic() || b == b'_' {
            let start = i;
            while i < len
                && (bytes[i].is_ascii_alphanumeric()
                    || bytes[i] == b'_'
                    || bytes[i] == b'-'
                    || bytes[i] == b'.')
            {
                i += 1;
            }
            let word = &input[start..i];
            match word {
                "true" => tokens.push(Token::BoolLit(true)),
                "false" => tokens.push(Token::BoolLit(false)),
                _ => tokens.push(Token::Path(word.to_owned())),
            }
            continue;
        }

        // Safe conversion for error message — byte is not valid ASCII identifier
        let ch = if b.is_ascii() {
            b as char
        } else {
            return Err(format!("unexpected byte 0x{b:02x}"));
        };
        return Err(format!("unexpected character '{ch}'"));
    }

    Ok(tokens)
}

// ---------------------------------------------------------------------------
// AST
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
enum Expr {
    Literal(Value),
    Path(String),
    Eq(Box<Expr>, Box<Expr>),
    NotEq(Box<Expr>, Box<Expr>),
    Gt(Box<Expr>, Box<Expr>),
    Gte(Box<Expr>, Box<Expr>),
    Lt(Box<Expr>, Box<Expr>),
    Lte(Box<Expr>, Box<Expr>),
    Not(Box<Expr>),
    And(Box<Expr>, Box<Expr>),
    Or(Box<Expr>, Box<Expr>),
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

struct Parser {
    tokens: Vec<Token>,
    pos: usize,
}

impl Parser {
    fn new(tokens: Vec<Token>) -> Self {
        Self { tokens, pos: 0 }
    }

    fn peek(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<Token> {
        if self.pos < self.tokens.len() {
            let tok = self.tokens[self.pos].clone();
            self.pos += 1;
            Some(tok)
        } else {
            None
        }
    }

    fn parse_expr(&mut self) -> Result<Expr, String> {
        self.parse_or()
    }

    fn parse_or(&mut self) -> Result<Expr, String> {
        let mut left = self.parse_and()?;
        while self.peek() == Some(&Token::Or) {
            self.advance();
            let right = self.parse_and()?;
            left = Expr::Or(Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    fn parse_and(&mut self) -> Result<Expr, String> {
        let mut left = self.parse_cmp()?;
        while self.peek() == Some(&Token::And) {
            self.advance();
            let right = self.parse_cmp()?;
            left = Expr::And(Box::new(left), Box::new(right));
        }
        Ok(left)
    }

    fn parse_cmp(&mut self) -> Result<Expr, String> {
        let left = self.parse_value()?;
        match self.peek() {
            Some(Token::Eq) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::Eq(Box::new(left), Box::new(right)))
            }
            Some(Token::NotEq) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::NotEq(Box::new(left), Box::new(right)))
            }
            Some(Token::Gt) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::Gt(Box::new(left), Box::new(right)))
            }
            Some(Token::Gte) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::Gte(Box::new(left), Box::new(right)))
            }
            Some(Token::Lt) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::Lt(Box::new(left), Box::new(right)))
            }
            Some(Token::Lte) => {
                self.advance();
                let right = self.parse_value()?;
                Ok(Expr::Lte(Box::new(left), Box::new(right)))
            }
            _ => Ok(left),
        }
    }

    fn parse_value(&mut self) -> Result<Expr, String> {
        // Prefix `!` (not)
        if self.peek() == Some(&Token::Not) {
            self.advance();
            let inner = self.parse_value()?;
            return Ok(Expr::Not(Box::new(inner)));
        }
        match self.peek().cloned() {
            Some(Token::StringLit(s)) => {
                self.advance();
                Ok(Expr::Literal(Value::String(s)))
            }
            Some(Token::NumberLit(n)) => {
                self.advance();
                Ok(Expr::Literal(
                    serde_json::Number::from_f64(n)
                        .map(Value::Number)
                        .unwrap_or(Value::Null),
                ))
            }
            Some(Token::BoolLit(b)) => {
                self.advance();
                Ok(Expr::Literal(Value::Bool(b)))
            }
            Some(Token::Path(p)) => {
                self.advance();
                Ok(Expr::Path(p))
            }
            Some(Token::LParen) => {
                self.advance();
                let expr = self.parse_expr()?;
                match self.advance() {
                    Some(Token::RParen) => Ok(expr),
                    _ => Err("expected ')'".into()),
                }
            }
            Some(tok) => Err(format!("unexpected token: {tok:?}")),
            None => Err("unexpected end of expression".into()),
        }
    }
}

// ---------------------------------------------------------------------------
// Evaluation
// ---------------------------------------------------------------------------

/// Resolve a dot-notation path against a JSON value.
///
/// Walks the JSON tree segment by segment. Returns `&Value::Null` if any
/// segment is missing.
///
/// ```
/// use serde_json::json;
/// use szal::condition::resolve_path;
///
/// let ctx = json!({"steps": {"build": {"output": {"url": "https://example.com"}}}});
/// assert_eq!(resolve_path("steps.build.output.url", &ctx), "https://example.com");
/// assert!(resolve_path("steps.missing.field", &ctx).is_null());
/// ```
#[inline]
#[must_use]
pub fn resolve_path<'a>(path: &str, context: &'a Value) -> &'a Value {
    let mut current = context;
    for segment in path.split('.') {
        match current.get(segment) {
            Some(v) => current = v,
            None => return &Value::Null,
        }
    }
    current
}

fn eval_expr(expr: &Expr, context: &Value) -> Result<Value, String> {
    match expr {
        Expr::Literal(v) => Ok(v.clone()),
        Expr::Path(p) => Ok(resolve_path(p, context).clone()),
        Expr::Eq(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(values_equal(&l, &r)))
        }
        Expr::NotEq(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(!values_equal(&l, &r)))
        }
        Expr::Gt(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(
                values_compare(&l, &r) == Some(std::cmp::Ordering::Greater),
            ))
        }
        Expr::Gte(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(matches!(
                values_compare(&l, &r),
                Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)
            )))
        }
        Expr::Lt(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(
                values_compare(&l, &r) == Some(std::cmp::Ordering::Less),
            ))
        }
        Expr::Lte(left, right) => {
            let l = eval_expr(left, context)?;
            let r = eval_expr(right, context)?;
            Ok(Value::Bool(matches!(
                values_compare(&l, &r),
                Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
            )))
        }
        Expr::Not(inner) => {
            let v = eval_expr(inner, context)?;
            Ok(Value::Bool(!is_truthy(&v)))
        }
        Expr::And(left, right) => {
            if !is_truthy(&eval_expr(left, context)?) {
                return Ok(Value::Bool(false));
            }
            Ok(Value::Bool(is_truthy(&eval_expr(right, context)?)))
        }
        Expr::Or(left, right) => {
            if is_truthy(&eval_expr(left, context)?) {
                return Ok(Value::Bool(true));
            }
            Ok(Value::Bool(is_truthy(&eval_expr(right, context)?)))
        }
    }
}

/// Compare two JSON values for equality.
///
/// Same-type comparisons use structural equality.
/// Cross-type comparisons always return false.
#[inline]
#[must_use]
fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::String(a), Value::String(b)) => a == b,
        (Value::Number(a), Value::Number(b)) => a == b,
        (Value::Bool(a), Value::Bool(b)) => a == b,
        (Value::Null, Value::Null) => true,
        _ => false,
    }
}

/// Compare two JSON values for ordering.
///
/// Numbers are compared numerically. Strings are compared lexicographically.
/// Cross-type or non-orderable comparisons return `None`.
#[inline]
#[must_use]
fn values_compare(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
    match (a, b) {
        (Value::Number(a), Value::Number(b)) => {
            let af = a.as_f64()?;
            let bf = b.as_f64()?;
            af.partial_cmp(&bf)
        }
        (Value::String(a), Value::String(b)) => Some(a.cmp(b)),
        _ => None,
    }
}

/// Determine the truthiness of a JSON value.
#[inline]
#[must_use]
fn is_truthy(v: &Value) -> bool {
    match v {
        Value::Bool(b) => *b,
        Value::Null => false,
        Value::String(s) => !s.is_empty(),
        Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
        Value::Array(a) => !a.is_empty(),
        Value::Object(o) => !o.is_empty(),
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Evaluate a condition expression against a JSON context.
///
/// Returns `Ok(true)` if the condition passes, `Ok(false)` if it does not,
/// or `Err` if the expression is malformed.
///
/// An empty expression is vacuously true.
///
/// # Examples
///
/// ```
/// use szal::condition::evaluate;
/// use serde_json::json;
///
/// let ctx = json!({"status": "ok"});
/// assert!(evaluate("status == 'ok'", &ctx).unwrap());
/// assert!(evaluate("", &ctx).unwrap());
/// ```
pub fn evaluate(expr: &str, context: &Value) -> Result<bool, String> {
    CompiledCondition::compile(expr)?.evaluate(context)
}

// ---------------------------------------------------------------------------
// Compilation + caching
// ---------------------------------------------------------------------------

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// A pre-compiled condition expression.
///
/// Tokenizing and parsing a condition string into an AST is the expensive part
/// of evaluation; once compiled, a `CompiledCondition` evaluates against many
/// contexts without re-parsing. Use [`ConditionCache`] to memoize compilation
/// across repeated runs of the same flow.
///
/// ```
/// use szal::condition::CompiledCondition;
/// use serde_json::json;
///
/// let cond = CompiledCondition::compile("status == 'ok'").unwrap();
/// assert!(cond.evaluate(&json!({"status": "ok"})).unwrap());
/// assert!(!cond.evaluate(&json!({"status": "bad"})).unwrap());
/// ```
#[derive(Debug, Clone)]
pub struct CompiledCondition {
    source: String,
    ast: Expr,
}

impl CompiledCondition {
    /// Compile a condition expression into a reusable AST.
    ///
    /// An empty (or whitespace-only) expression compiles to a vacuously-true
    /// condition. Returns `Err` if the expression is malformed.
    pub fn compile(expr: &str) -> Result<Self, String> {
        let trimmed = expr.trim();
        if trimmed.is_empty() {
            return Ok(Self {
                source: String::new(),
                ast: Expr::Literal(Value::Bool(true)),
            });
        }

        let tokens = tokenize(trimmed)?;
        let mut parser = Parser::new(tokens);
        let ast = parser.parse_expr()?;

        if parser.pos < parser.tokens.len() {
            return Err(format!(
                "unexpected trailing token: {:?}",
                parser.tokens[parser.pos]
            ));
        }

        Ok(Self {
            source: trimmed.to_owned(),
            ast,
        })
    }

    /// Evaluate the compiled condition against a JSON context.
    #[inline]
    pub fn evaluate(&self, context: &Value) -> Result<bool, String> {
        Ok(is_truthy(&eval_expr(&self.ast, context)?))
    }

    /// The original (trimmed) source expression.
    #[inline]
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }
}

/// A thread-safe cache of compiled conditions, keyed by source expression.
///
/// Memoizes the parse step so repeated evaluation of the same condition string
/// — e.g. across many runs of the same flow on a reused [`Engine`](crate::engine::Engine)
/// — parses only once. Both successful compilations and parse errors are cached,
/// so a malformed expression is not re-parsed on every encounter.
///
/// ```
/// use szal::condition::ConditionCache;
/// use serde_json::json;
///
/// let cache = ConditionCache::new();
/// assert!(cache.evaluate("n > 5", &json!({"n": 10})).unwrap());
/// assert!(!cache.evaluate("n > 5", &json!({"n": 3})).unwrap());
/// assert_eq!(cache.len(), 1); // compiled once, evaluated twice
/// ```
#[derive(Debug, Default)]
pub struct ConditionCache {
    entries: RwLock<HashMap<String, Arc<Result<CompiledCondition, String>>>>,
}

impl ConditionCache {
    /// Create an empty cache.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Evaluate `expr` against `context`, compiling and caching on first use.
    pub fn evaluate(&self, expr: &str, context: &Value) -> Result<bool, String> {
        match &*self.compiled(expr) {
            Ok(c) => c.evaluate(context),
            Err(e) => Err(e.clone()),
        }
    }

    /// Get (or compile and cache) the compiled form of `expr`.
    fn compiled(&self, expr: &str) -> Arc<Result<CompiledCondition, String>> {
        if let Some(hit) = self
            .entries
            .read()
            .expect("condition cache poisoned")
            .get(expr)
        {
            return hit.clone();
        }
        let compiled = Arc::new(CompiledCondition::compile(expr));
        self.entries
            .write()
            .expect("condition cache poisoned")
            .entry(expr.to_owned())
            .or_insert_with(|| compiled.clone())
            .clone()
    }

    /// Number of distinct expressions cached.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.read().expect("condition cache poisoned").len()
    }

    /// Whether the cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Render a template string by resolving `{{path}}` placeholders against a JSON context.
///
/// Supports dot-notation paths: `{{steps.build.output.url}}` walks into nested JSON.
/// Missing paths resolve to empty string. Non-string values are JSON-serialized.
///
/// ```
/// use serde_json::json;
/// use szal::condition::render_template;
///
/// let ctx = json!({"name": "Alice", "meta": {"role": "admin"}});
/// assert_eq!(render_template("Hello {{name}}, role={{meta.role}}", &ctx), "Hello Alice, role=admin");
/// ```
#[must_use]
pub fn render_template(template: &str, context: &Value) -> String {
    let mut result = String::with_capacity(template.len());
    let bytes = template.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if i + 1 < len && bytes[i] == b'{' && bytes[i + 1] == b'{' {
            // Find closing }}
            if let Some(end) = template[i + 2..].find("}}") {
                let path = template[i + 2..i + 2 + end].trim();
                let resolved = resolve_path(path, context);
                match resolved {
                    Value::Null => {} // missing path → empty
                    Value::String(s) => result.push_str(s),
                    other => {
                        use std::fmt::Write;
                        let _ = write!(result, "{other}");
                    }
                }
                i += 2 + end + 2; // skip past }}
                continue;
            }
        }
        // Safe: we only branch on ASCII bytes above, so this is a valid char boundary
        // for non-ASCII bytes, they fall through and we need to advance by char width
        if bytes[i].is_ascii() {
            result.push(bytes[i] as char);
            i += 1;
        } else {
            // Multi-byte UTF-8: find the char at this byte offset
            let ch = template[i..].chars().next().unwrap();
            result.push(ch);
            i += ch.len_utf8();
        }
    }

    result
}

/// Build a step result context for condition evaluation.
///
/// Creates a JSON object:
/// ```json
/// {
///   "steps": {
///     "<step_name>": {
///       "status": "<completed|failed|skipped>",
///       "output": <step output value>,
///       "error": <error string or null>
///     }
///   }
/// }
/// ```
///
/// Maps `step_id` from each [`StepResult`](crate::step::StepResult) back to the
/// step name via the [`StepDef`](crate::step::StepDef) slice.
#[must_use]
pub fn build_step_context(
    results: &[crate::step::StepResult],
    steps: &[crate::step::StepDef],
) -> Value {
    use serde_json::json;
    use std::collections::HashMap;

    let id_to_name: HashMap<_, _> = steps.iter().map(|s| (s.id, s.name.as_str())).collect();

    let mut step_map = serde_json::Map::new();

    for result in results {
        let name = match id_to_name.get(&result.step_id) {
            Some(n) => *n,
            None => {
                tracing::warn!(
                    step_id = %result.step_id,
                    "step result references unknown step id, skipping"
                );
                continue;
            }
        };

        let entry = json!({
            "status": result.status.to_string(),
            "output": result.output,
            "error": result.error,
        });

        step_map.insert(name.to_owned(), entry);
    }

    json!({ "steps": step_map })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Path resolution --

    #[test]
    fn path_resolution() {
        let ctx = json!({
            "steps": {
                "build": {
                    "status": "completed"
                }
            }
        });
        assert!(evaluate("steps.build.status == 'completed'", &ctx).unwrap());
    }

    #[test]
    fn missing_path_returns_null() {
        let ctx = json!({});
        // null != 'completed' so comparison is false
        assert!(!evaluate("steps.build.status == 'completed'", &ctx).unwrap());
        // bare missing path is null → falsy
        assert!(!evaluate("steps.build.status", &ctx).unwrap());
    }

    // -- Literal comparisons --

    #[test]
    fn string_comparison() {
        let ctx = json!({});
        assert!(evaluate("'completed' == 'completed'", &ctx).unwrap());
        assert!(!evaluate("'completed' == 'failed'", &ctx).unwrap());
    }

    #[test]
    fn number_comparison() {
        let ctx = json!({});
        assert!(evaluate("42 == 42", &ctx).unwrap());
        assert!(!evaluate("42 == 43", &ctx).unwrap());
    }

    #[test]
    fn float_number_comparison() {
        let ctx = json!({});
        assert!(evaluate("3.14 == 3.14", &ctx).unwrap());
        assert!(!evaluate("3.14 == 3.15", &ctx).unwrap());
    }

    #[test]
    fn boolean_literals() {
        let ctx = json!({});
        assert!(evaluate("true", &ctx).unwrap());
        assert!(!evaluate("false", &ctx).unwrap());
    }

    // -- Logical operators --

    #[test]
    fn and_operator() {
        let ctx = json!({});
        assert!(evaluate("true && true", &ctx).unwrap());
        assert!(!evaluate("true && false", &ctx).unwrap());
        assert!(!evaluate("false && true", &ctx).unwrap());
        assert!(!evaluate("false && false", &ctx).unwrap());
    }

    #[test]
    fn or_operator() {
        let ctx = json!({});
        assert!(evaluate("true || true", &ctx).unwrap());
        assert!(evaluate("true || false", &ctx).unwrap());
        assert!(evaluate("false || true", &ctx).unwrap());
        assert!(!evaluate("false || false", &ctx).unwrap());
    }

    #[test]
    fn not_equal() {
        let ctx = json!({});
        assert!(evaluate("'a' != 'b'", &ctx).unwrap());
        assert!(!evaluate("'a' != 'a'", &ctx).unwrap());
    }

    // -- Parentheses --

    #[test]
    fn parentheses() {
        let ctx = json!({});
        assert!(evaluate("(true || false) && true", &ctx).unwrap());
        assert!(!evaluate("(true || false) && false", &ctx).unwrap());
        assert!(evaluate("true || (false && false)", &ctx).unwrap());
    }

    // -- Complex expressions --

    #[test]
    fn complex_step_conditions() {
        let ctx = json!({
            "steps": {
                "build": { "status": "completed" },
                "test": { "status": "completed" }
            }
        });
        assert!(
            evaluate(
                "steps.build.status == 'completed' && steps.test.status == 'completed'",
                &ctx,
            )
            .unwrap()
        );

        let ctx_fail = json!({
            "steps": {
                "build": { "status": "completed" },
                "test": { "status": "failed" }
            }
        });
        assert!(
            !evaluate(
                "steps.build.status == 'completed' && steps.test.status == 'completed'",
                &ctx_fail,
            )
            .unwrap()
        );
    }

    #[test]
    fn missing_step() {
        let ctx = json!({
            "steps": {
                "build": { "status": "completed" }
            }
        });
        assert!(!evaluate("steps.missing.status == 'completed'", &ctx).unwrap());
    }

    // -- Error cases --

    #[test]
    fn malformed_expression() {
        let ctx = json!({});
        assert!(evaluate("== 'foo'", &ctx).is_err());
    }

    #[test]
    fn unterminated_string() {
        let ctx = json!({});
        assert!(evaluate("'unterminated", &ctx).is_err());
    }

    #[test]
    fn unmatched_paren() {
        let ctx = json!({});
        assert!(evaluate("(true", &ctx).is_err());
    }

    #[test]
    fn empty_expression_is_true() {
        let ctx = json!({});
        assert!(evaluate("", &ctx).unwrap());
        assert!(evaluate("   ", &ctx).unwrap());
    }

    // -- Cross-type comparison --

    #[test]
    fn cross_type_comparison_is_false() {
        let ctx = json!({});
        assert!(!evaluate("42 == 'forty-two'", &ctx).unwrap());
        assert!(!evaluate("true == 'true'", &ctx).unwrap());
        assert!(!evaluate("true == 1", &ctx).unwrap());
    }

    // -- Null equality --

    #[test]
    fn null_equals_null() {
        let ctx = json!({});
        // Two missing paths both resolve to null — they should be equal
        assert!(evaluate("missing.a == missing.b", &ctx).unwrap());
    }

    // -- build_step_context --

    #[test]
    fn build_context_structure() {
        use crate::step::{StepDef, StepResult, StepStatus};

        let build = StepDef::new("build");
        let test = StepDef::new("test");
        let steps = vec![build.clone(), test.clone()];

        let results = vec![
            StepResult {
                step_id: build.id,
                status: StepStatus::Completed,
                output: json!({"artifact": "build.tar.gz"}),
                duration_ms: 1200,
                attempts: 1,
                error: None,
            },
            StepResult {
                step_id: test.id,
                status: StepStatus::Failed,
                output: json!(null),
                duration_ms: 500,
                attempts: 2,
                error: Some("assertion failed".into()),
            },
        ];

        let ctx = build_step_context(&results, &steps);

        // Verify structure
        assert_eq!(ctx["steps"]["build"]["status"], "completed");
        assert_eq!(ctx["steps"]["build"]["output"]["artifact"], "build.tar.gz");
        assert!(ctx["steps"]["build"]["error"].is_null());

        assert_eq!(ctx["steps"]["test"]["status"], "failed");
        assert_eq!(ctx["steps"]["test"]["error"], "assertion failed");

        // Use with evaluate
        assert!(evaluate("steps.build.status == 'completed'", &ctx).unwrap());
        assert!(!evaluate("steps.test.status == 'completed'", &ctx).unwrap());
        assert!(evaluate("steps.test.status == 'failed'", &ctx).unwrap());
    }

    #[test]
    fn build_context_skips_unknown_step_ids() {
        use crate::step::{StepDef, StepResult, StepStatus};
        use uuid::Uuid;

        let build = StepDef::new("build");
        let steps = vec![build.clone()];

        let results = vec![
            StepResult {
                step_id: build.id,
                status: StepStatus::Completed,
                output: json!(null),
                duration_ms: 100,
                attempts: 1,
                error: None,
            },
            StepResult {
                step_id: Uuid::new_v4(), // unknown
                status: StepStatus::Failed,
                output: json!(null),
                duration_ms: 0,
                attempts: 1,
                error: Some("orphan".into()),
            },
        ];

        let ctx = build_step_context(&results, &steps);
        // Only the known step should appear
        assert_eq!(ctx["steps"]["build"]["status"], "completed");
        assert!(ctx["steps"].as_object().unwrap().len() == 1);
    }

    // -- Operator precedence --

    #[test]
    fn and_binds_tighter_than_or() {
        let ctx = json!({});
        // false || true && true  →  false || (true && true) → true
        assert!(evaluate("false || true && true", &ctx).unwrap());
        // true || true && false  →  true || (true && false) → true
        assert!(evaluate("true || true && false", &ctx).unwrap());
        // false || false && true →  false || (false && true) → false
        assert!(!evaluate("false || false && true", &ctx).unwrap());
    }

    // -- Trailing token error --

    #[test]
    fn trailing_tokens_are_error() {
        let ctx = json!({});
        assert!(evaluate("true true", &ctx).is_err());
    }

    // -- Short-circuit evaluation --

    #[test]
    fn and_short_circuits_on_false() {
        let ctx = json!({});
        // false && <anything> should return false without evaluating the right side
        // Here, the right side resolves to null (falsy) — but the result should be
        // false regardless, because the left side is false.
        assert!(!evaluate("false && missing.path", &ctx).unwrap());
    }

    #[test]
    fn or_short_circuits_on_true() {
        let ctx = json!({});
        // true || <anything> should return true without evaluating the right side
        assert!(evaluate("true || missing.path", &ctx).unwrap());
    }

    // -- String literals with non-ASCII content --

    #[test]
    fn string_literal_with_unicode() {
        let ctx = json!({"greeting": "héllo"});
        assert!(evaluate("greeting == 'héllo'", &ctx).unwrap());
        assert!(!evaluate("greeting == 'hello'", &ctx).unwrap());
    }

    #[test]
    fn render_template_with_unicode() {
        let ctx = json!({"name": "André"});
        assert_eq!(render_template("Hello {{name}}!", &ctx), "Hello André!");
    }

    #[test]
    fn render_template_with_unicode_literal_text() {
        let ctx = json!({"x": "y"});
        assert_eq!(render_template("café {{x}}", &ctx), "café y");
    }

    // -- Comparison operators --

    #[test]
    fn greater_than() {
        let ctx = json!({});
        assert!(evaluate("10 > 5", &ctx).unwrap());
        assert!(!evaluate("5 > 10", &ctx).unwrap());
        assert!(!evaluate("5 > 5", &ctx).unwrap());
    }

    #[test]
    fn greater_than_or_equal() {
        let ctx = json!({});
        assert!(evaluate("10 >= 5", &ctx).unwrap());
        assert!(evaluate("5 >= 5", &ctx).unwrap());
        assert!(!evaluate("4 >= 5", &ctx).unwrap());
    }

    #[test]
    fn less_than() {
        let ctx = json!({});
        assert!(evaluate("5 < 10", &ctx).unwrap());
        assert!(!evaluate("10 < 5", &ctx).unwrap());
        assert!(!evaluate("5 < 5", &ctx).unwrap());
    }

    #[test]
    fn less_than_or_equal() {
        let ctx = json!({});
        assert!(evaluate("5 <= 10", &ctx).unwrap());
        assert!(evaluate("5 <= 5", &ctx).unwrap());
        assert!(!evaluate("6 <= 5", &ctx).unwrap());
    }

    #[test]
    fn comparison_with_paths() {
        let ctx = json!({"a": 10, "b": 5});
        assert!(evaluate("a > b", &ctx).unwrap());
        assert!(!evaluate("b > a", &ctx).unwrap());
        assert!(evaluate("a >= 10", &ctx).unwrap());
        assert!(evaluate("b < a", &ctx).unwrap());
    }

    #[test]
    fn comparison_with_floats() {
        let ctx = json!({});
        assert!(evaluate("3.14 > 2.71", &ctx).unwrap());
        assert!(evaluate("2.71 < 3.14", &ctx).unwrap());
        assert!(evaluate("3.14 >= 3.14", &ctx).unwrap());
    }

    #[test]
    fn string_comparison_ordering() {
        let ctx = json!({});
        assert!(evaluate("'banana' > 'apple'", &ctx).unwrap());
        assert!(evaluate("'apple' < 'banana'", &ctx).unwrap());
        assert!(evaluate("'apple' <= 'apple'", &ctx).unwrap());
    }

    #[test]
    fn cross_type_comparison_returns_false() {
        let ctx = json!({});
        assert!(!evaluate("42 > 'hello'", &ctx).unwrap());
        assert!(!evaluate("'hello' < 42", &ctx).unwrap());
    }

    // -- Not operator --

    #[test]
    fn not_operator() {
        let ctx = json!({});
        assert!(!evaluate("!true", &ctx).unwrap());
        assert!(evaluate("!false", &ctx).unwrap());
    }

    #[test]
    fn not_with_path() {
        let ctx = json!({"enabled": false, "missing": null});
        assert!(evaluate("!enabled", &ctx).unwrap());
        assert!(evaluate("!missing", &ctx).unwrap());
    }

    #[test]
    fn not_with_comparison() {
        let ctx = json!({});
        assert!(evaluate("!(5 > 10)", &ctx).unwrap());
        assert!(!evaluate("!(10 > 5)", &ctx).unwrap());
    }

    #[test]
    fn double_not() {
        let ctx = json!({});
        assert!(evaluate("!!true", &ctx).unwrap());
        assert!(!evaluate("!!false", &ctx).unwrap());
    }

    #[test]
    fn not_in_compound_expression() {
        let ctx = json!({"status": "failed"});
        // ! binds tighter than ==, so use parens for negating a comparison
        assert!(evaluate("!(status == 'completed') && status == 'failed'", &ctx).unwrap());
        // Without parens: (!status) == 'completed' → false == 'completed' → false
        assert!(!evaluate("!status == 'completed'", &ctx).unwrap());
    }

    // -- Compiled conditions --

    #[test]
    fn compiled_condition_reuse() {
        let cond = CompiledCondition::compile("n > 5").unwrap();
        assert!(cond.evaluate(&json!({"n": 10})).unwrap());
        assert!(!cond.evaluate(&json!({"n": 3})).unwrap());
        assert_eq!(cond.source(), "n > 5");
    }

    #[test]
    fn compiled_empty_is_true() {
        let cond = CompiledCondition::compile("   ").unwrap();
        assert!(cond.evaluate(&json!({})).unwrap());
        assert_eq!(cond.source(), "");
    }

    #[test]
    fn compiled_malformed_errors() {
        assert!(CompiledCondition::compile("== 'x'").is_err());
        assert!(CompiledCondition::compile("true true").is_err());
        assert!(CompiledCondition::compile("'unterminated").is_err());
    }

    // -- Condition cache --

    #[test]
    fn cache_memoizes_compilation() {
        let cache = ConditionCache::new();
        assert!(cache.is_empty());
        // Same expression evaluated against different contexts compiles once.
        assert!(cache.evaluate("n > 5", &json!({"n": 10})).unwrap());
        assert!(!cache.evaluate("n > 5", &json!({"n": 3})).unwrap());
        assert!(cache.evaluate("n > 5", &json!({"n": 100})).unwrap());
        assert_eq!(cache.len(), 1);

        // A distinct expression adds a second entry.
        assert!(cache.evaluate("n < 5", &json!({"n": 1})).unwrap());
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn cache_caches_errors() {
        let cache = ConditionCache::new();
        let ctx = json!({});
        assert!(cache.evaluate("== bad", &ctx).is_err());
        // Re-evaluating the same malformed expression returns the cached error
        // without re-parsing, and does not add a second entry.
        assert!(cache.evaluate("== bad", &ctx).is_err());
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn cache_matches_direct_evaluate() {
        let cache = ConditionCache::new();
        let ctx = json!({"steps": {"build": {"status": "completed"}}});
        let expr = "steps.build.status == 'completed'";
        assert_eq!(
            cache.evaluate(expr, &ctx).unwrap(),
            evaluate(expr, &ctx).unwrap()
        );
    }
}