//! 服务管理器
//! 统一管理所有 ComfyUI 相关的服务实例

use anyhow::{Result, anyhow};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, warn};

use crate::business::services::{
    comfyui_manager::ComfyUIManager,
    template_engine::TemplateEngine,
    execution_engine::ExecutionEngine,
    realtime_monitor::RealtimeMonitor,
    config_manager::ConfigManager,
    error_handler::ErrorHandler,
};
use crate::data::repositories::comfyui_repository::ComfyUIRepository;
use crate::data::models::comfyui::ComfyUIConfig;

/// 服务管理器
/// 负责创建、管理和协调所有 ComfyUI 相关的服务
pub struct ServiceManager {
    /// ComfyUI 管理器
    comfyui_manager: Arc<RwLock<Option<Arc<ComfyUIManager>>>>,
    /// 模板引擎
    template_engine: Arc<RwLock<Option<Arc<TemplateEngine>>>>,
    /// 执行引擎
    execution_engine: Arc<RwLock<Option<Arc<ExecutionEngine>>>>,
    /// 实时监控
    realtime_monitor: Arc<RwLock<Option<Arc<RealtimeMonitor>>>>,
    /// 配置管理器
    config_manager: Arc<ConfigManager>,
    /// 错误处理器
    error_handler: Arc<ErrorHandler>,
    /// 数据仓库
    repository: Arc<ComfyUIRepository>,
    /// 初始化状态
    initialized: Arc<RwLock<bool>>,
}

impl ServiceManager {
    /// 创建新的服务管理器
    pub fn new(config_manager: ConfigManager, database: Arc<crate::infrastructure::database::Database>) -> Self {
        let repository = Arc::new(ComfyUIRepository::new(database));
        
        Self {
            comfyui_manager: Arc::new(RwLock::new(None)),
            template_engine: Arc::new(RwLock::new(None)),
            execution_engine: Arc::new(RwLock::new(None)),
            realtime_monitor: Arc::new(RwLock::new(None)),
            config_manager: Arc::new(config_manager),
            error_handler: Arc::new(ErrorHandler::new()),
            repository,
            initialized: Arc::new(RwLock::new(false)),
        }
    }

    /// 初始化所有服务
    pub async fn initialize(&self) -> Result<()> {
        info!("开始初始化服务管理器");

        // 检查是否已经初始化
        {
            let initialized = self.initialized.read().await;
            if *initialized {
                return Ok(());
            }
        }

        // 初始化数据库
        self.repository.initialize()?;

        // 获取配置
        let config = self.config_manager.get_comfyui_config().await;

        // 创建 ComfyUI 管理器
        let comfyui_manager = Arc::new(ComfyUIManager::new(config)?);
        {
            let mut manager_guard = self.comfyui_manager.write().await;
            *manager_guard = Some(Arc::clone(&comfyui_manager));
        }

        // 创建模板引擎
        let template_engine = Arc::new(TemplateEngine::new(Arc::clone(&self.repository)));
        {
            let mut engine_guard = self.template_engine.write().await;
            *engine_guard = Some(Arc::clone(&template_engine));
        }

        // 创建执行引擎
        let execution_engine = Arc::new(ExecutionEngine::new(
            Arc::clone(&comfyui_manager),
            Arc::clone(&template_engine),
            Arc::clone(&self.repository),
        ));
        {
            let mut engine_guard = self.execution_engine.write().await;
            *engine_guard = Some(Arc::clone(&execution_engine));
        }

        // 创建实时监控
        let realtime_monitor = Arc::new(RealtimeMonitor::new(
            Arc::clone(&comfyui_manager),
            Arc::clone(&self.repository),
        ));
        {
            let mut monitor_guard = self.realtime_monitor.write().await;
            *monitor_guard = Some(Arc::clone(&realtime_monitor));
        }

        // 预热模板缓存
        if let Err(e) = template_engine.warm_cache().await {
            warn!("模板缓存预热失败: {}", e);
        }

        // 标记为已初始化
        {
            let mut initialized = self.initialized.write().await;
            *initialized = true;
        }

        info!("服务管理器初始化完成");
        Ok(())
    }

    /// 获取 ComfyUI 管理器
    pub async fn get_comfyui_manager(&self) -> Result<Arc<ComfyUIManager>> {
        let manager_guard = self.comfyui_manager.read().await;
        match manager_guard.as_ref() {
            Some(manager) => Ok(Arc::clone(manager)),
            None => Err(anyhow!("ComfyUI 管理器未初始化")),
        }
    }

    /// 获取模板引擎
    pub async fn get_template_engine(&self) -> Result<Arc<TemplateEngine>> {
        let engine_guard = self.template_engine.read().await;
        match engine_guard.as_ref() {
            Some(engine) => Ok(Arc::clone(engine)),
            None => Err(anyhow!("模板引擎未初始化")),
        }
    }

    /// 获取执行引擎
    pub async fn get_execution_engine(&self) -> Result<Arc<ExecutionEngine>> {
        let engine_guard = self.execution_engine.read().await;
        match engine_guard.as_ref() {
            Some(engine) => Ok(Arc::clone(engine)),
            None => Err(anyhow!("执行引擎未初始化")),
        }
    }

    /// 获取实时监控
    pub async fn get_realtime_monitor(&self) -> Result<Arc<RealtimeMonitor>> {
        let monitor_guard = self.realtime_monitor.read().await;
        match monitor_guard.as_ref() {
            Some(monitor) => Ok(Arc::clone(monitor)),
            None => Err(anyhow!("实时监控未初始化")),
        }
    }

    /// 获取当前配置
    pub async fn get_config(&self) -> Result<crate::data::models::comfyui::ComfyUIConfig> {
        // 从数据库加载配置
        self.repository.get_config().await
    }

    /// 更新配置
    pub async fn update_config(&self, config: crate::data::models::comfyui::ComfyUIConfig) -> Result<()> {
        // 保存配置到数据库
        self.repository.save_config(&config).await?;

        // 重新初始化ComfyUI管理器以使用新配置
        let mut comfyui_manager = self.comfyui_manager.write().await;
        *comfyui_manager = Some(Arc::new(
            ComfyUIManager::new(config.clone())?
        ));

        info!("配置更新成功，ComfyUI管理器已重新初始化");
        Ok(())
    }

    /// 获取配置管理器
    pub fn get_config_manager(&self) -> Arc<ConfigManager> {
        Arc::clone(&self.config_manager)
    }

    /// 获取错误处理器
    pub fn get_error_handler(&self) -> Arc<ErrorHandler> {
        Arc::clone(&self.error_handler)
    }

    /// 获取数据仓库
    pub fn get_repository(&self) -> Arc<ComfyUIRepository> {
        Arc::clone(&self.repository)
    }

    /// 检查是否已初始化
    pub async fn is_initialized(&self) -> bool {
        *self.initialized.read().await
    }

    /// 重新配置服务
    pub async fn reconfigure(&self, new_config: ComfyUIConfig) -> Result<()> {
        info!("重新配置服务");

        // 更新配置
        self.config_manager.update_comfyui_config(new_config.clone()).await?;

        // 重新创建 ComfyUI 管理器
        let new_manager = Arc::new(ComfyUIManager::new(new_config)?);
        {
            let mut manager_guard = self.comfyui_manager.write().await;
            *manager_guard = Some(new_manager);
        }

        // 重新创建执行引擎（因为它依赖于 ComfyUI 管理器）
        let comfyui_manager = self.get_comfyui_manager().await?;
        let template_engine = self.get_template_engine().await?;
        let new_execution_engine = Arc::new(ExecutionEngine::new(
            comfyui_manager,
            template_engine,
            Arc::clone(&self.repository),
        ));
        {
            let mut engine_guard = self.execution_engine.write().await;
            *engine_guard = Some(new_execution_engine);
        }

        // 重新创建实时监控
        let comfyui_manager = self.get_comfyui_manager().await?;
        let new_monitor = Arc::new(RealtimeMonitor::new(
            comfyui_manager,
            Arc::clone(&self.repository),
        ));
        {
            let mut monitor_guard = self.realtime_monitor.write().await;
            *monitor_guard = Some(new_monitor);
        }

        info!("服务重新配置完成");
        Ok(())
    }

    /// 关闭所有服务
    pub async fn shutdown(&self) -> Result<()> {
        info!("关闭服务管理器");

        // 停止实时监控
        if let Ok(monitor) = self.get_realtime_monitor().await {
            let _ = monitor.stop().await;
        }

        // 断开 ComfyUI 连接
        if let Ok(manager) = self.get_comfyui_manager().await {
            let _ = manager.disconnect().await;
        }

        // 清理服务实例
        {
            let mut manager_guard = self.comfyui_manager.write().await;
            *manager_guard = None;
        }
        {
            let mut engine_guard = self.template_engine.write().await;
            *engine_guard = None;
        }
        {
            let mut engine_guard = self.execution_engine.write().await;
            *engine_guard = None;
        }
        {
            let mut monitor_guard = self.realtime_monitor.write().await;
            *monitor_guard = None;
        }

        // 标记为未初始化
        {
            let mut initialized = self.initialized.write().await;
            *initialized = false;
        }

        info!("服务管理器已关闭");
        Ok(())
    }

    /// 获取服务状态
    pub async fn get_service_status(&self) -> ServiceStatus {
        let initialized = self.is_initialized().await;
        let comfyui_connected = if let Ok(manager) = self.get_comfyui_manager().await {
            manager.is_connected().await
        } else {
            false
        };
        let realtime_monitor_running = if let Ok(monitor) = self.get_realtime_monitor().await {
            // TODO: 实现监控状态获取
            // monitor.get_monitor_stats().await.is_running
            false // 暂时返回 false
        } else {
            false
        };

        ServiceStatus {
            initialized,
            comfyui_connected,
            realtime_monitor_running,
        }
    }
}

/// 服务状态
#[derive(Debug, Clone)]
pub struct ServiceStatus {
    pub initialized: bool,
    pub comfyui_connected: bool,
    pub realtime_monitor_running: bool,
}
