use clap::Args;
use std::process::Command;

const UPDATE_GUIDE: &str = include_str!("../UPDATE_GUIDE.md");

#[derive(Args)]
pub struct UpdateArgs {
    /// Re-install even when already on the latest version
    #[arg(short, long)]
    pub force: bool,

    /// Show this guide
    #[arg(long)]
    pub guide: bool,
}

pub fn run(args: UpdateArgs) {
    if args.guide {
        println!("{}", UPDATE_GUIDE);
        return;
    }

    let current = env!("CARGO_PKG_VERSION");
    println!("Current version: {current}");

    let mut cmd = Command::new("cargo");
    cmd.arg("install").arg("pandora-kit");

    if args.force {
        cmd.arg("--force");
    }

    println!("Running: cargo install pandora-kit{}", if args.force { " --force" } else { "" });

    let status = cmd.status();

    match status {
        Ok(s) if s.success() => {
            println!("Updated {} to the latest version.", crate::BIN_NAME);
        }
        Ok(s) => {
            eprintln!("error: cargo install failed (exit {})", s.code().unwrap_or(-1));
            std::process::exit(1);
        }
        Err(e) => {
            eprintln!("error: could not run cargo: {e}");
            eprintln!("hint: make sure rust/cargo is installed and in your PATH");
            std::process::exit(1);
        }
    }
}
