use std::path::PathBuf;

use clap::Args;

use diffsift_core::baseline::{Baseline, BaselineEntry};

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

    /// Base ref (commit, branch, or tag)
    #[arg(long)]
    pub base: String,

    /// Head ref (commit, branch, or tag)
    #[arg(long)]
    pub head: String,

    /// Output path for baseline file
    #[arg(long, default_value = ".diffsift/baseline.json")]
    pub output: PathBuf,
}

pub fn run(args: BaselineArgs) -> miette::Result<()> {
    let result = diffsift_core::classify_diff(&args.repo, &args.base, &args.head)?;

    let mut baseline = Baseline::new();

    for file in &result.files {
        for hunk in &file.hunks {
            if hunk.patterns.is_empty() {
                continue;
            }
            if let Some(fp) = &hunk.fingerprint {
                baseline.fingerprints.push(BaselineEntry {
                    fingerprint: fp.clone(),
                    rule_id: hunk.patterns[0].pattern_id.clone(),
                    file_path: file.path.clone(),
                    category: format!("{:?}", hunk.category).to_lowercase(),
                });
            }
        }
    }

    baseline
        .save(&args.output)
        .map_err(|e| miette::miette!("Failed to save baseline: {e}"))?;

    println!(
        "Baseline saved to {} ({} findings)",
        args.output.display(),
        baseline.fingerprints.len()
    );

    Ok(())
}
