// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "distributed-tracing")]
use std::collections::HashMap;

/// Parse boolean environment variable with default
pub fn parse_bool_env(var_name: &str, default: bool) -> bool {
    std::env::var(var_name)
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(default)
}

/// Parse string list environment variable with default
#[cfg(feature = "distributed-tracing")]
pub fn parse_string_list_env(var_name: &str, default: Vec<String>) -> Vec<String> {
    std::env::var(var_name)
        .ok()
        .map(|v| v.split(',').map(|s| s.trim().to_string()).collect())
        .unwrap_or(default)
}

/// Parse key-value pairs from environment variable
/// Format: "key1=value1,key2=value2" or "key1=value1;key2=value2"
#[cfg(feature = "distributed-tracing")]
pub fn parse_key_value_env(var_name: &str) -> HashMap<String, String> {
    std::env::var(var_name)
        .ok()
        .map(|v| parse_key_value_string(&v))
        .unwrap_or_default()
}

/// Parse key-value string with support for both comma and semicolon separators
#[cfg(feature = "distributed-tracing")]
pub fn parse_key_value_string(s: &str) -> HashMap<String, String> {
    let mut map = HashMap::new();

    // Support both comma and semicolon as separators
    let separator = if s.contains(';') { ';' } else { ',' };

    for pair in s.split(separator) {
        let pair = pair.trim();
        if let Some((key, value)) = pair.split_once('=') {
            map.insert(key.trim().to_string(), value.trim().to_string());
        }
    }

    map
}
