use crate::cli::Cli;
use clap::CommandFactory;
use miette::Result;

pub(crate) fn generate() -> Result<()> {
    let mut cli = Cli::command().version(env!("CARGO_PKG_VERSION"));
    let mut spec = clap_usage::spec(&mut cli, "usage");

    // Declare what each command does to the world. clap cannot express this,
    // so it is applied to the derived spec; see command_effects.
    crate::command_effects::apply(&mut spec);

    println!("// @generated by usage-cli from clap metadata");
    // 3.6 added `effect=` and 4.0 added it on flags and args; older `usage`
    // CLIs reject the spec outright with "unsupported cmd prop effect", so this
    // moves in lockstep with the fields the spec actually carries.
    println!(r#"min_usage_version "4.0""#);
    println!("{spec}");
    println!("{}", include_str!("../assets/usage-extra.usage.kdl").trim());

    Ok(())
}

pub(crate) fn complete(shell: &str) -> Result<()> {
    match shell {
        "bash" => print!("{}", include_str!("../assets/completions/usage.bash")),
        "fish" => print!("{}", include_str!("../assets/completions/usage.fish")),
        "zsh" => print!("{}", include_str!("../assets/completions/_usage")),
        _ => {
            miette::bail!("unsupported shell: {}", shell);
        }
    };

    Ok(())
}
