// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Parse the command-line arguments for the generate-tests tool.

use std::io;

use anyhow::{Context as _, Result};
use camino::Utf8Path;
use clap::Parser as _;
use clap_derive::Parser;
use tracing::Level;

use crate::defs::Config;

/// The command-line interface arguments definition.
#[derive(Debug, Parser)]
#[clap(author, version, about)]
struct Cli {
    /// The path to the shell program to generate.
    #[clap(short, long)]
    output_file: String,

    /// Verbose operation: display diagnostic messages.
    #[clap(short)]
    verbose: bool,
}

/// 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::DEBUG } 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")
}

/// Parse the command-line arguments.
pub fn parse_args() -> Result<Config> {
    let args = Cli::parse();
    setup_tracing(args.verbose)?;

    let output_file = {
        let opath = Utf8Path::new(&args.output_file);
        let oparent = opath.parent().with_context(|| {
            format!(
                "Could not determine the parent directory for the output file {output_file}",
                output_file = args.output_file
            )
        })?;
        let oparent_canon = if oparent.as_os_str().is_empty() {
            Utf8Path::new(".")
                .canonicalize_utf8()
                .context("Could not canonicalize the current working directory")?
        } else {
            oparent.canonicalize_utf8().with_context(|| {
                format!(
                    "Could not canonicalize {oparent} for the output file {output_file}",
                    output_file = args.output_file,
                )
            })?
        };
        oparent_canon.join(opath.file_name().with_context(|| {
            format!(
                "No filename portion in the output file path {output_file}",
                output_file = args.output_file
            )
        })?)
    };

    Ok(Config::new(output_file))
}
