//! Cache system initialization
//!
//! This module handles the initialization of the comprehensive caching system,
//! including persistent storage, memory caching, and cache prewarming.

use std::sync::Arc;

use rustelo_core_lib::cache::content::ContentCache;
use tracing;

use crate::config::Config;

/// Initialize cache system with persistent storage if enabled
pub async fn initialize_cache_system(
    config: &Config,
) -> Result<
    (
        Option<std::path::PathBuf>,
        rustelo_core_lib::cache::CacheConfig,
        Arc<ContentCache>,
    ),
    Box<dyn std::error::Error>,
> {
    // Initialize cache system with persistent storage if enabled
    let cache_dir = if config.cache.persistent_enabled {
        let cache_path = std::path::PathBuf::from(&config.server_dirs.cache_dir);
        if !cache_path.exists() {
            std::fs::create_dir_all(&cache_path).map_err(|e| {
                format!(
                    "Failed to create cache directory '{}': {}",
                    cache_path.display(),
                    e
                )
            })?;
        }
        tracing::info!("Persistent cache enabled at: {}", cache_path.display());
        Some(cache_path)
    } else {
        tracing::info!("Persistent cache disabled, using memory cache only");
        None
    };

    // Convert server cache config to shared cache config
    let shared_cache_config = rustelo_core_lib::cache::CacheConfig {
        enable_persistent_cache: config.cache.persistent_enabled,
        persistent_cache_dir: cache_dir.clone(),
        cleanup_interval_seconds: config.cache.persistent_cleanup_interval,
        max_memory_bytes: config.cache.memory_max_size as usize,
        default_ttl_seconds: config.cache.memory_ttl,
        enable_prewarming: true,
        content_type_ttl: std::collections::HashMap::new(),
        max_entries: 1000,
    };

    // Initialize content cache system with persistent storage (without Leptos
    // reactive features for server)
    tracing::debug!("Initializing content cache system...");
    let content_cache = Arc::new(ContentCache::with_config_and_cache_dir(
        shared_cache_config.clone(),
        cache_dir.clone(),
    ));

    // Warm up cache with essential content if prewarming is enabled
    if shared_cache_config.enable_prewarming {
        tracing::debug!("Starting cache prewarming...");
        let cache_warmer = Arc::new(rustelo_core_lib::cache::content::CacheWarmer::new());
        tokio::spawn({
            let cache_warmer = cache_warmer.clone();
            let content_cache_clone = content_cache.clone();
            async move {
                content_cache_clone.preload_for_languages(vec!["en".to_string(), "es".to_string()]);
                cache_warmer.warm_essential_content().await;
                tracing::debug!("Cache prewarming completed successfully");
            }
        });
    }

    // Schedule periodic cache cleanup if persistent cache is enabled
    if config.cache.persistent_enabled {
        let cleanup_interval =
            std::time::Duration::from_secs(config.cache.persistent_cleanup_interval);
        let content_cache_cleanup = content_cache.clone();
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(cleanup_interval);
            loop {
                interval.tick().await;
                content_cache_cleanup.cleanup_expired();
                tracing::debug!("Periodic cache cleanup completed");
            }
        });
        tracing::info!(
            "Scheduled periodic cache cleanup every {} seconds",
            config.cache.persistent_cleanup_interval
        );
    }

    Ok((cache_dir, shared_cache_config, content_cache))
}
