//! Configuration file loader

use crate::config::TypeDialogConfig;
use crate::error::{ErrorWrapper, Result};
use std::fs;
use std::path::PathBuf;

/// Load global configuration from ~/.config/typedialog/config.toml
///
/// If the file doesn't exist, returns the default configuration.
pub fn load_global_config() -> Result<TypeDialogConfig> {
    let config_path = get_config_path()?;

    if config_path.exists() {
        let content = fs::read_to_string(&config_path)?;
        toml::from_str(&content).map_err(|e| {
            ErrorWrapper::config_not_found(format!(
                "Failed to parse config file at {:?}: {}",
                config_path, e
            ))
        })
    } else {
        Ok(TypeDialogConfig::default())
    }
}

/// Get the config file path (~/.config/typedialog/config.toml)
fn get_config_path() -> Result<PathBuf> {
    #[cfg(feature = "i18n")]
    {
        use dirs::config_dir;
        let config_dir = config_dir().ok_or_else(|| {
            ErrorWrapper::config_not_found("Unable to determine config directory")
        })?;
        Ok(config_dir.join("typedialog").join("config.toml"))
    }

    #[cfg(not(feature = "i18n"))]
    {
        // Fallback without dirs dependency
        std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .map_err(|_| ErrorWrapper::config_not_found("Unable to determine home directory"))
            .map(|home| PathBuf::from(home).join(".config/typedialog/config.toml"))
    }
}
