use clap::{Arg, ArgMatches, Command};
use log::{error, warn};
use logger::init_logger;
use mdbook::errors::Error;
use mdbook::preprocess::{CmdPreprocessor, Preprocessor};
use semver::{Version, VersionReq};
use std::io;
use std::process;

use mdbook_autosummary::AutoSummary;

mod logger;

const VERSION: &str = env!("CARGO_PKG_VERSION");

pub fn make_app() -> Command {
    Command::new("mdbook-autosummary")
        .about("A mdbook preprocessor which generates a SUMMARY.md for your book based on the folder structure")
        .subcommand(
            Command::new("supports")
                .arg(Arg::new("renderer").required(true))
                .about("Check whether a renderer is supported by this preprocessor"),
        )
        .subcommand(
            Command::new("version").long_flag("version")
                .about("Print the version of this preprocessor"),
        )
}

fn main() {
    init_logger();

    let matches = make_app().get_matches();

    let preprocessor = AutoSummary::new();

    if let Some(sub_args) = matches.subcommand_matches("supports") {
        handle_supports(&preprocessor, sub_args);
    } else if matches.subcommand_matches("version").is_some() {
        println!("mdbook-autosummary v{}", VERSION);
        process::exit(0);
    } else if let Err(e) = handle_preprocessing(&preprocessor) {
        error!("{}", e);
        process::exit(1);
    }
}

fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<(), Error> {
    let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?;

    let book_version = Version::parse(&ctx.mdbook_version)?;
    let version_req = VersionReq::parse(mdbook::MDBOOK_VERSION)?;

    if !version_req.matches(&book_version) {
        warn!(
            "Warning: The {} preprocessor was built against version {} of mdbook, \
             but mdbook version is {}",
            pre.name(),
            mdbook::MDBOOK_VERSION,
            ctx.mdbook_version
        );
    }

    let processed_book = pre.run(&ctx, book)?;
    serde_json::to_writer(io::stdout(), &processed_book)?;

    Ok(())
}

fn handle_supports(pre: &dyn Preprocessor, sub_args: &ArgMatches) -> ! {
    let renderer = sub_args
        .get_one::<String>("renderer")
        .expect("Required argument");
    let supported = pre.supports_renderer(renderer);

    // Signal whether the renderer is supported by exiting with 1 or 0.
    if supported {
        process::exit(0);
    } else {
        process::exit(1);
    }
}
