use std::path::PathBuf;

use clap::Args;

use diffsift_core::config;

#[derive(Args)]
pub struct CheckArgs {
    /// Path to the git repository
    #[arg(long, default_value = ".")]
    pub repo: PathBuf,
}

pub fn run(args: CheckArgs) -> miette::Result<()> {
    let mut errors = 0;

    // 1. Validate config.toml
    let config_path = args.repo.join(".diffsift").join("config.toml");
    if config_path.exists() {
        match config::load_config(Some(&config_path), Some(&args.repo)) {
            Ok(_) => println!("  ✓ .diffsift/config.toml is valid"),
            Err(e) => {
                println!("  ✗ .diffsift/config.toml: {e}");
                errors += 1;
            }
        }
    } else {
        println!("  - .diffsift/config.toml not found (using defaults)");
    }

    // 2. Validate rules.toml
    let rules_path = args.repo.join(".diffsift").join("rules.toml");
    if rules_path.exists() {
        match config::load_custom_rules(&rules_path) {
            Ok(rules) => {
                println!("  ✓ .diffsift/rules.toml is valid ({} rules)", rules.len());
                for (i, rule) in rules.iter().enumerate() {
                    // Validate glob patterns are non-empty
                    if rule.paths.is_empty() {
                        println!("  ✗ rules[{}]: no paths specified", i);
                        errors += 1;
                    }
                    // Validate at least one override is set
                    if rule.min_priority.is_none()
                        && rule.max_priority.is_none()
                        && rule.category.is_none()
                    {
                        println!(
                            "  ✗ rules[{}]: no override set (need min_priority, max_priority, or category)",
                            i
                        );
                        errors += 1;
                    }
                }
            }
            Err(e) => {
                println!("  ✗ .diffsift/rules.toml: {e}");
                errors += 1;
            }
        }
    } else {
        println!("  - .diffsift/rules.toml not found (no custom rules)");
    }

    // 3. Validate template_dir if configured
    let config = config::load_config(None, Some(&args.repo)).unwrap_or_default();
    if let Some(dir) = &config.prompts.template_dir {
        let template_path = args.repo.join(dir);
        if template_path.is_dir() {
            let template_files = [
                "system.jinja2",
                "review.jinja2",
                "small_diff_system.jinja2",
                "small_diff.jinja2",
            ];
            let mut found = 0;
            for name in &template_files {
                if template_path.join(name).exists() {
                    println!("  ✓ {dir}/{name} found");
                    found += 1;
                }
            }
            if found == 0 {
                println!("  - {dir}/ exists but contains no template files");
            }
        } else {
            println!("  ✗ template_dir '{dir}' does not exist");
            errors += 1;
        }
    }

    if errors > 0 {
        Err(miette::miette!("{errors} validation error(s) found"))
    } else {
        println!("\n  All checks passed.");
        Ok(())
    }
}
