use std::path::PathBuf;

use clap::Args;

use diffsift_core::config::DEFAULT_CONFIG_TOML;

#[derive(Args)]
pub struct InitArgs {
    /// Path to initialize (defaults to current directory)
    #[arg(long, default_value = ".")]
    pub path: PathBuf,

    /// Overwrite existing config
    #[arg(long)]
    pub force: bool,
}

pub fn run(args: InitArgs) -> miette::Result<()> {
    let config_dir = args.path.join(".diffsift");
    let config_file = config_dir.join("config.toml");

    if config_file.exists() && !args.force {
        return Err(miette::miette!(
            "Config already exists at {}. Use --force to overwrite.",
            config_file.display()
        ));
    }

    std::fs::create_dir_all(&config_dir)
        .map_err(|e| miette::miette!("Failed to create {}: {e}", config_dir.display()))?;

    std::fs::write(&config_file, DEFAULT_CONFIG_TOML)
        .map_err(|e| miette::miette!("Failed to write {}: {e}", config_file.display()))?;

    println!("Created {}", config_file.display());
    println!();
    println!("Next steps:");
    println!("  1. Edit .diffsift/config.toml to set your LLM provider and API key");
    println!("  2. Set ANTHROPIC_API_KEY or OPENAI_API_KEY in your environment");
    println!("  3. Run: diffsift review --repo . --base main --head HEAD");
    println!("  4. Add to CI: see https://gitlab.com/neilfitzgerald1972/diffsift#gitlab-ci");

    Ok(())
}
