//! Main entry point for the `cargo ros-add` subcommand.
//!
//! This binary handles adding dependencies to both Cargo.toml and package.xml files
//! for ROS 2 packages written in Rust.
//!
use clap::ArgMatches;
use ros_add::{PathDoc, XMLHelper, env_to_matches};
use std::{env, io::ErrorKind, path::Path, process::Command};

fn main() -> Result<(), ErrorKind> {
    let matches: ArgMatches = env_to_matches(env::args().collect::<Vec<_>>());

    let dependency: &str = matches.get_one::<String>("dependency").ok_or_else(|| {
        eprintln!(
            "Argument 'dependency' is required but missing. Check `env_to_matches` implementation."
        );
        ErrorKind::InvalidInput
    })?;

    let processed_dependency = dependency.into();
    let dependency_type = matches.clone().into();

    // First try with cargo add
    if !(matches.get_flag("no_cargo_toml") || matches.get_flag("buildtool"))
        && Path::new("Cargo.toml").exists()
    {
        println!("Attempting to add '{dependency}' to Cargo.toml...");

        let mut cargo_add = Command::new("cargo");
        cargo_add.arg("add").arg(dependency);

        // Add --color if specified
        if let Some(color) = matches.get_one::<String>("color") {
            cargo_add.args(["--color", color]);
        }

        // Only add --build if the flag was explicitly given
        if matches.get_flag("build") || matches.get_flag("build-export") {
            cargo_add.arg("--build");
        }

        PathDoc::new("Cargo.toml", dependency_type)
            .map_or_else(
                |dings| {
                    eprintln!("{dings}");
                    Err(dings)
                },
                |ok| ok.add_dependency_to_cargo_toml(processed_dependency),
            )
            .unwrap_or_else(|dings| println!("{dings}"));
    }
    if !matches.get_flag("no_package_xml") {
        println!(
            "Attempting to add '{}' to package.xml...",
            processed_dependency.name
        );
        // First add to package.xml
        XMLHelper::new("package.xml", dependency_type)
            .map(|ok| ok.add_dependency_to_package_xml(processed_dependency))??;
    }

    Ok(())
}
