// Windows isn't really amenable to having a single executable work as both a CLI and GUI app,
// so we just have a second binary for CLI usage
use creddy::{
    cli,
    errors::CliError,
};
use std::{
    env,
    process::{self, Command},
};


fn main() {
    let args = cli::parser().get_matches();
    if let Some(true) = args.get_one::<bool>("help") {
        cli::parser().print_help().unwrap(); // if we can't print help we can't print an error
        process::exit(0);
    }

    let res = match args.subcommand() {
        None | Some(("run", _)) => launch_gui(),
        Some(("get", m)) => cli::get(m),
        Some(("exec", m)) => cli::exec(m),
        Some(("shortcut", m)) => cli::invoke_shortcut(m),
        _ => unreachable!("Unknown subcommand"),
    };

    if let Err(e) = res {
        eprintln!("Error: {e}");
        process::exit(1);
    }
}


fn launch_gui() -> Result<(), CliError>  {
    let mut path = env::current_exe()?;
    path.pop(); // bin dir
    
    // binaries are colocated in dev, but not in production
    #[cfg(not(debug_assertions))]
    path.pop(); // install dir

    path.push("creddy.exe"); // exe in main install dir (aka gui exe)

    Command::new(path).spawn()?;
    Ok(())
}
