tron 2.1.0

A rust based template system built for speed and simplicity.
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
//! Template validation and linting functionality.
//!
//! This module provides comprehensive validation and linting capabilities for
//! Tron templates, helping developers catch issues early and maintain high-quality
//! template code.
//!
//! # Features
//!
//! - **Syntax Validation**: Check template syntax for common errors
//! - **Placeholder Analysis**: Detect unused, undefined, or problematic placeholders
//! - **Best Practice Linting**: Suggest improvements and flag potential issues
//! - **Circular Reference Detection**: Prevent infinite template composition loops
//! - **Performance Hints**: Identify potential performance bottlenecks
//!
//! # Examples
//!
//! Basic validation:
//!
//! ```
//! use tron::{TronTemplate, validation::TemplateValidator};
//!
//! let template = TronTemplate::new("fn @[name]@() { @[body]@ }").unwrap();
//! let validator = TemplateValidator::new();
//! let report = validator.validate(&template).unwrap();
//!
//! if report.has_issues() {
//!     for issue in report.issues() {
//!         println!("Issue: {}", issue.message());
//!     }
//! }
//! ```

use std::collections::HashMap;
use crate::error::Result;
use crate::template::TronTemplate;
use crate::template_ref::TronRef;

/// Severity levels for validation issues.
///
/// These levels help categorize the importance of different validation findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
    /// Informational messages that don't indicate problems
    Info,
    /// Warnings about potential issues or best practices
    Warning,
    /// Errors that must be fixed for the template to work correctly
    Error,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Info => write!(f, "INFO"),
            Severity::Warning => write!(f, "WARNING"),
            Severity::Error => write!(f, "ERROR"),
        }
    }
}

/// Categories of validation issues.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IssueCategory {
    /// Syntax-related issues
    Syntax,
    /// Placeholder-related issues
    Placeholder,
    /// Performance-related concerns
    Performance,
    /// Best practice violations
    Style,
    /// Security-related concerns
    Security,
}

impl std::fmt::Display for IssueCategory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IssueCategory::Syntax => write!(f, "Syntax"),
            IssueCategory::Placeholder => write!(f, "Placeholder"),
            IssueCategory::Performance => write!(f, "Performance"),
            IssueCategory::Style => write!(f, "Style"),
            IssueCategory::Security => write!(f, "Security"),
        }
    }
}

/// A single validation issue found in a template.
///
/// Each issue contains information about the problem, its severity,
/// and optionally the location where it was found.
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    severity: Severity,
    category: IssueCategory,
    message: String,
    line: Option<usize>,
    column: Option<usize>,
    suggestion: Option<String>,
}

impl ValidationIssue {
    /// Create a new validation issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{ValidationIssue, Severity, IssueCategory};
    ///
    /// let issue = ValidationIssue::new(
    ///     Severity::Warning,
    ///     IssueCategory::Style,
    ///     "Consider using descriptive placeholder names"
    /// );
    /// ```
    pub fn new<S: Into<String>>(severity: Severity, category: IssueCategory, message: S) -> Self {
        Self {
            severity,
            category,
            message: message.into(),
            line: None,
            column: None,
            suggestion: None,
        }
    }

    /// Set the line number where the issue was found.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{ValidationIssue, Severity, IssueCategory};
    ///
    /// let issue = ValidationIssue::new(Severity::Error, IssueCategory::Syntax, "Invalid syntax")
    ///     .with_line(5);
    /// ```
    pub fn with_line(mut self, line: usize) -> Self {
        self.line = Some(line);
        self
    }

    /// Set the column number where the issue was found.
    pub fn with_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }

    /// Add a suggestion for fixing the issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{ValidationIssue, Severity, IssueCategory};
    ///
    /// let issue = ValidationIssue::new(Severity::Warning, IssueCategory::Style, "Short placeholder name")
    ///     .with_suggestion("Consider using a more descriptive name like 'function_name'");
    /// ```
    pub fn with_suggestion<S: Into<String>>(mut self, suggestion: S) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }

    /// Get the issue severity.
    pub fn severity(&self) -> Severity {
        self.severity
    }

    /// Get the issue category.
    pub fn category(&self) -> &IssueCategory {
        &self.category
    }

    /// Get the issue message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Get the line number if available.
    pub fn line(&self) -> Option<usize> {
        self.line
    }

    /// Get the column number if available.
    pub fn column(&self) -> Option<usize> {
        self.column
    }

    /// Get the suggestion if available.
    pub fn suggestion(&self) -> Option<&str> {
        self.suggestion.as_deref()
    }
}

impl std::fmt::Display for ValidationIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}: {}", self.severity, self.category, self.message)?;
        
        if let (Some(line), Some(column)) = (self.line, self.column) {
            write!(f, " (line {}, column {})", line, column)?;
        } else if let Some(line) = self.line {
            write!(f, " (line {})", line)?;
        }
        
        if let Some(suggestion) = &self.suggestion {
            write!(f, "\n  Suggestion: {}", suggestion)?;
        }
        
        Ok(())
    }
}

/// Validation report containing all issues found during template validation.
#[derive(Debug)]
pub struct ValidationReport {
    issues: Vec<ValidationIssue>,
    template_path: Option<String>,
}

impl ValidationReport {
    /// Create a new empty validation report.
    pub fn new() -> Self {
        Self {
            issues: Vec::new(),
            template_path: None,
        }
    }

    /// Set the template path for this report.
    pub fn with_path<S: Into<String>>(mut self, path: S) -> Self {
        self.template_path = Some(path.into());
        self
    }

    /// Add an issue to the report.
    pub fn add_issue(&mut self, issue: ValidationIssue) {
        self.issues.push(issue);
    }

    /// Check if the report has any issues.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{ValidationReport, ValidationIssue, Severity, IssueCategory};
    ///
    /// let mut report = ValidationReport::new();
    /// assert!(!report.has_issues());
    ///
    /// report.add_issue(ValidationIssue::new(Severity::Warning, IssueCategory::Style, "Style issue"));
    /// assert!(report.has_issues());
    /// ```
    pub fn has_issues(&self) -> bool {
        !self.issues.is_empty()
    }

    /// Check if the report has any errors (not just warnings or info).
    pub fn has_errors(&self) -> bool {
        self.issues.iter().any(|issue| issue.severity == Severity::Error)
    }

    /// Get all issues in the report.
    pub fn issues(&self) -> &[ValidationIssue] {
        &self.issues
    }

    /// Get issues filtered by severity.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{ValidationReport, ValidationIssue, Severity, IssueCategory};
    ///
    /// let mut report = ValidationReport::new();
    /// report.add_issue(ValidationIssue::new(Severity::Error, IssueCategory::Syntax, "Error"));
    /// report.add_issue(ValidationIssue::new(Severity::Warning, IssueCategory::Style, "Warning"));
    ///
    /// let errors = report.issues_by_severity(Severity::Error);
    /// assert_eq!(errors.len(), 1);
    /// ```
    pub fn issues_by_severity(&self, severity: Severity) -> Vec<&ValidationIssue> {
        self.issues.iter()
            .filter(|issue| issue.severity == severity)
            .collect()
    }

    /// Get issues filtered by category.
    pub fn issues_by_category(&self, category: &IssueCategory) -> Vec<&ValidationIssue> {
        self.issues.iter()
            .filter(|issue| &issue.category == category)
            .collect()
    }

    /// Get the template path if set.
    pub fn template_path(&self) -> Option<&str> {
        self.template_path.as_deref()
    }

    /// Count issues by severity level.
    pub fn count_by_severity(&self) -> HashMap<Severity, usize> {
        let mut counts = HashMap::new();
        for issue in &self.issues {
            *counts.entry(issue.severity).or_insert(0) += 1;
        }
        counts
    }
}

impl Default for ValidationReport {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for ValidationReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(path) = &self.template_path {
            writeln!(f, "Validation Report for: {}", path)?;
        } else {
            writeln!(f, "Validation Report:")?;
        }

        if self.issues.is_empty() {
            writeln!(f, "✓ No issues found")?;
        } else {
            let counts = self.count_by_severity();
            writeln!(f, "Found {} issue(s):", self.issues.len())?;
            
            for (severity, count) in counts {
                writeln!(f, "  {} {}: {}", 
                    match severity {
                        Severity::Error => "",
                        Severity::Warning => "⚠️",
                        Severity::Info => "ℹ️",
                    },
                    severity, count)?;
            }
            writeln!(f)?;

            for (index, issue) in self.issues.iter().enumerate() {
                writeln!(f, "{}. {}", index + 1, issue)?;
            }
        }

        Ok(())
    }
}

/// Configuration for template validation.
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Check for placeholder naming conventions
    pub check_placeholder_naming: bool,
    /// Minimum length for placeholder names
    pub min_placeholder_length: usize,
    /// Check for unused placeholders
    pub check_unused_placeholders: bool,
    /// Check for security issues
    pub check_security: bool,
    /// Check for performance issues
    pub check_performance: bool,
    /// Maximum nesting depth for templates
    pub max_nesting_depth: usize,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            check_placeholder_naming: true,
            min_placeholder_length: 2,
            check_unused_placeholders: true,
            check_security: true,
            check_performance: true,
            max_nesting_depth: 10,
        }
    }
}

/// Template validator for checking template quality and correctness.
///
/// The validator can check for various issues including syntax errors,
/// placeholder problems, security concerns, and style violations.
///
/// # Examples
///
/// Basic validation:
///
/// ```
/// use tron::{TronTemplate, validation::TemplateValidator};
///
/// let template = TronTemplate::new("fn @[name]@() { @[body]@ }").unwrap();
/// let validator = TemplateValidator::new();
/// let report = validator.validate(&template).unwrap();
///
/// println!("{}", report);
/// ```
///
/// Custom configuration:
///
/// ```
/// use tron::validation::{TemplateValidator, ValidationConfig};
///
/// let mut config = ValidationConfig::default();
/// config.min_placeholder_length = 3;
/// config.check_security = false;
///
/// let validator = TemplateValidator::with_config(config);
/// ```
#[derive(Debug)]
pub struct TemplateValidator {
    config: ValidationConfig,
}

impl TemplateValidator {
    /// Create a new validator with default configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::TemplateValidator;
    ///
    /// let validator = TemplateValidator::new();
    /// ```
    pub fn new() -> Self {
        Self {
            config: ValidationConfig::default(),
        }
    }

    /// Create a validator with custom configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::validation::{TemplateValidator, ValidationConfig};
    ///
    /// let mut config = ValidationConfig::default();
    /// config.min_placeholder_length = 3;
    ///
    /// let validator = TemplateValidator::with_config(config);
    /// ```
    pub fn with_config(config: ValidationConfig) -> Self {
        Self { config }
    }

    /// Validate a template and return a report.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::{TronTemplate, validation::TemplateValidator};
    ///
    /// let template = TronTemplate::new("Hello @[n]@!").unwrap();
    /// let validator = TemplateValidator::new();
    /// let report = validator.validate(&template).unwrap();
    ///
    /// // This will flag 'n' as a short placeholder name
    /// assert!(report.has_issues());
    /// ```
    pub fn validate(&self, template: &TronTemplate) -> Result<ValidationReport> {
        let mut report = ValidationReport::new();
        
        if let Some(path) = template.path() {
            report = report.with_path(path.to_string_lossy().to_string());
        }

        self.check_placeholder_issues(template, &mut report)?;
        self.check_style_issues(template, &mut report)?;
        
        if self.config.check_security {
            self.check_security_issues(template, &mut report)?;
        }
        
        if self.config.check_performance {
            self.check_performance_issues(template, &mut report)?;
        }

        Ok(report)
    }

    /// Validate a template reference.
    pub fn validate_ref(&self, template_ref: &TronRef) -> Result<ValidationReport> {
        self.validate(template_ref.inner())
    }

    /// Check for circular references in template composition.
    ///
    /// This is a static analysis that checks if templates could potentially
    /// create infinite loops when composed together.
    pub fn check_circular_references(&self, templates: &[&TronTemplate]) -> Result<ValidationReport> {
        let mut report = ValidationReport::new();
        let mut dependency_graph = HashMap::new();
        
        // Build dependency graph (simplified - would need more complex analysis for real circular detection)
        for template in templates {
            let placeholders = template.placeholder_names();
            let content = template.content();
            
            for placeholder in placeholders {
                // Check if this placeholder might reference another template
                if content.contains(&format!("@[{}]@", placeholder)) {
                    // This is a simplified check - real implementation would be more sophisticated
                    dependency_graph.entry(template.content().clone())
                        .or_insert_with(Vec::new)
                        .push(placeholder);
                }
            }
        }

        // For now, just warn about potential issues
        if dependency_graph.len() > 1 {
            report.add_issue(ValidationIssue::new(
                Severity::Info,
                IssueCategory::Performance,
                "Multiple templates detected - consider checking for circular references manually"
            ));
        }

        Ok(report)
    }

    fn check_placeholder_issues(&self, template: &TronTemplate, report: &mut ValidationReport) -> Result<()> {
        let placeholders = template.placeholder_names();
        
        if self.config.check_placeholder_naming {
            for placeholder in &placeholders {
                // Check minimum length
                if placeholder.len() < self.config.min_placeholder_length {
                    report.add_issue(ValidationIssue::new(
                        Severity::Warning,
                        IssueCategory::Style,
                        format!("Placeholder '{}' is shorter than recommended minimum of {} characters", 
                            placeholder, self.config.min_placeholder_length)
                    ).with_suggestion("Consider using more descriptive placeholder names"));
                }

                // Check naming convention
                if placeholder.chars().any(|c| c.is_uppercase()) {
                    report.add_issue(ValidationIssue::new(
                        Severity::Warning,
                        IssueCategory::Style,
                        format!("Placeholder '{}' contains uppercase letters", placeholder)
                    ).with_suggestion("Consider using snake_case for placeholder names"));
                }

                // Check for numbers only
                if placeholder.chars().all(|c| c.is_numeric()) {
                    report.add_issue(ValidationIssue::new(
                        Severity::Warning,
                        IssueCategory::Style,
                        format!("Placeholder '{}' consists only of numbers", placeholder)
                    ).with_suggestion("Consider using descriptive names instead of just numbers"));
                }
                // Check for invalid characters (whitespace or non-identifier)
                if placeholder.chars().any(char::is_whitespace) || !placeholder.chars().all(|c| c == '_' || c.is_ascii_alphanumeric()) {
                    report.add_issue(ValidationIssue::new(
                        Severity::Error,
                        IssueCategory::Syntax,
                        format!("Placeholder '{}' contains invalid characters (whitespace or non-identifier)", placeholder)
                    ).with_suggestion("Use only letters, numbers, and underscores in placeholder names"));
                }
            }
        }

        // Check for empty placeholders that might be missed
        let content = template.content();
        if content.contains("@@") {
            report.add_issue(ValidationIssue::new(
                Severity::Error,
                IssueCategory::Syntax,
                "Found '@@' which might indicate a malformed placeholder"
            ).with_suggestion("Check for missing brackets in placeholder syntax"));
        }

        Ok(())
    }

    fn check_style_issues(&self, template: &TronTemplate, report: &mut ValidationReport) -> Result<()> {
        let content = template.content();
        
        // Check for trailing whitespace in lines
        for (line_num, line) in content.lines().enumerate() {
            if line.ends_with(' ') || line.ends_with('\t') {
                report.add_issue(ValidationIssue::new(
                    Severity::Warning,
                    IssueCategory::Style,
                    "Line has trailing whitespace"
                ).with_line(line_num + 1)
                .with_suggestion("Remove trailing whitespace"));
            }
        }

        // Check for inconsistent indentation (mixing tabs and spaces)
        let has_tabs = content.contains('\t');
        let has_space_indent = content.lines().any(|line| line.starts_with("  "));
        
        if has_tabs && has_space_indent {
            report.add_issue(ValidationIssue::new(
                Severity::Warning,
                IssueCategory::Style,
                "Inconsistent indentation detected (mixing tabs and spaces)"
            ).with_suggestion("Use consistent indentation throughout the template"));
        }

        Ok(())
    }

    fn check_security_issues(&self, template: &TronTemplate, report: &mut ValidationReport) -> Result<()> {
        let content = template.content();
        
        // Check for potential injection patterns
        let suspicious_patterns = [
            "eval(",
            "exec(",
            "system(",
            "shell_exec(",
            "<script",
            "javascript:",
        ];
        
        for pattern in &suspicious_patterns {
            if content.to_lowercase().contains(pattern) {
                report.add_issue(ValidationIssue::new(
                    Severity::Warning,
                    IssueCategory::Security,
                    format!("Found potentially unsafe pattern: '{}'", pattern)
                ).with_suggestion("Review for potential security implications"));
            }
        }

        // Check for hardcoded secrets patterns (simplified patterns)
        let secret_keywords = ["password", "api_key", "apikey", "secret", "token"];
        
        let lower_content = content.to_lowercase();
        for keyword in &secret_keywords {
            if lower_content.contains(&format!("{}=", keyword)) || 
               lower_content.contains(&format!("{} =", keyword)) {
                report.add_issue(ValidationIssue::new(
                    Severity::Warning,
                    IssueCategory::Security,
                    format!("Found potential hardcoded secret with keyword '{}'", keyword)
                ).with_suggestion("Consider using placeholders for sensitive values"));
            }
        }

        Ok(())
    }

    fn check_performance_issues(&self, template: &TronTemplate, report: &mut ValidationReport) -> Result<()> {
        let content = template.content();
        let placeholder_count = template.placeholder_names().len();
        
        // Check for excessive placeholder count
        if placeholder_count > 50 {
            report.add_issue(ValidationIssue::new(
                Severity::Warning,
                IssueCategory::Performance,
                format!("Template has {} placeholders, which might impact performance", placeholder_count)
            ).with_suggestion("Consider breaking down into smaller templates or using template composition"));
        }

        // Check template size
        if content.len() > 10000 {
            report.add_issue(ValidationIssue::new(
                Severity::Info,
                IssueCategory::Performance,
                format!("Large template size ({} characters)", content.len())
            ).with_suggestion("Consider breaking down into smaller, more manageable templates"));
        }

        // Check for potential regex performance issues (simplified)
        if content.contains("@[") && (content.contains("*") || content.contains("+")) {
            report.add_issue(ValidationIssue::new(
                Severity::Info,
                IssueCategory::Performance,
                "Template contains both placeholders and regex-like characters"
            ).with_suggestion("Ensure placeholder names don't contain complex regex patterns"));
        }

        Ok(())
    }
}

impl Default for TemplateValidator {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_validation_issue_creation() {
        let issue = ValidationIssue::new(
            Severity::Warning,
            IssueCategory::Style,
            "Test issue"
        ).with_line(5)
        .with_suggestion("Fix it");

        assert_eq!(issue.severity(), Severity::Warning);
        assert_eq!(issue.category(), &IssueCategory::Style);
        assert_eq!(issue.message(), "Test issue");
        assert_eq!(issue.line(), Some(5));
        assert_eq!(issue.suggestion(), Some("Fix it"));
    }

    #[test]
    fn test_validation_report() {
        let mut report = ValidationReport::new();
        assert!(!report.has_issues());
        assert!(!report.has_errors());

        report.add_issue(ValidationIssue::new(
            Severity::Warning,
            IssueCategory::Style,
            "Warning"
        ));
        
        assert!(report.has_issues());
        assert!(!report.has_errors());

        report.add_issue(ValidationIssue::new(
            Severity::Error,
            IssueCategory::Syntax,
            "Error"
        ));
        
        assert!(report.has_errors());
        assert_eq!(report.issues().len(), 2);
    }

    #[test]
    fn test_template_validation() -> Result<()> {
        let template = TronTemplate::new("Hello @[n]@!")?;
        let validator = TemplateValidator::new();
        let report = validator.validate(&template)?;

        // Should flag 'n' as a short placeholder name
        assert!(report.has_issues());
        
        let warnings = report.issues_by_severity(Severity::Warning);
        assert!(!warnings.is_empty());
        Ok(())
    }

    #[test]
    fn test_good_template_validation() -> Result<()> {
        let template = TronTemplate::new("Hello @[user_name]@! Welcome to @[application_name]@.")?;
        let validator = TemplateValidator::new();
        let report = validator.validate(&template)?;

        // Good template should have minimal or no issues
        assert!(!report.has_errors());
        Ok(())
    }

    #[test]
    fn test_security_validation() -> Result<()> {
        let template = TronTemplate::new("function test() { eval(@[code]@); }")?;
        let validator = TemplateValidator::new();
        let report = validator.validate(&template)?;

        let security_issues = report.issues_by_category(&IssueCategory::Security);
        assert!(!security_issues.is_empty());
        Ok(())
    }

    #[test]
    fn test_custom_config() -> Result<()> {
        let mut config = ValidationConfig::default();
        config.min_placeholder_length = 5;

        let template = TronTemplate::new("Hello @[name]@!")?; // 'name' is 4 chars
        let validator = TemplateValidator::with_config(config);
        let report = validator.validate(&template)?;

        // Should flag 'name' as too short with min length 5
        assert!(report.has_issues());
        Ok(())
    }
}