use std::env;
use std::path::{Path, PathBuf};

pub fn get_profile_name_from_env() -> Option<String> {
    let env_vars = ["NODE_ENV", "RUN_ENV", "APP_ENV", "SPRING_PROFILES_ACTIVE", "MISE_ENV","STELA_ENV"];
    for var in env_vars.iter() {
        if let Ok(value) = env::var(var) {
            if !value.is_empty() {
                return Some(value);
            }
        }
    }
    None
}

pub fn get_profile_name_from_file(env_file: &str) -> Option<String> {
    let mut env_file_name = env_file;
    if env_file.contains("/") {
        env_file_name = env_file_name.rsplit('/').next().unwrap_or(env_file_name);
    } else if env_file.contains('\\') {
        env_file_name = env_file_name.rsplit('\\').next().unwrap_or(env_file_name);
    }
    if env_file_name.starts_with(".env.") {
        let profile_name = env_file_name.replace(".env.", "");
        return Some(profile_name);
    } else if env_file_name.ends_with(".properties") && env_file_name.contains('-') {
        return env_file_name
            .replace(".properties", "")
            .rsplit('-')
            .next()
            .map(|x| x.to_string());
    }
    None
}

pub fn find_dotenv_keys_file() -> Option<PathBuf> {
    let current_dir = env::current_dir().unwrap();
    find_dotenv_keys_file_by_path(&current_dir)
}

pub fn find_dotenv_keys_file_by_path(dir: &Path) -> Option<PathBuf> {
    if dir.join(".env.keys").exists() {
        return Some(dir.join(".env.keys"));
    } else if let Some(parent) = dir.parent() {
        return find_dotenv_keys_file_by_path(parent);
    }
    None
}

pub fn find_env_file_path(dir: &Path, env_file_name: &str) -> Option<PathBuf> {
    if dir.join(env_file_name).exists() {
        return Some(dir.join(env_file_name));
    } else if let Some(parent) = dir.parent() {
        return find_env_file_path(parent, env_file_name);
    }
    None
}
