use crate::command_prelude::*;
use anyhow::anyhow;
use cargo::core::compiler::future_incompat::{OnDiskReports, REPORT_PREAMBLE};
use cargo::drop_println;

pub fn cli() -> App {
    subcommand("report")
        .about("Generate and display various kinds of reports")
        .after_help("Run `cargo help report` for more detailed information.\n")
        .setting(clap::AppSettings::SubcommandRequiredElseHelp)
        .subcommand(
            subcommand("future-incompatibilities")
                .alias("future-incompat")
                .about("Reports any crates which will eventually stop compiling")
                .arg(
                    opt(
                        "id",
                        "identifier of the report generated by a Cargo command invocation",
                    )
                    .value_name("id"),
                ),
        )
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
    if !config.nightly_features_allowed {
        return Err(anyhow!("`cargo report` can only be used on the nightly channel").into());
    }
    match args.subcommand() {
        ("future-incompatibilities", Some(args)) => report_future_incompatibilies(config, args),
        (cmd, _) => panic!("unexpected command `{}`", cmd),
    }
}

fn report_future_incompatibilies(config: &Config, args: &ArgMatches<'_>) -> CliResult {
    let ws = args.workspace(config)?;
    let reports = OnDiskReports::load(&ws)?;
    let id = args
        .value_of_u32("id")?
        .unwrap_or_else(|| reports.last_id());
    let report = reports.get_report(id, config)?;
    drop_println!(config, "{}", REPORT_PREAMBLE);
    drop(config.shell().print_ansi_stdout(report.as_bytes()));
    Ok(())
}
