use std::path::PathBuf;

pub fn get_config_path(cli_override: Option<&str>) -> PathBuf {
    if let Some(path) = cli_override {
        return PathBuf::from(path);
    }

    if let Ok(path) = std::env::var("LORE_CONFIG_PATH") {
        return PathBuf::from(path);
    }

    let xdg_path = get_xdg_config_dir().join("lore").join("config.json");
    if xdg_path.exists() {
        return xdg_path;
    }

    let local_path = PathBuf::from("lore.config.json");
    if local_path.exists() {
        return local_path;
    }

    xdg_path
}

pub fn get_data_dir() -> PathBuf {
    get_xdg_data_dir().join("lore")
}

pub fn get_db_path(config_override: Option<&str>) -> PathBuf {
    if let Some(path) = config_override {
        return PathBuf::from(path);
    }
    get_data_dir().join("lore.db")
}

pub fn get_log_dir(config_override: Option<&str>) -> PathBuf {
    if let Some(path) = config_override {
        return PathBuf::from(path);
    }
    get_data_dir().join("logs")
}

pub fn get_backup_dir(config_override: Option<&str>) -> PathBuf {
    if let Some(path) = config_override {
        return PathBuf::from(path);
    }
    get_data_dir().join("backups")
}

fn get_xdg_config_dir() -> PathBuf {
    std::env::var("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".config")
        })
}

fn get_xdg_data_dir() -> PathBuf {
    std::env::var("XDG_DATA_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".local")
                .join("share")
        })
}

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

    #[test]
    fn test_cli_override_takes_precedence() {
        let path = get_config_path(Some("/custom/path.json"));
        assert_eq!(path, PathBuf::from("/custom/path.json"));
    }
}
