use std::path::Path;

use dotenvy;

/// Initialize environment variables for CLI from .env file in current working directory
///
/// This function looks for a `.env` file in the current working directory (where the command is executed).
/// This works for both development and published binaries.
///
/// If `APP_BASE_DIR` environment variable is set, it will look for the .env file in that directory instead.
///
/// The .env file is optional - if it doesn't exist, the function silently returns Ok(()).
///
/// # Returns
/// A `Result` containing the environment variables, or an error if the initialization fails.
/// Errors are typically ignored since .env files are optional.
pub fn init() -> Result<(), dotenvy::Error> {
    let base_dir = if let Ok(dir) = std::env::var("APP_BASE_DIR") {
        dir
    } else {
        // Use current working directory for published binaries
        // This allows users to place .env files where they run the command
        std::env::current_dir()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|_| ".".to_string())
    };

    let env_file = ".env";
    let path = format!("{base_dir}/{env_file}");

    tracing::debug!("Attempting to load environment variables from {path}");
    dotenvy::from_path(Path::new(path.as_str()))
}
