use std::io;
use std::process::ExitCode;

use clap::Parser;
use hanuke::cli::{Cli, Command};
use hanuke::{app, report, version};

fn main() -> ExitCode {
    let cli = Cli::parse();
    if let Some(Command::Version(v)) = &cli.command {
        println!("{}", version::format_version(v.commit));
        return ExitCode::SUCCESS;
    }

    let args = &cli.check;
    let result = match app::run(args) {
        Ok(result) => result,
        Err(e) => {
            eprintln!("hanuke: {e}");
            return ExitCode::from(2);
        }
    };

    let mut stdout = io::stdout().lock();
    let written = if args.json {
        report::write_json(&result, args.verbose, &mut stdout)
    } else if args.verbose {
        report::write_verbose(&result, &mut stdout)
    } else if !args.show.is_empty() {
        report::write_show(&result, &args.show, &mut stdout)
    } else {
        Ok(())
    };
    if let Err(e) = written {
        eprintln!("hanuke: {e}");
        return ExitCode::from(2);
    }

    if result.is_ok() {
        ExitCode::SUCCESS
    } else {
        if !args.verbose && !args.json {
            let first = report::format_issue(&result.issues[0]);
            eprintln!(
                "hanuke: NG: {} issue(s), first: {first}",
                result.issues.len()
            );
        }
        ExitCode::from(1)
    }
}
