/*
 * SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
 * SPDX-License-Identifier: BSD-2-Clause
 */
#![allow(clippy::result_large_err)]

use std::io;

use anyhow::{Context, Result};
use clap::Parser;
use clap_derive::Parser;
use tracing::Level;

mod defs;
mod output;
mod parse;

use defs::Config;
use tracing::debug;

#[derive(Debug, Parser)]
#[clap(author, version, about)]
struct Cli {
    /// The name of the JSON test data file.
    #[clap(short = 'f', long)]
    data_file: String,

    /// The name of the file to generate.
    #[clap(short, long)]
    output: String,

    /// Verbose operation; display diagnostic output.
    #[clap(short, long)]
    verbose: bool,

    /// The path to the template to use.
    template_path: String,
}

fn parse_args() -> Result<Config> {
    let args = Cli::try_parse().context("Could not parse the command-line arguments")?;
    Ok(Config {
        data_path: args.data_file,
        output_path: args.output,
        template_path: args.template_path,
        verbose: args.verbose,
    })
}

/// Initialize the logging subsystem provided by the `tracing` library.
fn setup_tracing(verbose: bool) -> Result<()> {
    let sub = tracing_subscriber::fmt()
        .without_time()
        .with_max_level(if verbose { Level::TRACE } else { Level::INFO })
        .with_writer(io::stderr)
        .finish();
    #[allow(clippy::absolute_paths)]
    tracing::subscriber::set_global_default(sub).context("Could not initialize the tracing logger")
}

fn main() -> Result<()> {
    let cfg = parse_args()?;
    setup_tracing(cfg.verbose)?;
    let template = parse::parse_template(&cfg).context("Could not parse the template file")?;
    let test_data = parse::parse_test_data(&cfg).context("Could not parse the test data")?;
    output::write_output_file(&cfg, &template, &test_data)
        .context("Could not generate the output file")?;
    debug!("Everything seems fine!");
    Ok(())
}
