// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Helper functions for handling the process environment.

use core::iter;

use std::collections::HashSet;

/// The variables needed to execute a program in a `C.UTF-8` locale.
pub const UTF8_VARS: [(&str, &str); 2] = [("LANGUAGE", ""), ("LC_ALL", "C.UTF-8")];

/// 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(("env", "0.1"));

    #[cfg(not(feature = "env-utf8"))]
    let it_env_utf8 = it_base;
    #[cfg(feature = "env-utf8")]
    let it_env_utf8 = it_base.chain(iter::once(("env-utf8", "0.1")));

    it_env_utf8
}

/// Get the variables needed to execute a program in a `C.UTF-8` locale.
#[inline]
pub fn c_utf8_vars() -> impl Iterator<Item = (&'static str, &'static str)> {
    UTF8_VARS.into_iter()
}

/// Add the variables needed to execute a program in a `C.UTF-8` locale.
#[inline]
pub fn c_utf8_add_vars<I>(it: I) -> impl Iterator<Item = (String, String)>
where
    I: IntoIterator<Item = (String, String)>,
{
    let ours: HashSet<_> = UTF8_VARS.into_iter().map(|(key, _)| key).collect();
    #[expect(clippy::needless_borrowed_reference, reason = "make up your mind")]
    it.into_iter()
        .filter(move |&(ref key, _)| !ours.contains(key.as_str()))
        .chain(
            UTF8_VARS
                .into_iter()
                .map(|(key, value)| (key.to_owned(), value.to_owned())),
        )
}
