blazy 0.2.3

Unified, AI-safe meta-package manager for 26 OS and language package managers
use crate::model::ProviderId;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BlazyConfig {
    /// Ordered preference when resolving an unqualified package name.
    pub provider_priority: Vec<ProviderId>,
    /// Providers explicitly blocked by policy.
    pub denied_providers: Vec<ProviderId>,
    /// Whether plans that may trigger UAC / admin elevation are permitted.
    pub allow_elevation: bool,
    /// Timeout in seconds for search/list/outdated subprocesses.
    pub query_timeout_secs: u64,
    /// Per-provider query timeout overrides in seconds (e.g. `gem = 90`).
    pub provider_timeouts: BTreeMap<ProviderId, u64>,
    /// Timeout in seconds for install/remove/update subprocesses.
    pub action_timeout_secs: u64,
}

impl Default for BlazyConfig {
    fn default() -> Self {
        Self {
            provider_priority: vec![
                ProviderId::Scoop,
                ProviderId::Brew,
                ProviderId::Winget,
                ProviderId::Choco,
                ProviderId::Apt,
                ProviderId::Pacman,
                ProviderId::Dnf,
                ProviderId::Mise,
                ProviderId::Nix,
                ProviderId::Flatpak,
                ProviderId::Snap,
                ProviderId::Uv,
                ProviderId::Pip,
                ProviderId::Pnpm,
                ProviderId::Npm,
                ProviderId::Yarn,
                ProviderId::Bun,
                ProviderId::Deno,
                ProviderId::Cargo,
                ProviderId::Go,
                ProviderId::Dotnet,
                ProviderId::Gem,
                ProviderId::Composer,
                ProviderId::Luarocks,
                ProviderId::Dart,
            ],
            denied_providers: Vec::new(),
            allow_elevation: false,
            query_timeout_secs: 25,
            provider_timeouts: BTreeMap::from([(ProviderId::Gem, 90)]),
            action_timeout_secs: 300,
        }
    }
}

impl BlazyConfig {
    pub fn timeout_for(&self, id: ProviderId) -> u64 {
        self.provider_timeouts
            .get(&id)
            .copied()
            .unwrap_or(self.query_timeout_secs)
    }
    pub fn load() -> (Self, Vec<String>) {
        Self::load_with_source().0
    }

    pub fn load_with_source() -> ((Self, Vec<String>), Option<PathBuf>) {
        let mut warnings = Vec::new();
        for path in Self::candidate_paths() {
            if path.exists() {
                match std::fs::read_to_string(&path) {
                    Ok(raw) => match toml::from_str::<BlazyConfig>(&raw) {
                        Ok(cfg) => return ((cfg, warnings), Some(path)),
                        Err(err) => warnings.push(format!(
                            "Failed to parse config at {}: {err}; using defaults",
                            path.display()
                        )),
                    },
                    Err(err) => warnings.push(format!(
                        "Failed to read config at {}: {err}; using defaults",
                        path.display()
                    )),
                }
            }
        }
        ((Self::default(), warnings), None)
    }

    pub fn global_config_path() -> PathBuf {
        if let Some(home) = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")) {
            return PathBuf::from(home)
                .join(".config")
                .join("blazy")
                .join("config.toml");
        }
        PathBuf::from("blazy.config.toml")
    }

    pub fn save_to(&self, path: &std::path::Path) -> Result<(), String> {
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent)
                    .map_err(|e| format!("failed to create config directory: {e}"))?;
            }
        }
        let body = toml::to_string_pretty(self)
            .map_err(|e| format!("failed to serialize config: {e}"))?;
        let header = "# blazy user preferences\n# Edit `provider_priority` to control which package manager blazy picks first.\n\n";
        std::fs::write(path, format!("{header}{body}"))
            .map_err(|e| format!("failed to write {}: {e}", path.display()))
    }

    fn candidate_paths() -> Vec<PathBuf> {
        let mut paths = vec![PathBuf::from("blazy.config.toml"), PathBuf::from(".blazy.toml")];
        if let Some(home) = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")) {
            let home_path = PathBuf::from(home);
            paths.push(home_path.join(".config").join("blazy").join("config.toml"));
            paths.push(home_path.join(".blazy.toml"));
        }
        paths
    }

    pub fn is_denied(&self, id: ProviderId) -> bool {
        self.denied_providers.contains(&id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn saves_and_reloads_user_preferences() {
        let dir = std::env::temp_dir().join("blazy_cfg_test");
        let path = dir.join("config.toml");
        let mut cfg = BlazyConfig::default();
        cfg.provider_priority = vec![ProviderId::Uv, ProviderId::Scoop, ProviderId::Bun];
        cfg.save_to(&path).unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        let loaded: BlazyConfig = toml::from_str(&raw).unwrap();
        assert_eq!(
            loaded.provider_priority,
            vec![ProviderId::Uv, ProviderId::Scoop, ProviderId::Bun]
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}