sherpack-engine 0.4.0

Jinja2 templating engine for Sherpack with Kubernetes-specific filters
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
//! Template functions (global functions available in templates)

use minijinja::value::{Object, Rest};
use minijinja::{Error, ErrorKind, State, Value};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

/// Maximum recursion depth for tpl function (prevents infinite loops)
const MAX_TPL_DEPTH: usize = 10;

/// Key for storing tpl recursion depth in State's temp storage
const TPL_DEPTH_KEY: &str = "__sherpack_tpl_depth";

/// Counter object for tracking tpl recursion depth
/// Implements Object trait so it can be stored in State's temp storage
#[derive(Debug, Default)]
struct TplDepthCounter(AtomicUsize);

impl Object for TplDepthCounter {
    fn repr(self: &Arc<Self>) -> minijinja::value::ObjectRepr {
        minijinja::value::ObjectRepr::Plain
    }
}

impl TplDepthCounter {
    fn increment(&self) -> usize {
        self.0.fetch_add(1, Ordering::SeqCst) + 1
    }

    fn decrement(&self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

/// Fail with a custom error message
///
/// Usage: {{ fail("Something went wrong") }}
pub fn fail(message: String) -> Result<Value, Error> {
    Err(Error::new(ErrorKind::InvalidOperation, message))
}

/// Create a dict from key-value pairs
///
/// Usage: {{ dict("key1", value1, "key2", value2) }}
pub fn dict(args: Vec<Value>) -> Result<Value, Error> {
    if !args.len().is_multiple_of(2) {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            "dict requires an even number of arguments (key-value pairs)",
        ));
    }

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

    for chunk in args.chunks(2) {
        let key = chunk[0]
            .as_str()
            .ok_or_else(|| Error::new(ErrorKind::InvalidOperation, "dict keys must be strings"))?;
        let value: serde_json::Value = serde_json::to_value(&chunk[1])
            .map_err(|e| Error::new(ErrorKind::InvalidOperation, e.to_string()))?;
        map.insert(key.to_string(), value);
    }

    Ok(Value::from_serialize(serde_json::Value::Object(map)))
}

/// Create a list from values
///
/// Usage: {{ list("a", "b", "c") }}
pub fn list(args: Vec<Value>) -> Value {
    Value::from(args)
}

/// Get a value with a default if undefined
///
/// Usage: {{ get(values, "key", "default") }}
pub fn get(obj: Value, key: String, default: Option<Value>) -> Value {
    match obj.get_attr(&key) {
        Ok(v) if !v.is_undefined() => v,
        _ => default.unwrap_or(Value::UNDEFINED),
    }
}

/// Set a key in a dict (returns new dict, original unchanged)
///
/// Usage: {{ set(mydict, "newkey", "newvalue") }}
pub fn set(dict: Value, key: String, val: Value) -> Result<Value, Error> {
    use minijinja::value::ValueKind;

    match dict.kind() {
        ValueKind::Map => {
            let mut result = indexmap::IndexMap::new();

            // Copy existing entries
            if let Ok(iter) = dict.try_iter() {
                for k in iter {
                    if let Some(k_str) = k.as_str()
                        && let Ok(v) = dict.get_item(&k)
                    {
                        result.insert(k_str.to_string(), v);
                    }
                }
            }

            // Set the new value
            result.insert(key, val);
            Ok(Value::from_iter(result))
        }
        _ => Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("set requires a dict, got {:?}", dict.kind()),
        )),
    }
}

/// Remove a key from a dict (returns new dict, original unchanged)
///
/// Usage: {{ unset(mydict, "keytoremove") }}
pub fn unset(dict: Value, key: String) -> Result<Value, Error> {
    use minijinja::value::ValueKind;

    match dict.kind() {
        ValueKind::Map => {
            let mut result = indexmap::IndexMap::new();

            if let Ok(iter) = dict.try_iter() {
                for k in iter {
                    if let Some(k_str) = k.as_str()
                        && k_str != key
                        && let Ok(v) = dict.get_item(&k)
                    {
                        result.insert(k_str.to_string(), v);
                    }
                }
            }

            Ok(Value::from_iter(result))
        }
        _ => Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("unset requires a dict, got {:?}", dict.kind()),
        )),
    }
}

/// Deep get with path and default value
///
/// Usage: {{ dig(mydict, "a", "b", "c", "default") }}
/// Equivalent to mydict.a.b.c with fallback to default if any key is missing
pub fn dig(dict: Value, keys_and_default: Rest<Value>) -> Result<Value, Error> {
    let args: &[Value] = &keys_and_default;

    if args.is_empty() {
        return Err(Error::new(
            ErrorKind::InvalidOperation,
            "dig requires at least one key and a default value",
        ));
    }

    // Last argument is the default value, rest are keys
    let (keys, default_slice) = args.split_at(args.len() - 1);
    let default = default_slice.first().cloned().unwrap_or(Value::UNDEFINED);

    if keys.is_empty() {
        // Only default was provided, return the dict itself
        return Ok(dict);
    }

    // Traverse the path
    let mut current = dict;
    for key in keys {
        match key.as_str() {
            Some(k) => match current.get_attr(k) {
                Ok(v) if !v.is_undefined() => current = v,
                _ => return Ok(default),
            },
            None => {
                // Handle integer keys for lists
                if let Some(idx) = key.as_i64() {
                    match current.get_item(&Value::from(idx)) {
                        Ok(v) if !v.is_undefined() => current = v,
                        _ => return Ok(default),
                    }
                } else {
                    return Ok(default);
                }
            }
        }
    }

    Ok(current)
}

/// Return first non-empty value
///
/// Usage: {{ coalesce(a, b, c) }}
pub fn coalesce(args: Vec<Value>) -> Value {
    for arg in args {
        if !arg.is_undefined() && !arg.is_none() {
            if let Some(s) = arg.as_str() {
                if !s.is_empty() {
                    return arg;
                }
            } else {
                return arg;
            }
        }
    }
    Value::UNDEFINED
}

/// Ternary operator
///
/// Usage: {{ ternary(true_value, false_value, condition) }}
pub fn ternary(true_val: Value, false_val: Value, condition: Value) -> Value {
    if condition.is_true() {
        true_val
    } else {
        false_val
    }
}

/// Generate a UUID (v4)
///
/// Usage: {{ uuidv4() }}
pub fn uuidv4() -> String {
    // Simple UUID v4 generation without external dependency
    use std::time::{SystemTime, UNIX_EPOCH};

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();

    let random_part = timestamp ^ (timestamp >> 32);

    format!(
        "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
        (random_part & 0xFFFFFFFF) as u32,
        ((random_part >> 32) & 0xFFFF) as u16,
        ((random_part >> 48) & 0x0FFF) as u16,
        (((random_part >> 60) & 0x3F) | 0x80) as u16 | ((random_part & 0xFF) << 8) as u16,
        (random_part ^ (random_part >> 16)) & 0xFFFFFFFFFFFF
    )
}

/// Convert a value to a string representation
///
/// Usage: {{ tostring(value) }}
pub fn tostring(value: Value) -> String {
    if let Some(s) = value.as_str() {
        s.to_string()
    } else {
        value.to_string()
    }
}

/// Convert a value to an integer
///
/// Usage: {{ toint(value) }}
pub fn toint(value: Value) -> Result<i64, Error> {
    if let Some(n) = value.as_i64() {
        Ok(n)
    } else if let Some(s) = value.as_str() {
        s.parse::<i64>().map_err(|_| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("cannot convert '{}' to int", s),
            )
        })
    } else {
        Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("cannot convert {:?} to int", value),
        ))
    }
}

/// Convert a value to a float
///
/// Usage: {{ tofloat(value) }}
pub fn tofloat(value: Value) -> Result<f64, Error> {
    if let Some(n) = value.as_i64() {
        Ok(n as f64)
    } else if let Some(s) = value.as_str() {
        s.parse::<f64>().map_err(|_| {
            Error::new(
                ErrorKind::InvalidOperation,
                format!("cannot convert '{}' to float", s),
            )
        })
    } else {
        Err(Error::new(
            ErrorKind::InvalidOperation,
            format!("cannot convert {:?} to float", value),
        ))
    }
}

/// Get current timestamp
///
/// Usage: {{ now() }}
pub fn now() -> String {
    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

/// Printf-style formatting
///
/// Usage: {{ printf("%s-%d", name, count) }}
///
/// Supports format specifiers: %s, %d, %f, %v, %%
pub fn printf(format: String, args: Vec<Value>) -> Result<String, Error> {
    // Pre-allocate with estimated size
    let mut result = String::with_capacity(format.len() + args.len() * 10);
    let mut chars = format.chars().peekable();
    let mut arg_idx = 0;

    while let Some(c) = chars.next() {
        if c != '%' {
            result.push(c);
            continue;
        }

        // Handle format specifier
        let format_char = match chars.next() {
            Some(fc) => fc,
            None => {
                // Trailing % at end of string
                result.push('%');
                break;
            }
        };

        // Handle escaped %%
        if format_char == '%' {
            result.push('%');
            continue;
        }

        // Need an argument for this specifier
        if arg_idx >= args.len() {
            return Err(Error::new(
                ErrorKind::InvalidOperation,
                "not enough arguments for format string",
            ));
        }

        let arg = &args[arg_idx];
        match format_char {
            's' | 'v' => result.push_str(&arg.to_string()),
            'd' => {
                if let Some(n) = arg.as_i64() {
                    result.push_str(&n.to_string());
                } else {
                    result.push_str(&arg.to_string());
                }
            }
            'f' => {
                if let Some(n) = arg.as_i64() {
                    result.push_str(&(n as f64).to_string());
                } else {
                    result.push_str(&arg.to_string());
                }
            }
            _ => {
                // Unknown format specifier, treat as %v
                result.push_str(&arg.to_string());
            }
        }
        arg_idx += 1;
    }

    Ok(result)
}

/// Evaluate a string as a template (Helm's tpl function)
///
/// Usage: {{ tpl(values.dynamicTemplate, ctx) }}
///
/// This allows template strings stored in values to contain Jinja expressions.
/// The context parameter provides the variables available to the nested template.
///
/// ## Security Features (Sherpack improvements over Helm)
///
/// - **Recursion limit**: Maximum depth of 10 to prevent infinite loops
/// - **Source tracking**: Better error messages showing template origin
///
/// ## Example
///
/// In values.yaml:
/// ```yaml
/// host: "{{ release.name }}.example.com"
/// ```
///
/// Then in template:
/// ```jinja
/// host: {{ tpl(values.host, {"release": release}) }}
/// ```
/// Result: `host: myrelease.example.com`
pub fn tpl(state: &State, template: String, context: Value) -> Result<String, Error> {
    // Skip if no template markers present (optimization)
    if !template.contains("{{") && !template.contains("{%") {
        return Ok(template);
    }

    // Check recursion depth to prevent infinite loops
    let depth = increment_tpl_depth(state)?;

    // Render the template string using the current environment
    let result = state.env().render_str(&template, context).map_err(|e| {
        // Enhance error message with tpl context
        Error::new(
            ErrorKind::InvalidOperation,
            format!(
                "tpl error (depth {}): {}\n  Template: \"{}\"",
                depth,
                e,
                truncate_for_error(&template, 60)
            ),
        )
    });

    // Decrement depth after rendering (for sibling tpl calls)
    decrement_tpl_depth(state);

    result
}

/// Increment tpl recursion depth, returning error if limit exceeded
fn increment_tpl_depth(state: &State) -> Result<usize, Error> {
    let counter = state.get_or_set_temp_object(TPL_DEPTH_KEY, TplDepthCounter::default);
    let depth = counter.increment();

    if depth > MAX_TPL_DEPTH {
        Err(Error::new(
            ErrorKind::InvalidOperation,
            format!(
                "tpl recursion depth {} exceeded maximum {} - possible infinite loop in values. \
                 Check for circular references in template strings.",
                depth, MAX_TPL_DEPTH
            ),
        ))
    } else {
        Ok(depth)
    }
}

/// Decrement tpl recursion depth
fn decrement_tpl_depth(state: &State) {
    let counter = state.get_or_set_temp_object(TPL_DEPTH_KEY, TplDepthCounter::default);
    counter.decrement();
}

/// Truncate string for error messages
fn truncate_for_error(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len])
    }
}

/// Kubernetes resource lookup (Helm-compatible)
///
/// Usage: {{ lookup("v1", "Secret", "default", "my-secret") }}
///
/// **IMPORTANT:** In template-only mode (sherpack template), this function
/// always returns an empty object, matching Helm's behavior.
///
/// Parameters:
/// - apiVersion: API version (e.g., "v1", "apps/v1")
/// - kind: Resource kind (e.g., "Secret", "ConfigMap", "Deployment")
/// - namespace: Namespace (empty string "" for cluster-scoped resources)
/// - name: Resource name (empty string "" to list all resources)
///
/// Return values:
/// - Single resource: Returns the resource as a dict
/// - List (name=""): Returns {"items": [...]} dict
/// - Not found / template mode: Returns empty dict {}
///
/// ## Why lookup returns empty in template mode
///
/// Like Helm, Sherpack separates template rendering from cluster operations:
/// - `sherpack template`: Pure rendering, no cluster access → lookup returns {}
/// - `sherpack install/upgrade`: Cluster access for apply, but lookup still empty
///
/// ## Alternatives to lookup
///
/// Instead of using lookup, consider these Sherpack patterns:
///
/// 1. **Check if resource exists**: Use sync-waves to create dependencies
///    ```yaml
///    sherpack.io/sync-wave: "0"  # Create first
///    ---
///    sherpack.io/sync-wave: "1"  # Created after wave 0 is ready
///    ```
///
/// 2. **Reuse existing secrets**: Use external-secrets or hooks
///    ```yaml
///    sherpack.io/hook: pre-install
///    sherpack.io/hook-weight: "-5"
///    ```
///
/// 3. **Conditional resources**: Use values-based conditions
///    ```jinja
///    {%- if values.existingSecret %}
///    secretName: {{ values.existingSecret }}
///    {%- else %}
///    secretName: {{ release.name }}-secret
///    {%- endif %}
///    ```
pub fn lookup(api_version: String, kind: String, namespace: String, name: String) -> Value {
    // Log what was requested (useful for debugging/migration from Helm)
    // In template mode, this always returns empty - matching Helm behavior
    let _ = (api_version, kind, namespace, name); // Acknowledge params

    // Return empty dict - same as Helm's `helm template` behavior
    // This ensures charts work in GitOps workflows and CI/CD pipelines
    Value::from_serialize(serde_json::json!({}))
}

/// Evaluate a string as a template with full context (convenience version)
///
/// Usage: {{ tpl_ctx(values.dynamicTemplate) }}
///
/// This version automatically passes the full template context (values, release, pack, etc.)
/// to the nested template, similar to Helm's `tpl $str .` pattern.
///
/// ## Security Features
///
/// - **Recursion limit**: Shares depth counter with `tpl()`, max depth 10
/// - **Full context**: Passes values, release, pack, capabilities, template
pub fn tpl_ctx(state: &State, template: String) -> Result<String, Error> {
    // Skip if no template markers present (optimization)
    if !template.contains("{{") && !template.contains("{%") {
        return Ok(template);
    }

    // Check recursion depth to prevent infinite loops
    let depth = increment_tpl_depth(state)?;

    // Build context from all available variables
    let mut ctx = serde_json::Map::new();

    // Try to lookup and add standard context variables
    for var in ["values", "release", "pack", "capabilities", "template"] {
        if let Some(v) = state.lookup(var)
            && !v.is_undefined()
            && let Ok(json_val) = serde_json::to_value(&v)
        {
            ctx.insert(var.to_string(), json_val);
        }
    }

    let context = Value::from_serialize(serde_json::Value::Object(ctx));

    let result = state.env().render_str(&template, context).map_err(|e| {
        Error::new(
            ErrorKind::InvalidOperation,
            format!(
                "tpl_ctx error (depth {}): {}\n  Template: \"{}\"",
                depth,
                e,
                truncate_for_error(&template, 60)
            ),
        )
    });

    // Decrement depth after rendering
    decrement_tpl_depth(state);

    result
}

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

    #[test]
    fn test_dict() {
        let result = dict(vec![
            Value::from("key1"),
            Value::from("value1"),
            Value::from("key2"),
            Value::from(42),
        ])
        .unwrap();

        assert_eq!(result.get_attr("key1").unwrap().as_str(), Some("value1"));
    }

    #[test]
    fn test_list() {
        let result = list(vec![Value::from("a"), Value::from("b"), Value::from("c")]);
        assert_eq!(result.len(), Some(3));
    }

    #[test]
    fn test_ternary() {
        assert_eq!(
            ternary(Value::from("yes"), Value::from("no"), Value::from(true)).as_str(),
            Some("yes")
        );
        assert_eq!(
            ternary(Value::from("yes"), Value::from("no"), Value::from(false)).as_str(),
            Some("no")
        );
    }

    #[test]
    fn test_printf() {
        let result = printf(
            "Hello %s, you have %d messages".to_string(),
            vec![Value::from("Alice"), Value::from(5)],
        )
        .unwrap();
        assert_eq!(result, "Hello Alice, you have 5 messages");
    }

    #[test]
    fn test_tpl_integration() {
        use minijinja::Environment;

        // Test tpl via full environment (since it needs State)
        let mut env = Environment::new();
        env.add_function("tpl", super::tpl);

        let template = r#"{{ tpl("Hello {{ name }}!", {"name": "World"}) }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "Hello World!");
    }

    #[test]
    fn test_tpl_no_markers() {
        use minijinja::Environment;

        // Plain string without template markers should be returned as-is
        let mut env = Environment::new();
        env.add_function("tpl", super::tpl);

        let template = r#"{{ tpl("plain text", {}) }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "plain text");
    }

    #[test]
    fn test_tpl_complex() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("tpl", super::tpl);

        // Test with conditional
        let template =
            r#"{{ tpl("{% if enabled %}yes{% else %}no{% endif %}", {"enabled": true}) }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "yes");
    }

    #[test]
    fn test_tpl_recursion_limit() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("tpl", super::tpl);

        // Create a deeply nested tpl call that would exceed MAX_TPL_DEPTH
        // Each nested tpl increases depth by 1
        let template = r#"{{ tpl("{{ tpl(\"{{ tpl(\\\"{{ tpl(\\\\\\\"{{ tpl(\\\\\\\\\\\\\\\"{{ tpl(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"{{ tpl(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"{{ tpl(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"{{ tpl(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"done\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\", {}) }}\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\", {}) }}\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\", {}) }}\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\", {}) }}\\\\\\\\\\\\\\\", {}) }}\\\\\\\"  , {}) }}\\\\\\\", {}) }}\\\", {}) }}\", {}) }}", {}) }}"#;

        let result = env.render_str(template, ());

        // Should fail with recursion limit error
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("recursion") || err.to_string().contains("depth"),
            "Expected recursion error, got: {}",
            err
        );
    }

    #[test]
    fn test_tpl_nested_valid() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("tpl", super::tpl);

        // 3 levels of nesting should work fine
        let template = r#"{{ tpl("{{ tpl(\"{{ tpl(\\\"level3\\\", {}) }}\", {}) }}", {}) }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "level3");
    }

    #[test]
    fn test_truncate_for_error() {
        assert_eq!(truncate_for_error("short", 10), "short");
        assert_eq!(
            truncate_for_error("this is a longer string", 10),
            "this is a ..."
        );
    }

    #[test]
    fn test_lookup_returns_empty() {
        // lookup should return empty dict in template mode
        let result = lookup(
            "v1".to_string(),
            "Secret".to_string(),
            "default".to_string(),
            "my-secret".to_string(),
        );

        // Should be an empty object, not undefined
        assert!(!result.is_undefined());
        // Should be iterable (dict)
        assert!(result.try_iter().is_ok());
    }

    #[test]
    fn test_lookup_in_template() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("lookup", super::lookup);

        // Common Helm pattern: check if secret exists
        let template = r#"{% set secret = lookup("v1", "Secret", "default", "my-secret") %}{% if secret %}secret exists{% else %}no secret{% endif %}"#;
        let result = env.render_str(template, ()).unwrap();
        // Empty dict is falsy, so we get "no secret"
        assert_eq!(result, "no secret");
    }

    #[test]
    fn test_lookup_conditional_pattern() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("lookup", super::lookup);

        // Recommended pattern: check if lookup result exists before accessing properties
        let template = r#"{% set secret = lookup("v1", "Secret", "ns", "s") %}{% if secret.data is defined %}{{ secret.data.password }}{% else %}generated{% endif %}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "generated");
    }

    #[test]
    fn test_lookup_safe_pattern() {
        use crate::filters::tojson;
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("lookup", super::lookup);
        env.add_function("get", super::get);
        env.add_filter("tojson", tojson);

        // Safe pattern for strict mode: use get() with default
        let template = r#"{% set secret = lookup("v1", "Secret", "ns", "s") %}{{ get(secret, "data", {}) | tojson }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "{}");
    }

    #[test]
    fn test_set_function() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("set", super::set);

        let template = r#"{% set d = {"a": 1} %}{{ set(d, "b", 2) }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert!(result.contains("a") && result.contains("b"));
    }

    #[test]
    fn test_unset_function() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("unset", super::unset);

        let template = r#"{% set d = {"a": 1, "b": 2} %}{{ unset(d, "a") }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert!(!result.contains("a") && result.contains("b"));
    }

    #[test]
    fn test_dig_function() {
        use minijinja::Environment;

        let mut env = Environment::new();
        env.add_function("dig", super::dig);

        // Test deep access that exists
        let template =
            r#"{% set d = {"a": {"b": {"c": "found"}}} %}{{ dig(d, "a", "b", "c", "default") }}"#;
        let result = env.render_str(template, ()).unwrap();
        assert_eq!(result, "found");

        // Test deep access that doesn't exist (returns default)
        let template2 = r#"{% set d = {"a": {"b": {}}} %}{{ dig(d, "a", "b", "c", "default") }}"#;
        let result2 = env.render_str(template2, ()).unwrap();
        assert_eq!(result2, "default");
    }
}