// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Handle some basic options: help, version, features.
//!
//! Even though most command-line parsing libraries provide some sort of
//! handling for these options, the Ringlet utilities have a tradition of
//! being able to handle them bundled/or and combined.

use core::iter;

use itertools::Itertools as _;

#[cfg(feature = "cli-basic-clap")]
use {clap::Parser as _, clap_derive::Parser};

/// Get the list of features supported by the module.
#[inline]
pub fn features() -> impl Iterator<Item = (&'static str, &'static str)> {
    let it_base = iter::once(("cli-basic", "0.1"));

    #[cfg(not(feature = "cli-basic-clap"))]
    let it_cli_basic_clap = it_base;
    #[cfg(feature = "cli-basic-clap")]
    let it_cli_basic_clap = it_base.chain(iter::once(("cli-basic-clap", "0.1")));

    it_cli_basic_clap
}

/// Just the most basic information.
#[derive(Debug)]
#[cfg_attr(feature = "cli-basic-clap", derive(Parser))]
#[cfg_attr(feature = "cli-basic-clap", clap(disable_help_flag = true))]
struct BasicOptions {
    /// List the features supported by the program and exit.
    #[cfg_attr(feature = "cli-basic-clap", clap(long))]
    features: bool,

    /// Display program usage information and exit.
    #[cfg_attr(feature = "cli-basic-clap", clap(short = 'h', long))]
    help: bool,

    /// Display program version information and exit.
    #[cfg_attr(feature = "cli-basic-clap", clap(short = 'V', long))]
    version: bool,
}

/// Check for and handle the basic query options (help, features, version).
#[expect(clippy::print_stdout, reason = "this is the whole point")]
#[inline]
pub fn handle_basic_options<'features, FI>(
    prog: &str,
    version: &str,
    features: FI,
    usage: &str,
) -> bool
where
    FI: Iterator<Item = (&'features str, &'features str)>,
{
    #[cfg(feature = "cli-basic-clap")]
    let Ok(args) = BasicOptions::try_parse() else {
        return false;
    };

    if args.version {
        println!("{prog} {version}");
    }
    if args.features {
        println!(
            "Features: {features}",
            features = features
                .map(|(name, value)| format!("{name}={value}"))
                .join(" ")
        );
    }
    if args.help {
        println!("{usage}");
    }
    args.version || args.features || args.help
}
