rust-guardian 0.1.1

Dynamic code quality enforcement preventing incomplete or placeholder code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! Rust Guardian CLI - Command-line interface for code quality enforcement
//!
//! Architecture: Application Layer - CLI coordinates user interactions with domain services
//! - Translates user commands to domain operations  
//! - Handles external concerns like file I/O, process exit codes, and terminal output
//! - Provides clean separation between user interface and business logic

use clap::{Parser, Subcommand, ValueEnum};
use rust_guardian::{
    AnalysisOptions, GuardianConfig, GuardianError, GuardianResult, GuardianValidator,
    OutputFormat, ReportOptions, Severity, ValidationOptions,
};
use std::path::{Path, PathBuf};
use std::process;

/// Rust Guardian - Dynamic code quality enforcement
#[derive(Parser)]
#[command(name = "rust-guardian")]
#[command(version = "0.1.1")]
#[command(about = "Dynamic code quality enforcement preventing incomplete or placeholder code")]
#[command(
    long_about = "Rust Guardian analyzes code for quality violations, placeholder implementations, and architectural compliance. Designed for autonomous agent workflows and CI/CD integration."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose logging
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Configuration file path
    #[arg(short, long, global = true)]
    config: Option<PathBuf>,

    /// Disable colored output
    #[arg(long, global = true)]
    no_color: bool,
}

#[derive(Subcommand)]
enum Commands {
    /// Check files for code quality violations
    Check {
        /// Paths to analyze (files or directories)
        paths: Vec<PathBuf>,

        /// Output format
        #[arg(short, long, value_enum, default_value = "human")]
        format: OutputFormatArg,

        /// Minimum severity level to report
        #[arg(short, long, value_enum)]
        severity: Option<SeverityArg>,

        /// Maximum number of violations to report
        #[arg(long)]
        max_violations: Option<usize>,

        /// Additional exclude patterns
        #[arg(long, action = clap::ArgAction::Append)]
        exclude: Vec<String>,

        /// Ignore .guardianignore files
        #[arg(long)]
        no_ignore: bool,

        /// Custom .guardianignore file
        #[arg(long)]
        guardianignore: Option<PathBuf>,

        /// Disable parallel processing
        #[arg(long)]
        no_parallel: bool,

        /// Fail on first error
        #[arg(long)]
        fail_fast: bool,

        /// Enable caching for better performance
        #[arg(long)]
        cache: bool,

        /// Custom cache file path
        #[arg(long)]
        cache_file: Option<PathBuf>,
    },

    /// Watch for file changes and run checks automatically
    Watch {
        /// Path to watch (defaults to current directory)
        path: Option<PathBuf>,

        /// File patterns to watch (glob patterns)
        #[arg(short, long, action = clap::ArgAction::Append)]
        pattern: Vec<String>,

        /// Debounce delay in milliseconds
        #[arg(long, default_value = "500")]
        delay: u64,
    },

    /// Validate configuration file
    ValidateConfig {
        /// Configuration file to validate
        config_file: Option<PathBuf>,
    },

    /// Explain what a specific rule does
    Explain {
        /// Rule ID to explain
        rule_id: String,
    },

    /// Show cache statistics
    Cache {
        #[command(subcommand)]
        action: CacheCommands,
    },

    /// List available rules and patterns
    Rules {
        /// Show only enabled rules
        #[arg(long)]
        enabled_only: bool,

        /// Filter by category
        #[arg(long)]
        category: Option<String>,
    },
}

#[derive(Subcommand)]
enum CacheCommands {
    /// Show cache statistics
    Stats {
        /// Cache file path
        #[arg(long)]
        cache_file: Option<PathBuf>,
    },

    /// Clear the cache
    Clear {
        /// Cache file path
        #[arg(long)]
        cache_file: Option<PathBuf>,
    },

    /// Clean up stale cache entries
    Cleanup {
        /// Cache file path
        #[arg(long)]
        cache_file: Option<PathBuf>,
    },
}

#[derive(Copy, Clone, ValueEnum, PartialEq)]
enum OutputFormatArg {
    Human,
    Json,
    Junit,
    Sarif,
    Github,
    Agent,
}

impl From<OutputFormatArg> for OutputFormat {
    fn from(arg: OutputFormatArg) -> Self {
        match arg {
            OutputFormatArg::Human => OutputFormat::Human,
            OutputFormatArg::Json => OutputFormat::Json,
            OutputFormatArg::Junit => OutputFormat::Junit,
            OutputFormatArg::Sarif => OutputFormat::Sarif,
            OutputFormatArg::Github => OutputFormat::GitHub,
            OutputFormatArg::Agent => OutputFormat::Agent,
        }
    }
}

#[derive(Clone, ValueEnum)]
enum SeverityArg {
    Info,
    Warning,
    Error,
}

impl From<SeverityArg> for Severity {
    fn from(arg: SeverityArg) -> Self {
        match arg {
            SeverityArg::Info => Severity::Info,
            SeverityArg::Warning => Severity::Warning,
            SeverityArg::Error => Severity::Error,
        }
    }
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();

    // Initialize logging
    init_logging(cli.verbose);

    // Run the command and handle the result
    let result = run_command(cli).await;

    match result {
        Ok(exit_code) => {
            process::exit(exit_code);
        }
        Err(e) => {
            eprintln!("Error: {e}");
            process::exit(1);
        }
    }
}

async fn run_command(cli: Cli) -> GuardianResult<i32> {
    match cli.command {
        Commands::Check {
            paths,
            format,
            severity,
            max_violations,
            exclude,
            no_ignore,
            guardianignore: _guardianignore,
            no_parallel,
            fail_fast,
            cache,
            cache_file,
        } => {
            run_check(
                cli.config,
                paths,
                format,
                severity,
                max_violations,
                exclude,
                no_ignore,
                no_parallel,
                fail_fast,
                cache,
                cache_file,
                !cli.no_color,
            )
            .await
        }
        Commands::Watch {
            path,
            pattern,
            delay,
        } => run_watch(path, pattern, delay).await,
        Commands::ValidateConfig { config_file } => run_validate_config(config_file.or(cli.config)),
        Commands::Explain { rule_id } => run_explain(rule_id),
        Commands::Cache { action } => run_cache_command(action).await,
        Commands::Rules {
            enabled_only,
            category,
        } => run_list_rules(cli.config, enabled_only, category),
    }
}

#[allow(clippy::too_many_arguments)]
async fn run_check(
    config_path: Option<PathBuf>,
    paths: Vec<PathBuf>,
    format: OutputFormatArg,
    severity: Option<SeverityArg>,
    max_violations: Option<usize>,
    exclude_patterns: Vec<String>,
    no_ignore: bool,
    no_parallel: bool,
    fail_fast: bool,
    use_cache: bool,
    cache_file: Option<PathBuf>,
    use_colors: bool,
) -> GuardianResult<i32> {
    // Load configuration
    let config = if let Some(config_path) = config_path {
        GuardianConfig::load_from_file(config_path)?
    } else {
        // Try to find default config file
        let default_configs = ["guardian.yaml", "guardian.yml", ".guardian.yaml"];
        let mut config = None;

        for config_name in &default_configs {
            if Path::new(config_name).exists() {
                config = Some(GuardianConfig::load_from_file(config_name)?);
                break;
            }
        }

        config.unwrap_or_else(GuardianConfig::default)
    };

    // Create validator
    let mut validator = GuardianValidator::new_with_config(config)?;

    // Enable cache if requested
    if use_cache {
        let cache_path =
            cache_file.unwrap_or_else(|| PathBuf::from(".rust").join("guardian_cache.json"));
        validator = validator.with_cache(cache_path)?;
    }

    // Use current directory if no paths specified
    let paths = if paths.is_empty() {
        vec![PathBuf::from(".")]
    } else {
        paths
    };

    // Set up validation options
    let validation_options = ValidationOptions {
        use_cache,
        output_format: format.into(),
        report_options: ReportOptions {
            use_colors,
            max_violations,
            min_severity: severity.map(|s| s.into()),
            ..Default::default()
        },
        analysis_options: AnalysisOptions {
            parallel: !no_parallel,
            fail_fast,
            exclude_patterns,
            ignore_ignore_files: no_ignore,
            ..Default::default()
        },
        ..Default::default()
    };

    // Run validation
    let report = validator
        .validate_with_options(paths, &validation_options)
        .await?;

    // Format and output results
    let formatted = validator.format_report(&report, format.into())?;
    println!("{formatted}");

    // Print cache statistics if caching is enabled
    if use_cache {
        if let Some(stats) = validator.cache_statistics() {
            if format == OutputFormatArg::Human {
                eprintln!("\n{}", stats.format_display());
            }
        }
    }

    // Save cache if enabled
    if use_cache {
        validator.save_cache()?;
    }

    // Return appropriate exit code
    if report.has_errors() {
        Ok(1) // Exit code 1 for errors
    } else {
        Ok(0) // Exit code 0 for success
    }
}

async fn run_watch(
    path: Option<PathBuf>,
    patterns: Vec<String>,
    delay_ms: u64,
) -> GuardianResult<i32> {
    use notify::{Event, RecursiveMode, Result as NotifyResult, Watcher};
    use std::io::{self, Write};
    use std::sync::mpsc;
    use std::thread;
    use std::time::Duration;

    let watch_path = path.unwrap_or_else(|| PathBuf::from("."));

    println!("🔍 Starting Rust Guardian watch mode...");
    println!("📂 Watching: {}", watch_path.display());

    // Set up file patterns to watch (default to Rust files if none specified)
    let watch_patterns = if patterns.is_empty() {
        vec!["**/*.rs".to_string()]
    } else {
        patterns
    };

    println!("🎯 Patterns: {}", watch_patterns.join(", "));
    println!("⏱️  Debounce delay: {delay_ms}ms");
    println!("Press Ctrl+C to stop watching\\n");

    // Create a channel for file system events
    let (tx, rx) = mpsc::channel();

    // Create a watcher
    let mut watcher = notify::recommended_watcher(move |res: NotifyResult<Event>| match res {
        Ok(event) => {
            if let Err(e) = tx.send(event) {
                eprintln!("Error sending event: {e}");
            }
        }
        Err(e) => eprintln!("Watch error: {e}"),
    })
    .map_err(|e| GuardianError::config(format!("Failed to create file watcher: {e}")))?;

    // Start watching the path
    watcher
        .watch(&watch_path, RecursiveMode::Recursive)
        .map_err(|e| {
            GuardianError::config(format!(
                "Failed to watch path '{}': {}",
                watch_path.display(),
                e
            ))
        })?;

    // Track last run to implement debouncing
    let mut last_run = std::time::Instant::now();
    let debounce_duration = Duration::from_millis(delay_ms);

    // Run initial check
    println!("🚀 Running initial analysis...");
    run_watch_analysis_with_config(&watch_path, &watch_patterns, None).await?;

    // Main event loop
    loop {
        match rx.recv_timeout(Duration::from_millis(100)) {
            Ok(event) => {
                // Check for config file changes first
                if let Some(config_path) = is_config_change(&event) {
                    println!("🔄 Configuration file changed: {}", config_path.display());
                    println!("📝 Reloading configuration and running analysis...");

                    // Clear terminal and run analysis with new config
                    print!("\\x1B[2J\\x1B[H"); // Clear screen and move cursor to top
                    io::stdout().flush().unwrap();

                    if let Err(e) = run_watch_analysis_with_config(
                        &watch_path,
                        &watch_patterns,
                        Some(&config_path),
                    )
                    .await
                    {
                        eprintln!("❌ Config reload and analysis failed: {e}");
                    }
                    last_run = std::time::Instant::now();
                }
                // Otherwise check for regular file changes
                else if should_trigger_analysis(&event, &watch_patterns) {
                    let now = std::time::Instant::now();
                    if now.duration_since(last_run) >= debounce_duration {
                        // Clear terminal and run analysis
                        print!("\\x1B[2J\\x1B[H"); // Clear screen and move cursor to top
                        io::stdout().flush().unwrap();

                        println!("📝 File changes detected, running analysis...");
                        if let Err(e) =
                            run_watch_analysis_with_config(&watch_path, &watch_patterns, None).await
                        {
                            eprintln!("❌ Analysis failed: {e}");
                        }
                        last_run = now;
                    }
                }
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {
                // No events - continue watching
                continue;
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                eprintln!("File watcher disconnected");
                break;
            }
        }

        // Small delay to prevent excessive CPU usage
        thread::sleep(Duration::from_millis(10));
    }

    Ok(0)
}

/// Check if an event should trigger analysis or config reload
fn should_trigger_analysis(event: &notify::Event, patterns: &[String]) -> bool {
    use notify::EventKind;

    // Only trigger on write/create/rename events
    match event.kind {
        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) => {}
        _ => return false,
    }

    // Check if any affected path matches our patterns
    for path in &event.paths {
        let path_str = path.to_string_lossy();

        for pattern in patterns {
            if let Ok(glob_pattern) = glob::Pattern::new(pattern) {
                if glob_pattern.matches(&path_str) {
                    return true;
                }
            }
        }
    }

    false
}

/// Check if an event indicates a config file change
fn is_config_change(event: &notify::Event) -> Option<PathBuf> {
    use notify::EventKind;

    // Only trigger on write/create/rename events
    match event.kind {
        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) => {}
        _ => return None,
    }

    // Check if any affected path is a config file
    for path in &event.paths {
        let file_name = path.file_name()?.to_str()?;

        // Check for common config file names
        if matches!(
            file_name,
            "guardian.yaml" | "guardian.yml" | ".guardian.yaml" | ".guardian.yml"
        ) {
            return Some(path.clone());
        }
    }

    None
}

/// Run analysis for watch mode with optional config file
async fn run_watch_analysis_with_config(
    watch_path: &Path,
    _patterns: &[String],
    config_path: Option<&Path>,
) -> GuardianResult<()> {
    // Load configuration
    let config = if let Some(config_path) = config_path {
        match GuardianConfig::load_from_file(config_path) {
            Ok(config) => {
                println!("✅ Configuration reloaded from: {}", config_path.display());
                config
            }
            Err(e) => {
                eprintln!(
                    "⚠️  Failed to reload config from {}: {}",
                    config_path.display(),
                    e
                );
                eprintln!("   Using default configuration instead...");
                GuardianConfig::default()
            }
        }
    } else {
        // Try to find default config file
        let default_configs = ["guardian.yaml", "guardian.yml", ".guardian.yaml"];
        let mut config = None;

        for config_name in &default_configs {
            if Path::new(config_name).exists() {
                match GuardianConfig::load_from_file(config_name) {
                    Ok(loaded_config) => {
                        config = Some(loaded_config);
                        break;
                    }
                    Err(e) => {
                        eprintln!("⚠️  Failed to load config from {config_name}: {e}");
                        continue;
                    }
                }
            }
        }

        config.unwrap_or_else(GuardianConfig::default)
    };

    // Create validator
    let mut validator = GuardianValidator::new_with_config(config)?;

    // Set up validation options for watch mode
    let validation_options = ValidationOptions {
        analysis_options: AnalysisOptions {
            parallel: true,
            fail_fast: false,
            exclude_patterns: vec![], // Use default exclusions
            ..Default::default()
        },
        report_options: ReportOptions {
            use_colors: true,
            show_suggestions: true,
            ..Default::default()
        },
        output_format: OutputFormat::Human,
        ..Default::default()
    };

    // Run validation
    match validator
        .validate_with_options(vec![watch_path], &validation_options)
        .await
    {
        Ok(report) => {
            if report.has_violations() {
                let formatted = validator.format_report(&report, OutputFormat::Human)?;
                println!("{formatted}");

                let error_count = report.summary.violations_by_severity.error;
                let warning_count = report.summary.violations_by_severity.warning;
                let info_count = report.summary.violations_by_severity.info;

                if error_count > 0 {
                    println!(
                        "\\n❌ Found {} error{}, {} warning{}, {} info",
                        error_count,
                        if error_count == 1 { "" } else { "s" },
                        warning_count,
                        if warning_count == 1 { "" } else { "s" },
                        info_count
                    );
                } else if warning_count > 0 {
                    println!(
                        "\\n⚠️  Found {} warning{}, {} info",
                        warning_count,
                        if warning_count == 1 { "" } else { "s" },
                        info_count
                    );
                } else {
                    println!(
                        "\\n✅ Found {} info message{}",
                        info_count,
                        if info_count == 1 { "" } else { "s" }
                    );
                }
            } else {
                println!("✅ No code quality violations found");
            }

            println!(
                "📊 Analyzed {} files in {:.1}s",
                report.summary.total_files,
                report.summary.execution_time_ms as f64 / 1000.0
            );
            println!("⌚ Watching for changes... (Press Ctrl+C to stop)\\n");
        }
        Err(e) => {
            eprintln!("❌ Analysis error: {e}");
        }
    }

    Ok(())
}

fn run_validate_config(config_path: Option<PathBuf>) -> GuardianResult<i32> {
    let config_path = config_path.unwrap_or_else(|| PathBuf::from("guardian.yaml"));

    println!("Validating configuration: {}", config_path.display());

    match GuardianConfig::load_from_file(&config_path) {
        Ok(config) => {
            println!("✅ Configuration is valid");

            // Show some statistics
            let total_categories = config.patterns.len();
            let enabled_categories = config.patterns.values().filter(|c| c.enabled).count();
            let total_rules: usize = config.patterns.values().map(|c| c.rules.len()).sum();
            let enabled_rules: usize = config
                .patterns
                .values()
                .filter(|c| c.enabled)
                .map(|c| c.rules.iter().filter(|r| r.enabled).count())
                .sum();

            println!("📊 Configuration summary:");
            println!("  Categories: {total_categories} total, {enabled_categories} enabled");
            println!("  Rules: {total_rules} total, {enabled_rules} enabled");
            println!("  Path patterns: {}", config.paths.patterns.len());

            Ok(0)
        }
        Err(e) => {
            eprintln!("❌ Configuration validation failed: {e}");
            Ok(1)
        }
    }
}

fn run_explain(rule_id: String) -> GuardianResult<i32> {
    let config = GuardianConfig::default();

    // Find the rule in the configuration
    for (category_name, category) in &config.patterns {
        for rule in &category.rules {
            if rule.id == rule_id {
                println!("📖 Rule: {}", rule.id);
                println!("📂 Category: {category_name}");
                println!(
                    "⚠️ Severity: {:?}",
                    rule.severity.unwrap_or(category.severity)
                );
                println!("🔍 Type: {:?}", rule.rule_type);
                println!("✅ Enabled: {}", rule.enabled);
                println!();
                println!("📝 Description:");
                println!("   {}", rule.message);
                println!();
                println!("🔎 Pattern:");
                println!("   {}", rule.pattern);

                if let Some(exclude) = &rule.exclude_if {
                    println!();
                    println!("🚫 Exclusions:");
                    if let Some(attr) = &exclude.attribute {
                        println!("   Attribute: {attr}");
                    }
                    if exclude.in_tests {
                        println!("   Excluded in test files");
                    }
                    if let Some(patterns) = &exclude.file_patterns {
                        println!("   File patterns: {}", patterns.join(", "));
                    }
                }

                return Ok(0);
            }
        }
    }

    eprintln!("❌ Rule '{rule_id}' not found");
    println!();
    println!("Available rules:");

    for (category_name, category) in &config.patterns {
        println!("  {category_name}:");
        for rule in &category.rules {
            println!("    - {}", rule.id);
        }
    }

    Ok(1)
}

async fn run_cache_command(action: CacheCommands) -> GuardianResult<i32> {
    match action {
        CacheCommands::Stats { cache_file } => {
            let cache_path =
                cache_file.unwrap_or_else(|| PathBuf::from(".rust").join("guardian_cache.json"));

            if !cache_path.exists() {
                println!("No cache file found at {}", cache_path.display());
                return Ok(1);
            }

            let mut cache = rust_guardian::FileCache::new(&cache_path);
            cache.load()?;

            let stats = cache.statistics();
            println!("📊 Cache Statistics");
            println!("   File: {}", cache_path.display());
            println!("   {}", stats.format_display());
            println!("   Created: {}", format_timestamp(stats.created_at));
            println!("   Updated: {}", format_timestamp(stats.updated_at));

            Ok(0)
        }
        CacheCommands::Clear { cache_file } => {
            let cache_path =
                cache_file.unwrap_or_else(|| PathBuf::from(".rust").join("guardian_cache.json"));

            let mut cache = rust_guardian::FileCache::new(&cache_path);
            cache.load()?;
            cache.clear()?;

            println!("✅ Cache cleared: {}", cache_path.display());
            Ok(0)
        }
        CacheCommands::Cleanup { cache_file } => {
            let cache_path =
                cache_file.unwrap_or_else(|| PathBuf::from(".rust").join("guardian_cache.json"));

            if !cache_path.exists() {
                println!("No cache file found at {}", cache_path.display());
                return Ok(1);
            }

            let mut cache = rust_guardian::FileCache::new(&cache_path);
            cache.load()?;
            let removed = cache.cleanup()?;
            cache.save()?;

            println!("✅ Cleaned up {removed} stale cache entries");
            Ok(0)
        }
    }
}

fn run_list_rules(
    config_path: Option<PathBuf>,
    enabled_only: bool,
    category_filter: Option<String>,
) -> GuardianResult<i32> {
    let config = if let Some(path) = config_path {
        GuardianConfig::load_from_file(path)?
    } else {
        // Try to find default config file
        let default_configs = ["guardian.yaml", "guardian.yml", ".guardian.yaml"];
        let mut config = None;

        for config_name in &default_configs {
            if Path::new(config_name).exists() {
                config = Some(GuardianConfig::load_from_file(config_name)?);
                break;
            }
        }

        config.unwrap_or_else(GuardianConfig::default)
    };

    println!("📋 Available Rules\n");

    for (category_name, category) in &config.patterns {
        // Apply category filter
        if let Some(ref filter) = category_filter {
            if category_name != filter {
                continue;
            }
        }

        // Skip disabled categories if enabled_only is true
        if enabled_only && !category.enabled {
            continue;
        }

        let status = if category.enabled { "" } else { "" };
        println!(
            "{}📂 {} ({})",
            status,
            category_name,
            category.severity.as_str()
        );

        for rule in &category.rules {
            // Skip disabled rules if enabled_only is true
            if enabled_only && !rule.enabled {
                continue;
            }

            let rule_status = if rule.enabled { "" } else { "" };
            let severity = rule.severity.unwrap_or(category.severity);

            println!(
                "  {}🔍 {} [{}] - {}",
                rule_status,
                rule.id,
                severity.as_str(),
                rule.message
            );
        }
        println!();
    }

    Ok(0)
}

fn init_logging(verbose: bool) {
    let level = if verbose {
        tracing::Level::DEBUG
    } else {
        tracing::Level::WARN
    };

    tracing_subscriber::fmt()
        .with_max_level(level)
        .with_target(false)
        .init();
}

fn format_timestamp(timestamp: u64) -> String {
    use chrono::{TimeZone, Utc};

    let dt = Utc
        .timestamp_opt(timestamp as i64, 0)
        .single()
        .unwrap_or_else(Utc::now);

    dt.format("%Y-%m-%d %H:%M:%S UTC").to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_check_command() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.rs");

        fs::write(&test_file, "// TODO: implement this\nfn main() {}").unwrap();

        // Create a test config that will detect TODO comments
        let config_file = temp_dir.path().join("test_config.yaml");
        let config = GuardianConfig::default();
        let yaml = serde_yaml::to_string(&config).unwrap();
        fs::write(&config_file, yaml).unwrap();

        // Test basic check with explicit config
        let result = run_check(
            Some(config_file),
            vec![test_file],
            OutputFormatArg::Json,
            None,
            None,
            vec![],
            false,
            false,
            false,
            false,
            None,
            false,
        )
        .await;

        // Should find violations (exit code 1)
        assert_eq!(result.unwrap(), 1);
    }

    #[test]
    fn test_validate_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_file = temp_dir.path().join("test_config.yaml");

        // Create a valid config file
        let config = GuardianConfig::default();
        let yaml = serde_yaml::to_string(&config).unwrap();
        fs::write(&config_file, yaml).unwrap();

        let result = run_validate_config(Some(config_file));
        assert_eq!(result.unwrap(), 0);
    }

    #[test]
    fn test_explain_rule() {
        let result = run_explain("todo_comments".to_string());
        assert_eq!(result.unwrap(), 0);

        let result = run_explain("nonexistent_rule".to_string());
        assert_eq!(result.unwrap(), 1);
    }

    #[test]
    fn test_list_rules() {
        let result = run_list_rules(None, false, None);
        assert_eq!(result.unwrap(), 0);

        let result = run_list_rules(None, true, Some("placeholders".to_string()));
        assert_eq!(result.unwrap(), 0);
    }
}