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
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
//! Engine error types with beautiful formatting

// Allow unused_assignments for derive macros (miette/thiserror use fields via attributes)
#![allow(unused_assignments)]

use indexmap::IndexMap;
use miette::{Diagnostic, NamedSource, SourceSpan};
use thiserror::Error;

use crate::suggestions::{
    AVAILABLE_FILTERS, extract_filter_name, extract_function_name, extract_variable_name,
    suggest_iteration_fix, suggest_undefined_variable, suggest_unknown_filter,
    suggest_unknown_function,
};

/// Main engine error type
#[derive(Error, Debug)]
pub enum EngineError {
    #[error("Template error")]
    Template(Box<TemplateError>),

    #[error("Filter error: {message}")]
    Filter { message: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("YAML error: {0}")]
    Yaml(#[from] serde_yaml::Error),

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    #[error("Multiple template errors occurred")]
    MultipleErrors(Box<RenderReport>),
}

impl From<TemplateError> for EngineError {
    fn from(e: TemplateError) -> Self {
        EngineError::Template(Box::new(e))
    }
}

/// Error kind for categorizing template errors
///
/// Note: This enum is non-exhaustive - new variants may be added in future versions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TemplateErrorKind {
    UndefinedVariable,
    UnknownFilter,
    UnknownFunction,
    SyntaxError,
    TypeError,
    InvalidOperation,
    YamlParseError,
    Other,
}

impl TemplateErrorKind {
    /// Convert to a code string for diagnostics
    pub fn to_code_string(&self) -> &'static str {
        match self {
            Self::UndefinedVariable => "undefined_variable",
            Self::UnknownFilter => "unknown_filter",
            Self::UnknownFunction => "unknown_function",
            Self::SyntaxError => "syntax",
            Self::TypeError => "type",
            Self::InvalidOperation => "invalid_operation",
            Self::YamlParseError => "yaml_parse",
            Self::Other => "render",
        }
    }
}

/// Template-specific error with source information
#[derive(Error, Debug, Diagnostic, Clone)]
#[error("{message}")]
#[diagnostic(code(sherpack::template::render))]
pub struct TemplateError {
    /// Error message
    pub message: String,

    /// Error kind for categorization
    pub kind: TemplateErrorKind,

    /// Template source code
    #[source_code]
    pub src: NamedSource<String>,

    /// Error location in source
    #[label("error occurred here")]
    pub span: Option<SourceSpan>,

    /// Suggestion for fixing the error
    #[help]
    pub suggestion: Option<String>,

    /// Additional context (available values, etc.)
    pub context: Option<String>,
}

impl TemplateError {
    /// Create a new template error from a MiniJinja error
    pub fn from_minijinja(
        err: minijinja::Error,
        template_name: &str,
        template_source: &str,
    ) -> Self {
        let (kind, message) = categorize_minijinja_error(&err);
        let line = err.line();

        // Calculate source span from line number
        let span = line.and_then(|line_num| calculate_span(template_source, line_num));

        // Generate suggestion based on error kind
        let suggestion = generate_suggestion(&err, &kind, None);

        Self {
            message,
            kind,
            src: NamedSource::new(template_name, template_source.to_string()),
            span,
            suggestion,
            context: None,
        }
    }

    /// Create a new template error from a MiniJinja error with enhanced context-aware suggestions
    pub fn from_minijinja_enhanced(
        err: minijinja::Error,
        template_name: &str,
        template_source: &str,
        values: Option<&serde_json::Value>,
    ) -> Self {
        let (kind, message) = categorize_minijinja_error(&err);
        let line = err.line();

        // Calculate source span from line number
        let span = line.and_then(|line_num| calculate_span(template_source, line_num));

        // Generate context-aware suggestion
        let suggestion = generate_suggestion(&err, &kind, values);

        Self {
            message,
            kind,
            src: NamedSource::new(template_name, template_source.to_string()),
            span,
            suggestion,
            context: None,
        }
    }

    /// Create a simple error without source mapping
    pub fn simple(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            kind: TemplateErrorKind::Other,
            src: NamedSource::new("<unknown>", String::new()),
            span: None,
            suggestion: None,
            context: None,
        }
    }

    /// Add context information
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(context.into());
        self
    }

    /// Add a suggestion
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }

    /// Get the error kind
    pub fn kind(&self) -> TemplateErrorKind {
        self.kind
    }
}

/// Categorize a MiniJinja error into our error kinds
fn categorize_minijinja_error(err: &minijinja::Error) -> (TemplateErrorKind, String) {
    let msg = err.to_string();
    let msg_lower = msg.to_lowercase();

    // Get the detailed display which contains more info
    let detailed = format!("{:#}", err);

    let kind = match err.kind() {
        minijinja::ErrorKind::UndefinedError => TemplateErrorKind::UndefinedVariable,
        minijinja::ErrorKind::UnknownFilter => TemplateErrorKind::UnknownFilter,
        minijinja::ErrorKind::UnknownFunction => TemplateErrorKind::UnknownFunction,
        minijinja::ErrorKind::SyntaxError => TemplateErrorKind::SyntaxError,
        minijinja::ErrorKind::InvalidOperation => TemplateErrorKind::InvalidOperation,
        minijinja::ErrorKind::NonPrimitive | minijinja::ErrorKind::NonKey => {
            TemplateErrorKind::TypeError
        }
        _ => {
            // Fallback to string matching for other cases
            if msg_lower.contains("undefined") || msg_lower.contains("unknown variable") {
                TemplateErrorKind::UndefinedVariable
            } else if msg_lower.contains("filter") {
                TemplateErrorKind::UnknownFilter
            } else if msg_lower.contains("function") {
                TemplateErrorKind::UnknownFunction
            } else if msg_lower.contains("syntax") || msg_lower.contains("expected") {
                TemplateErrorKind::SyntaxError
            } else if msg_lower.contains("not iterable") || msg_lower.contains("cannot") {
                TemplateErrorKind::TypeError
            } else {
                TemplateErrorKind::Other
            }
        }
    };

    // Extract the actual expression from the detailed error if possible
    // MiniJinja format shows: "   8 >   typo: {{ value.app.name }}"
    // followed by: "     i            ^^^^^^^^^ undefined value"
    let enhanced_msg = match kind {
        TemplateErrorKind::UndefinedVariable => {
            if let Some(expr) = extract_expression_from_display(&detailed) {
                format!("undefined variable `{}`", expr)
            } else {
                msg.replace("undefined value", "undefined variable")
            }
        }
        TemplateErrorKind::UnknownFilter => {
            if let Some(filter) = extract_filter_from_display(&detailed) {
                format!("unknown filter `{}`", filter)
            } else {
                msg.clone()
            }
        }
        _ => msg
            .replace("invalid operation: ", "")
            .replace("syntax error: ", "")
            .replace("undefined value", "undefined variable"),
    };

    (kind, enhanced_msg)
}

/// Extract the problematic expression from MiniJinja's detailed display
fn extract_expression_from_display(display: &str) -> Option<String> {
    // MiniJinja format:
    //    8 >   typo: {{ value.app.name }}
    //      i            ^^^^^^^^^ undefined value
    // The `>` marker shows the error line

    let lines: Vec<&str> = display.lines().collect();

    // First, find the line with the `>` marker (error line)
    for (i, line) in lines.iter().enumerate() {
        // Look for pattern like "   8 >   " at the start
        let trimmed = line.trim_start();
        if trimmed.contains(" > ") || trimmed.starts_with("> ") {
            // This is the error line - extract expression
            if let Some(start) = line.find("{{")
                && let Some(end) = line[start..].find("}}")
            {
                let expr = line[start + 2..start + end].trim();
                // Get the first part before any filter (for undefined var)
                let expr_part = expr.split('|').next().unwrap_or(expr).trim();
                if !expr_part.is_empty() {
                    return Some(expr_part.to_string());
                }
            }
        }

        // Also check the line after a ^^^^^ marker for the error line
        if line.contains("^^^^^") {
            // The line with ^^^^^ follows the error line, so check i-1
            if i > 0 {
                let prev_line = lines[i - 1];
                if let Some(start) = prev_line.find("{{")
                    && let Some(end) = prev_line[start..].find("}}")
                {
                    let expr = prev_line[start + 2..start + end].trim();
                    let expr_part = expr.split('|').next().unwrap_or(expr).trim();
                    if !expr_part.is_empty() {
                        return Some(expr_part.to_string());
                    }
                }
            }
        }
    }

    None
}

/// Extract the filter name from MiniJinja's detailed display
fn extract_filter_from_display(display: &str) -> Option<String> {
    // Look for the error line (marked with >) and find the filter
    // MiniJinja format:
    //    8 >   badFilter: {{ values.app.name | toyml }}
    //      i                                   ^^^^^ unknown filter

    let lines: Vec<&str> = display.lines().collect();

    // Find the error line
    for line in &lines {
        let trimmed = line.trim_start();
        if trimmed.contains(" > ") || trimmed.starts_with("> ") {
            // Look for {{ ... | filter }} pattern
            if let Some(start) = line.find("{{")
                && let Some(end) = line[start..].find("}}")
            {
                let expr = &line[start + 2..start + end];
                // Find the pipe and get the filter name
                if let Some(pipe_pos) = expr.rfind('|') {
                    let filter_part = expr[pipe_pos + 1..].trim();
                    // Filter name is the first word
                    let filter_name = filter_part.split_whitespace().next();
                    if let Some(name) = filter_name
                        && !name.is_empty()
                    {
                        return Some(name.to_string());
                    }
                }
            }
        }
    }

    // Fallback: look for pattern "unknown filter" in error message
    for line in &lines {
        if line.contains("unknown filter") {
            // Try to extract from the ^^^^^ marker line
            continue;
        }
    }

    None
}

/// Calculate the source span for a given line number
fn calculate_span(source: &str, line_num: usize) -> Option<SourceSpan> {
    let mut offset = 0;

    for (idx, line) in source.lines().enumerate() {
        let current_line = idx + 1;
        if current_line == line_num {
            // Return span for the entire line
            return Some(SourceSpan::new(offset.into(), line.len()));
        }
        offset += line.len() + 1; // +1 for newline
    }

    None
}

/// Generate context-aware suggestions based on error kind
fn generate_suggestion(
    err: &minijinja::Error,
    kind: &TemplateErrorKind,
    values: Option<&serde_json::Value>,
) -> Option<String> {
    let msg = err.to_string();
    let detailed = format!("{:#}", err);

    match kind {
        TemplateErrorKind::UndefinedVariable => {
            // Try to extract variable name from detailed display first
            let var_name =
                extract_expression_from_display(&detailed).or_else(|| extract_variable_name(&msg));

            if let Some(var_name) = var_name {
                // Check for common typo: "value" instead of "values"
                if var_name == "value" || var_name.starts_with("value.") {
                    let corrected = var_name.replacen("value", "values", 1);
                    return Some(format!(
                        "Did you mean `{}`? Use `values` (plural) to access the values object.",
                        corrected
                    ));
                }

                // Check for property access on values
                if let Some(path) = var_name.strip_prefix("values.") {
                    let parts: Vec<&str> = path.split('.').collect();

                    if let Some(vals) = values {
                        // Navigate to find where the path breaks
                        let mut current = vals;
                        let mut valid_parts = vec![];

                        for part in &parts {
                            if let Some(next) = current.get(part) {
                                valid_parts.push(*part);
                                current = next;
                            } else {
                                // This part doesn't exist - suggest alternatives
                                if let Some(obj) = current.as_object() {
                                    let available: Vec<&str> =
                                        obj.keys().map(|s| s.as_str()).collect();

                                    // Find closest match
                                    let matches = crate::suggestions::find_closest_matches(
                                        part,
                                        &available,
                                        3,
                                        crate::suggestions::SuggestionCategory::Property,
                                    );

                                    let prefix = if valid_parts.is_empty() {
                                        "values".to_string()
                                    } else {
                                        format!("values.{}", valid_parts.join("."))
                                    };

                                    if !matches.is_empty() {
                                        let suggestions: Vec<String> = matches
                                            .iter()
                                            .map(|m| format!("`{}.{}`", prefix, m.text))
                                            .collect();
                                        return Some(format!(
                                            "Key `{}` not found. Did you mean {}? Available: {}",
                                            part,
                                            suggestions.join(" or "),
                                            available.join(", ")
                                        ));
                                    } else {
                                        return Some(format!(
                                            "Key `{}` not found in `{}`. Available keys: {}",
                                            part,
                                            prefix,
                                            available.join(", ")
                                        ));
                                    }
                                }
                                break;
                            }
                        }
                    }
                }

                // General undefined variable suggestion
                let available = values
                    .and_then(|v| v.as_object())
                    .map(|obj| obj.keys().cloned().collect::<Vec<_>>())
                    .unwrap_or_default();

                return suggest_undefined_variable(&var_name, &available).or_else(|| {
                    Some(format!(
                        "Variable `{}` is not defined. Check spelling or use `| default(\"fallback\")`.",
                        var_name
                    ))
                });
            }
            Some("Variable is not defined. Check spelling or use the `default` filter.".to_string())
        }

        TemplateErrorKind::UnknownFilter => {
            // Try to extract filter name from detailed display first
            let filter_name =
                extract_filter_from_display(&detailed).or_else(|| extract_filter_name(&msg));

            if let Some(filter_name) = filter_name {
                return suggest_unknown_filter(&filter_name);
            }
            Some(format!(
                "Unknown filter. Available: {}",
                AVAILABLE_FILTERS.join(", ")
            ))
        }

        TemplateErrorKind::UnknownFunction => {
            if let Some(func_name) = extract_function_name(&msg) {
                return suggest_unknown_function(&func_name);
            }
            Some("Unknown function. Check the function name and arguments.".to_string())
        }

        TemplateErrorKind::SyntaxError => {
            if msg.contains("}") || msg.contains("%") {
                Some(
                    "Check bracket matching: `{{ }}` for expressions, `{% %}` for statements, `{# #}` for comments".to_string(),
                )
            } else if msg.contains("expected") {
                Some(
                    "Syntax error. Check for missing closing tags or mismatched brackets."
                        .to_string(),
                )
            } else {
                None
            }
        }

        TemplateErrorKind::TypeError => {
            if msg.to_lowercase().contains("not iterable") {
                Some(suggest_iteration_fix("object"))
            } else if msg.to_lowercase().contains("not callable") {
                Some(
                    "Use `{{ value }}` for variables, `{{ func() }}` for function calls."
                        .to_string(),
                )
            } else {
                None
            }
        }

        _ => None,
    }
}

/// Severity level for render issues
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// Warning - doesn't prevent rendering but may cause issues
    Warning,
    /// Error - prevents successful rendering
    Error,
}

/// A render issue (warning or infrastructure problem)
#[derive(Debug, Clone)]
pub struct RenderIssue {
    /// Issue category (e.g., "files_api", "subchart")
    pub category: String,
    /// Human-readable message
    pub message: String,
    /// Severity level
    pub severity: IssueSeverity,
}

impl RenderIssue {
    /// Create a new warning
    pub fn warning(category: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            category: category.into(),
            message: message.into(),
            severity: IssueSeverity::Warning,
        }
    }

    /// Create a new error
    pub fn error(category: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            category: category.into(),
            message: message.into(),
            severity: IssueSeverity::Error,
        }
    }
}

/// A collection of errors from rendering multiple templates
#[derive(Debug, Default)]
pub struct RenderReport {
    /// Errors grouped by template file (IndexMap preserves insertion order)
    pub errors_by_template: IndexMap<String, Vec<TemplateError>>,

    /// Successfully rendered templates
    pub successful_templates: Vec<String>,

    /// Total error count
    pub total_errors: usize,

    /// Infrastructure issues (warnings/errors not tied to specific templates)
    pub issues: Vec<RenderIssue>,
}

impl RenderReport {
    /// Create a new empty report
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an error for a specific template
    pub fn add_error(&mut self, template_name: String, error: TemplateError) {
        self.errors_by_template
            .entry(template_name)
            .or_default()
            .push(error);
        self.total_errors += 1;
    }

    /// Mark a template as successfully rendered
    pub fn add_success(&mut self, template_name: String) {
        self.successful_templates.push(template_name);
    }

    /// Add an infrastructure issue (warning or error not tied to a template)
    pub fn add_issue(&mut self, issue: RenderIssue) {
        self.issues.push(issue);
    }

    /// Add a warning
    pub fn add_warning(&mut self, category: impl Into<String>, message: impl Into<String>) {
        self.issues.push(RenderIssue::warning(category, message));
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        self.total_errors > 0
    }

    /// Check if there are any warnings
    pub fn has_warnings(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Warning)
    }

    /// Check if there are any issues (warnings or errors)
    pub fn has_issues(&self) -> bool {
        !self.issues.is_empty()
    }

    /// Get warnings only
    pub fn warnings(&self) -> impl Iterator<Item = &RenderIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Warning)
    }

    /// Get count of templates with errors
    pub fn templates_with_errors(&self) -> usize {
        self.errors_by_template.len()
    }

    /// Generate summary message: "5 errors in 3 templates"
    pub fn summary(&self) -> String {
        let template_word = if self.templates_with_errors() == 1 {
            "template"
        } else {
            "templates"
        };
        let error_word = if self.total_errors == 1 {
            "error"
        } else {
            "errors"
        };

        let base = format!(
            "{} {} in {} {}",
            self.total_errors,
            error_word,
            self.templates_with_errors(),
            template_word
        );

        let warning_count = self.warnings().count();
        if warning_count > 0 {
            let warning_word = if warning_count == 1 {
                "warning"
            } else {
                "warnings"
            };
            format!("{}, {} {}", base, warning_count, warning_word)
        } else {
            base
        }
    }
}

/// Result type that includes both successful renders and collected errors
#[derive(Debug)]
pub struct RenderResultWithReport {
    /// Rendered manifests (may be partial if errors occurred, IndexMap preserves order)
    pub manifests: IndexMap<String, String>,

    /// Post-install notes
    pub notes: Option<String>,

    /// Error report (empty if all templates rendered successfully)
    pub report: RenderReport,
}

impl RenderResultWithReport {
    /// Check if rendering was fully successful (no errors)
    pub fn is_success(&self) -> bool {
        !self.report.has_errors()
    }
}

/// Result type for engine operations
pub type Result<T> = std::result::Result<T, EngineError>;

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

    #[test]
    fn test_render_report_new() {
        let report = RenderReport::new();
        assert!(!report.has_errors());
        assert_eq!(report.total_errors, 0);
        assert_eq!(report.templates_with_errors(), 0);
        assert!(report.successful_templates.is_empty());
    }

    #[test]
    fn test_render_report_add_error() {
        let mut report = RenderReport::new();

        let error = TemplateError::simple("test error");
        report.add_error("template.yaml".to_string(), error);

        assert!(report.has_errors());
        assert_eq!(report.total_errors, 1);
        assert_eq!(report.templates_with_errors(), 1);
    }

    #[test]
    fn test_render_report_multiple_errors_same_template() {
        let mut report = RenderReport::new();

        report.add_error(
            "template.yaml".to_string(),
            TemplateError::simple("error 1"),
        );
        report.add_error(
            "template.yaml".to_string(),
            TemplateError::simple("error 2"),
        );

        assert_eq!(report.total_errors, 2);
        assert_eq!(report.templates_with_errors(), 1);
        assert_eq!(report.errors_by_template["template.yaml"].len(), 2);
    }

    #[test]
    fn test_render_report_multiple_templates() {
        let mut report = RenderReport::new();

        report.add_error("a.yaml".to_string(), TemplateError::simple("error 1"));
        report.add_error("b.yaml".to_string(), TemplateError::simple("error 2"));
        report.add_error("c.yaml".to_string(), TemplateError::simple("error 3"));

        assert_eq!(report.total_errors, 3);
        assert_eq!(report.templates_with_errors(), 3);
    }

    #[test]
    fn test_render_report_add_success() {
        let mut report = RenderReport::new();

        report.add_success("good.yaml".to_string());
        report.add_success("also-good.yaml".to_string());

        assert!(!report.has_errors());
        assert_eq!(report.successful_templates.len(), 2);
    }

    #[test]
    fn test_render_report_summary_singular() {
        let mut report = RenderReport::new();
        report.add_error("template.yaml".to_string(), TemplateError::simple("error"));

        assert_eq!(report.summary(), "1 error in 1 template");
    }

    #[test]
    fn test_render_report_summary_plural() {
        let mut report = RenderReport::new();
        report.add_error("a.yaml".to_string(), TemplateError::simple("error 1"));
        report.add_error("a.yaml".to_string(), TemplateError::simple("error 2"));
        report.add_error("b.yaml".to_string(), TemplateError::simple("error 3"));

        assert_eq!(report.summary(), "3 errors in 2 templates");
    }

    #[test]
    fn test_render_result_with_report_success() {
        let result = RenderResultWithReport {
            manifests: IndexMap::new(),
            notes: None,
            report: RenderReport::new(),
        };
        assert!(result.is_success());
    }

    #[test]
    fn test_render_result_with_report_failure() {
        let mut report = RenderReport::new();
        report.add_error("test.yaml".to_string(), TemplateError::simple("error"));

        let result = RenderResultWithReport {
            manifests: IndexMap::new(),
            notes: None,
            report,
        };
        assert!(!result.is_success());
    }

    #[test]
    fn test_template_error_simple() {
        let error = TemplateError::simple("test message");
        assert_eq!(error.message, "test message");
        assert_eq!(error.kind, TemplateErrorKind::Other);
        assert!(error.suggestion.is_none());
    }

    #[test]
    fn test_template_error_with_suggestion() {
        let error = TemplateError::simple("test").with_suggestion("try this");
        assert_eq!(error.suggestion, Some("try this".to_string()));
    }

    #[test]
    fn test_template_error_with_context() {
        let error = TemplateError::simple("test").with_context("additional info");
        assert_eq!(error.context, Some("additional info".to_string()));
    }

    #[test]
    fn test_template_error_kind() {
        let error = TemplateError {
            message: "test".to_string(),
            kind: TemplateErrorKind::UndefinedVariable,
            src: NamedSource::new("test", String::new()),
            span: None,
            suggestion: None,
            context: None,
        };
        assert_eq!(error.kind(), TemplateErrorKind::UndefinedVariable);
    }

    #[test]
    fn test_template_error_kind_to_code_string() {
        assert_eq!(
            TemplateErrorKind::UndefinedVariable.to_code_string(),
            "undefined_variable"
        );
        assert_eq!(
            TemplateErrorKind::UnknownFilter.to_code_string(),
            "unknown_filter"
        );
        assert_eq!(TemplateErrorKind::SyntaxError.to_code_string(), "syntax");
    }

    #[test]
    fn test_extract_expression_from_display_with_marker() {
        let display = r#"
   8 >   typo: {{ value.app.name }}
     i            ^^^^^^^^^ undefined value
"#;
        let expr = extract_expression_from_display(display);
        assert_eq!(expr, Some("value.app.name".to_string()));
    }

    #[test]
    fn test_extract_expression_with_filter() {
        let display = r#"
   8 >   data: {{ values.app.name | upper }}
     i                              ^^^^^ unknown filter
"#;
        let expr = extract_expression_from_display(display);
        assert_eq!(expr, Some("values.app.name".to_string()));
    }

    #[test]
    fn test_extract_filter_from_display() {
        let display = r#"
   8 >   data: {{ values.name | toyml }}
     i                          ^^^^^ unknown filter
"#;
        let filter = extract_filter_from_display(display);
        assert_eq!(filter, Some("toyml".to_string()));
    }

    #[test]
    fn test_render_issue_warning() {
        let issue = RenderIssue::warning("files_api", "Files API unavailable");
        assert_eq!(issue.category, "files_api");
        assert_eq!(issue.message, "Files API unavailable");
        assert_eq!(issue.severity, IssueSeverity::Warning);
    }

    #[test]
    fn test_render_issue_error() {
        let issue = RenderIssue::error("subchart", "Failed to load subchart");
        assert_eq!(issue.category, "subchart");
        assert_eq!(issue.severity, IssueSeverity::Error);
    }

    #[test]
    fn test_render_report_add_warning() {
        let mut report = RenderReport::new();
        report.add_warning("test_category", "test warning message");

        assert!(report.has_warnings());
        assert!(report.has_issues());
        assert!(!report.has_errors()); // Template errors, not issues

        let warnings: Vec<_> = report.warnings().collect();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].category, "test_category");
        assert_eq!(warnings[0].message, "test warning message");
    }

    #[test]
    fn test_render_report_summary_with_warnings() {
        let mut report = RenderReport::new();
        report.add_error("a.yaml".to_string(), TemplateError::simple("error"));
        report.add_warning("files_api", "Files unavailable");

        let summary = report.summary();
        assert!(summary.contains("1 error"));
        assert!(summary.contains("1 warning"));
    }

    #[test]
    fn test_render_report_multiple_warnings() {
        let mut report = RenderReport::new();
        report.add_warning("files_api", "warning 1");
        report.add_warning("subchart", "warning 2");
        report.add_issue(RenderIssue::error("critical", "an error"));

        assert_eq!(report.warnings().count(), 2);
        assert_eq!(report.issues.len(), 3);
    }
}