//! Configuration management for GDELT CLI.
//!
//! Configuration is loaded from:
//! 1. Built-in defaults
//! 2. Config file (~/.config/gdelt/config.toml)
//! 3. Environment variables (GDELT_*)
//! 4. Command-line arguments

#![allow(dead_code)]

pub mod schema;

pub use schema::Config;

use crate::error::{GdeltError, Result};
use directories::ProjectDirs;
use std::path::PathBuf;

/// Get the project directories
pub fn project_dirs() -> Option<ProjectDirs> {
    ProjectDirs::from("", "", "gdelt")
}

/// Get the default config file path
pub fn default_config_path() -> Option<PathBuf> {
    project_dirs().map(|dirs| dirs.config_dir().join("config.toml"))
}

/// Get the default data directory
pub fn data_dir() -> Option<PathBuf> {
    project_dirs().map(|dirs| dirs.data_dir().to_path_buf())
}

/// Get the default cache directory
pub fn cache_dir() -> Option<PathBuf> {
    project_dirs().map(|dirs| dirs.cache_dir().to_path_buf())
}

/// Load configuration from file and environment
pub fn load_config(path: Option<PathBuf>) -> Result<Config> {
    let config_path = path.or_else(default_config_path);

    let config = if let Some(path) = config_path {
        if path.exists() {
            let contents = std::fs::read_to_string(&path).map_err(|e| {
                GdeltError::Config(format!("Failed to read config file: {e}"))
            })?;
            toml::from_str(&contents).map_err(|e| {
                GdeltError::Config(format!("Failed to parse config file: {e}"))
            })?
        } else {
            Config::default()
        }
    } else {
        Config::default()
    };

    Ok(config)
}

/// Ensure required directories exist
pub fn ensure_directories() -> Result<()> {
    if let Some(data) = data_dir() {
        std::fs::create_dir_all(&data)?;
        std::fs::create_dir_all(data.join("downloads"))?;
        std::fs::create_dir_all(data.join("exports"))?;
    }
    if let Some(cache) = cache_dir() {
        std::fs::create_dir_all(cache)?;
    }
    if let Some(config) = default_config_path() {
        if let Some(parent) = config.parent() {
            std::fs::create_dir_all(parent)?;
        }
    }
    Ok(())
}
