//! ComfyUI V2 核心业务服务
//! 提供完整的 ComfyUI 集成功能，包括连接管理、工作流执行、模板管理等

use anyhow::{Result, anyhow};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::{RwLock, Mutex};
use tracing::{info, warn, error, debug};
use serde::{Serialize, Deserialize};
use uuid::Uuid;

use comfyui_sdk::ComfyUIClient;
use comfyui_sdk::types::{ComfyUIClientConfig, ComfyUIWorkflow, PromptRequest, ExecutionOptions, ParameterValues};
use comfyui_sdk::templates::WorkflowInstance;

use crate::data::models::comfyui::{
    WorkflowModel, TemplateModel, ExecutionModel, ExecutionStatus,
    ExecuteWorkflowRequest
};
use crate::presentation::commands::comfyui_v2_commands::{
    CreateWorkflowRequest, UpdateWorkflowRequest, CreateTemplateRequest, ExecuteTemplateRequest
};
use crate::data::repositories::comfyui_repository::ComfyUIRepository;
use crate::business::services::realtime_monitor_v2::RealtimeMonitorV2;
use crate::business::services::queue_manager::QueueManager;
use crate::business::services::template_engine::TemplateEngine;

/// ComfyUI V2 配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComfyUIV2Config {
    pub base_url: String,
    pub timeout: Option<u64>,
    pub retry_attempts: Option<u32>,
    pub enable_cache: Option<bool>,
    pub max_concurrency: Option<u32>,
    pub websocket_url: Option<String>,
    pub timeout_seconds: Option<u64>,
    pub retry_delay_ms: Option<u64>,
    pub enable_websocket: Option<bool>,
    pub custom_headers: Option<std::collections::HashMap<String, String>>,
}

impl Default for ComfyUIV2Config {
    fn default() -> Self {
        Self {
            base_url: "http://127.0.0.1:8188".to_string(),
            timeout: Some(30000),
            retry_attempts: Some(3),
            enable_cache: Some(true),
            max_concurrency: Some(4),
            websocket_url: Some("ws://127.0.0.1:8188/ws".to_string()),
            timeout_seconds: Some(300),
            retry_delay_ms: Some(1000),
            enable_websocket: Some(true),
            custom_headers: None,
        }
    }
}

/// 连接状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionStatus {
    pub connected: bool,
    pub last_connected_at: Option<String>,
    pub last_disconnected_at: Option<String>,
    pub reconnect_attempts: u32,
    pub total_connections: u32,
    pub error_message: Option<String>,
}

/// 系统信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    pub version: String,
    pub python_version: String,
    pub platform: String,
    pub gpu_info: Option<String>,
    pub memory_info: Option<String>,
    pub disk_info: Option<String>,
}

/// 队列状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueueStatus {
    pub running_count: u32,
    pub pending_count: u32,
    pub history_count: u32,
}

/// ComfyUI V2 核心服务
pub struct ComfyUIV2Service {
    /// 配置
    config: Arc<RwLock<ComfyUIV2Config>>,
    /// ComfyUI 客户端
    client: Arc<RwLock<Option<ComfyUIClient>>>,
    /// 连接状态
    connection_status: Arc<RwLock<ConnectionStatus>>,
    /// 数据仓库
    repository: Arc<ComfyUIRepository>,
    /// 实时监控服务
    realtime_monitor: Arc<RealtimeMonitorV2>,
    /// 队列管理器
    queue_manager: Arc<QueueManager>,
    /// 模板引擎
    template_engine: Arc<TemplateEngine>,
    /// 是否正在运行
    is_running: Arc<RwLock<bool>>,
}

impl ComfyUIV2Service {
    /// 创建新的 ComfyUI V2 服务
    pub fn new(
        repository: Arc<ComfyUIRepository>,
        realtime_monitor: Arc<RealtimeMonitorV2>,
        queue_manager: Arc<QueueManager>,
        template_engine: Arc<TemplateEngine>,
    ) -> Self {
        Self {
            config: Arc::new(RwLock::new(ComfyUIV2Config::default())),
            client: Arc::new(RwLock::new(None)),
            connection_status: Arc::new(RwLock::new(ConnectionStatus {
                connected: false,
                last_connected_at: None,
                last_disconnected_at: None,
                reconnect_attempts: 0,
                total_connections: 0,
                error_message: None,
            })),
            repository,
            realtime_monitor,
            queue_manager,
            template_engine,
            is_running: Arc::new(RwLock::new(false)),
        }
    }

    // ==================== 连接管理 ====================

    /// 连接到 ComfyUI 服务
    pub async fn connect(&self, config: ComfyUIV2Config) -> Result<String> {
        info!("连接到 ComfyUI 服务: {}", config.base_url);

        // 更新配置
        {
            let mut config_guard = self.config.write().await;
            *config_guard = config.clone();
        }

        // 创建 ComfyUI 客户端配置
        let client_config = ComfyUIClientConfig {
            base_url: config.base_url.clone(),
            timeout: Some(Duration::from_millis(config.timeout.unwrap_or(30000))),
            retry_attempts: Some(config.retry_attempts.unwrap_or(3)),
            retry_delay: Some(Duration::from_millis(1000)),
            headers: None,
        };

        // 创建客户端
        match ComfyUIClient::new(client_config) {
            Ok(client) => {
                // 测试连接
                match client.http().get_queue().await {
                    Ok(_) => {
                        // 保存客户端
                        {
                            let mut client_guard = self.client.write().await;
                            *client_guard = Some(client);
                        }

                        // 更新连接状态
                        {
                            let mut status = self.connection_status.write().await;
                            status.connected = true;
                            status.last_connected_at = Some(
                                SystemTime::now()
                                    .duration_since(UNIX_EPOCH)
                                    .unwrap()
                                    .as_secs()
                                    .to_string()
                            );
                            status.total_connections += 1;
                            status.error_message = None;
                        }

                        // 启动实时监控
                        if let Err(e) = self.realtime_monitor.start().await {
                            warn!("启动实时监控失败: {}", e);
                        }

                        {
                            let mut running = self.is_running.write().await;
                            *running = true;
                        }

                        info!("成功连接到 ComfyUI 服务");
                        Ok("连接成功".to_string())
                    }
                    Err(e) => {
                        error!("ComfyUI 连接测试失败: {}", e);
                        
                        // 更新连接状态
                        {
                            let mut status = self.connection_status.write().await;
                            status.connected = false;
                            status.error_message = Some(format!("连接测试失败: {}", e));
                        }

                        Err(anyhow!("连接失败: {}", e))
                    }
                }
            }
            Err(e) => {
                error!("创建 ComfyUI 客户端失败: {}", e);
                
                // 更新连接状态
                {
                    let mut status = self.connection_status.write().await;
                    status.connected = false;
                    status.error_message = Some(format!("客户端创建失败: {}", e));
                }

                Err(anyhow!("连接失败: {}", e))
            }
        }
    }

    /// 断开 ComfyUI 连接
    pub async fn disconnect(&self) -> Result<String> {
        info!("断开 ComfyUI 连接");

        // 停止实时监控
        if let Err(e) = self.realtime_monitor.stop().await {
            warn!("停止实时监控失败: {}", e);
        }

        // 清除客户端
        {
            let mut client_guard = self.client.write().await;
            *client_guard = None;
        }

        // 更新连接状态
        {
            let mut status = self.connection_status.write().await;
            status.connected = false;
            status.last_disconnected_at = Some(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs()
                    .to_string()
            );
            status.error_message = None;
        }

        {
            let mut running = self.is_running.write().await;
            *running = false;
        }

        info!("已断开 ComfyUI 连接");
        Ok("断开连接成功".to_string())
    }

    /// 检查是否已连接
    pub async fn is_connected(&self) -> bool {
        let status = self.connection_status.read().await;
        status.connected
    }

    /// 获取连接状态
    pub async fn get_connection_status(&self) -> ConnectionStatus {
        self.connection_status.read().await.clone()
    }

    /// 健康检查
    pub async fn health_check(&self) -> Result<String> {
        let client_guard = self.client.read().await;
        if let Some(client) = client_guard.as_ref() {
            match client.http().get_queue().await {
                Ok(_) => Ok("healthy".to_string()),
                Err(e) => {
                    error!("健康检查失败: {}", e);
                    Err(anyhow!("健康检查失败: {}", e))
                }
            }
        } else {
            Err(anyhow!("未连接到 ComfyUI 服务"))
        }
    }

    /// 获取系统信息
    pub async fn get_system_info(&self) -> Result<SystemInfo> {
        let client_guard = self.client.read().await;
        if let Some(client) = client_guard.as_ref() {
            match client.get_system_stats().await {
                Ok(info) => Ok(SystemInfo {
                    version: "unknown".to_string(), // 版本信息需要从其他地方获取
                    python_version: info.system.python_version.clone(),
                    platform: info.system.os.clone(),
                    gpu_info: info.devices.first().map(|d| format!("{:?}", d)),
                    memory_info: None, // 内存信息需要从其他地方获取
                    disk_info: None, // 磁盘信息需要从其他地方获取
                }),
                Err(e) => {
                    error!("获取系统信息失败: {}", e);
                    Err(anyhow!("获取系统信息失败: {}", e))
                }
            }
        } else {
            Err(anyhow!("未连接到 ComfyUI 服务"))
        }
    }

    /// 获取队列状态
    pub async fn get_queue_status(&self) -> Result<QueueStatus> {
        let client_guard = self.client.read().await;
        if let Some(client) = client_guard.as_ref() {
            match client.get_queue_status().await {
                Ok(status) => Ok(QueueStatus {
                    running_count: status.queue_running.len() as u32,
                    pending_count: status.queue_pending.len() as u32,
                    history_count: 0, // 历史记录需要单独获取
                }),
                Err(e) => {
                    error!("获取队列状态失败: {}", e);
                    Err(anyhow!("获取队列状态失败: {}", e))
                }
            }
        } else {
            Err(anyhow!("未连接到 ComfyUI 服务"))
        }
    }

    // ==================== 配置管理 ====================

    /// 获取配置
    pub async fn get_config(&self) -> ComfyUIV2Config {
        self.config.read().await.clone()
    }

    /// 更新配置
    pub async fn update_config(&self, config: ComfyUIV2Config) -> Result<String> {
        info!("更新 ComfyUI V2 配置");

        {
            let mut config_guard = self.config.write().await;
            *config_guard = config;
        }

        Ok("配置更新成功".to_string())
    }

    /// 验证配置
    pub async fn validate_config(&self, config: ComfyUIV2Config) -> Result<String> {
        // 验证 URL 格式
        if !config.base_url.starts_with("http://") && !config.base_url.starts_with("https://") {
            return Err(anyhow!("无效的 base_url 格式"));
        }

        // 验证超时时间
        if let Some(timeout) = config.timeout {
            if timeout < 1000 || timeout > 300000 {
                return Err(anyhow!("超时时间必须在 1000-300000 毫秒之间"));
            }
        }

        // 验证重试次数
        if let Some(retry_attempts) = config.retry_attempts {
            if retry_attempts > 10 {
                return Err(anyhow!("重试次数不能超过 10 次"));
            }
        }

        // 验证并发数
        if let Some(max_concurrency) = config.max_concurrency {
            if max_concurrency < 1 || max_concurrency > 16 {
                return Err(anyhow!("最大并发数必须在 1-16 之间"));
            }
        }

        Ok("valid".to_string())
    }

    /// 检查是否正在运行
    pub async fn is_running(&self) -> bool {
        *self.is_running.read().await
    }

    // ==================== 工作流管理 ====================

    /// 创建工作流
    pub async fn create_workflow(&self, request: CreateWorkflowRequest) -> Result<WorkflowModel> {
        info!("创建工作流: {}", request.name);

        // 验证工作流数据
        // 将 JSON 转换为 ComfyUIWorkflow 进行验证
        let workflow_data: ComfyUIWorkflow = serde_json::from_value(request.workflow_json.clone())
            .map_err(|e| anyhow!("工作流数据格式错误: {}", e))?;

        if let Err(e) = self.validate_workflow_data(&workflow_data) {
            return Err(anyhow!("工作流数据验证失败: {}", e));
        }

        // 创建工作流模型
        // 使用已经转换的工作流数据

        let workflow = WorkflowModel {
            id: Uuid::new_v4().to_string(),
            name: request.name,
            description: request.description,
            workflow_data,
            version: "1.0".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            enabled: true,
            tags: request.tags.unwrap_or_default(),
            category: None,
        };

        // 保存到数据库
        match self.repository.create_workflow(&workflow) {
            Ok(_) => {
                info!("工作流创建成功: {}", workflow.id);
                Ok(workflow)
            }
            Err(e) => {
                error!("保存工作流失败: {}", e);
                Err(anyhow!("保存工作流失败: {}", e))
            }
        }
    }

    /// 获取工作流列表
    pub async fn list_workflows(&self, _category: Option<String>, _tags: Option<Vec<String>>) -> Result<Vec<WorkflowModel>> {
        debug!("获取工作流列表");

        match self.repository.list_workflows(false) {
            Ok(workflows) => {
                debug!("获取到 {} 个工作流", workflows.len());
                Ok(workflows)
            }
            Err(e) => {
                error!("获取工作流列表失败: {}", e);
                Err(anyhow!("获取工作流列表失败: {}", e))
            }
        }
    }

    /// 获取单个工作流
    pub async fn get_workflow(&self, id: String) -> Result<WorkflowModel> {
        debug!("获取工作流: {}", id);

        match self.repository.get_workflow(&id) {
            Ok(Some(workflow)) => Ok(workflow),
            Ok(None) => Err(anyhow!("工作流不存在: {}", id)),
            Err(e) => {
                error!("获取工作流失败: {}", e);
                Err(anyhow!("获取工作流失败: {}", e))
            }
        }
    }

    /// 更新工作流
    pub async fn update_workflow(&self, id: String, request: UpdateWorkflowRequest) -> Result<WorkflowModel> {
        info!("更新工作流: {}", id);

        // 1. 获取现有工作流
        let mut workflow = match self.repository.get_workflow(&id) {
            Ok(Some(workflow)) => workflow,
            Ok(None) => return Err(anyhow!("工作流不存在: {}", id)),
            Err(e) => {
                error!("获取工作流失败: {}", e);
                return Err(anyhow!("获取工作流失败: {}", e));
            }
        };

        // 2. 更新字段
        if let Some(name) = request.name {
            workflow.name = name;
        }

        if let Some(description) = request.description {
            workflow.description = Some(description);
        }

        if let Some(workflow_json) = request.workflow_json {
            // 验证工作流数据格式
            let workflow_data: ComfyUIWorkflow = serde_json::from_value(workflow_json)
                .map_err(|e| anyhow!("工作流数据格式错误: {}", e))?;

            // 验证工作流数据
            if let Err(e) = self.validate_workflow_data(&workflow_data) {
                return Err(anyhow!("工作流数据验证失败: {}", e));
            }

            workflow.workflow_data = workflow_data;
        }

        if let Some(tags) = request.tags {
            workflow.tags = tags;
        }

        // 3. 更新时间戳
        workflow.updated_at = chrono::Utc::now();

        // 4. 保存到数据库
        match self.repository.update_workflow(&workflow) {
            Ok(_) => {
                info!("工作流更新成功: {}", workflow.id);
                Ok(workflow)
            }
            Err(e) => {
                error!("保存工作流失败: {}", e);
                Err(anyhow!("保存工作流失败: {}", e))
            }
        }
    }

    /// 删除工作流
    pub async fn delete_workflow(&self, id: String) -> Result<String> {
        info!("删除工作流: {}", id);

        // 检查工作流是否存在
        match self.repository.get_workflow(&id) {
            Ok(Some(_)) => {},
            Ok(None) => return Err(anyhow!("工作流不存在: {}", id)),
            Err(e) => return Err(anyhow!("获取工作流失败: {}", e)),
        }

        // 删除工作流
        match self.repository.delete_workflow(&id) {
            Ok(_) => {
                info!("工作流删除成功: {}", id);
                Ok("工作流删除成功".to_string())
            }
            Err(e) => {
                error!("删除工作流失败: {}", e);
                Err(anyhow!("删除工作流失败: {}", e))
            }
        }
    }

    /// 搜索工作流
    pub async fn search_workflows(&self, query: String, _category: Option<String>) -> Result<Vec<WorkflowModel>> {
        debug!("搜索工作流: {}", query);

        match self.repository.search_workflows(&query) {
            Ok(workflows) => {
                debug!("搜索到 {} 个工作流", workflows.len());
                Ok(workflows)
            }
            Err(e) => {
                error!("搜索工作流失败: {}", e);
                Err(anyhow!("搜索工作流失败: {}", e))
            }
        }
    }

    /// 按分类获取工作流
    pub async fn get_workflows_by_category(&self, category: String) -> Result<Vec<WorkflowModel>> {
        debug!("按分类获取工作流: {}", category);

        match self.repository.get_workflows_by_category(&category) {
            Ok(workflows) => {
                debug!("分类 {} 下有 {} 个工作流", category, workflows.len());
                Ok(workflows)
            }
            Err(e) => {
                error!("按分类获取工作流失败: {}", e);
                Err(anyhow!("按分类获取工作流失败: {}", e))
            }
        }
    }

    /// 验证工作流数据
    fn validate_workflow_data(&self, workflow_data: &ComfyUIWorkflow) -> Result<()> {
        // 检查是否为空
        if workflow_data.is_empty() {
            return Err(anyhow!("工作流数据不能为空"));
        }

        // 基本验证：检查是否有节点
        if workflow_data.len() == 0 {
            return Err(anyhow!("工作流必须包含至少一个节点"));
        }

        // TODO: 添加更详细的工作流验证逻辑
        // - 验证节点类型
        // - 验证节点连接
        // - 验证必需参数

        Ok(())
    }

    // ==================== 模板管理 ====================

    /// 创建模板
    pub async fn create_template(&self, request: CreateTemplateRequest) -> Result<TemplateModel> {
        info!("创建模板: {}", request.name);

        // TODO: 实现模板创建逻辑
        // 当前 CreateTemplateRequest 结构与 TemplateModel 不匹配
        // 需要重新设计 API 结构或适配现有结构

        Err(anyhow!("模板创建功能暂未实现 - 需要重新设计 API 结构"))
    }

    /// 获取模板列表
    pub async fn list_templates(&self, _category: Option<String>, _tags: Option<Vec<String>>) -> Result<Vec<TemplateModel>> {
        debug!("获取模板列表");

        match self.repository.list_templates(false) {
            Ok(templates) => {
                debug!("获取到 {} 个模板", templates.len());
                Ok(templates)
            }
            Err(e) => {
                error!("获取模板列表失败: {}", e);
                Err(anyhow!("获取模板列表失败: {}", e))
            }
        }
    }

    /// 获取单个模板
    pub async fn get_template(&self, id: String) -> Result<TemplateModel> {
        debug!("获取模板: {}", id);

        match self.repository.get_template(&id) {
            Ok(Some(template)) => Ok(template),
            Ok(None) => Err(anyhow!("模板不存在: {}", id)),
            Err(e) => {
                error!("获取模板失败: {}", e);
                Err(anyhow!("获取模板失败: {}", e))
            }
        }
    }

    /// 删除模板
    pub async fn delete_template(&self, id: String) -> Result<String> {
        info!("删除模板: {}", id);

        // 检查模板是否存在
        match self.repository.get_template(&id) {
            Ok(Some(_)) => {},
            Ok(None) => return Err(anyhow!("模板不存在: {}", id)),
            Err(e) => return Err(anyhow!("获取模板失败: {}", e)),
        }

        // 删除模板
        match self.repository.delete_template(&id) {
            Ok(_) => {
                info!("模板删除成功: {}", id);
                Ok("模板删除成功".to_string())
            }
            Err(e) => {
                error!("删除模板失败: {}", e);
                Err(anyhow!("删除模板失败: {}", e))
            }
        }
    }

    // ==================== 执行管理 ====================

    /// 执行工作流
    pub async fn execute_workflow(&self, workflow_id: String, parameters: HashMap<String, serde_json::Value>) -> Result<ExecutionModel> {
        info!("执行工作流: {}", workflow_id);

        // 1. 获取工作流
        let workflow = self.repository.get_workflow(&workflow_id)?
            .ok_or_else(|| anyhow!("工作流不存在: {}", workflow_id))?;

        // 2. 检查连接状态
        if !self.is_connected().await {
            return Err(anyhow!("ComfyUI 服务未连接"));
        }

        // 3. 创建执行记录
        let execution_id = Uuid::new_v4().to_string();
        let mut execution = ExecutionModel::new("temp_prompt_id".to_string());
        execution.id = execution_id.clone();
        execution.workflow_id = Some(workflow_id.clone());
        execution.status = ExecutionStatus::Running;
        execution.parameters = Some(parameters.clone());

        // 4. 保存执行记录
        self.repository.create_execution(&execution)?;

        // 5. 使用SDK执行工作流
        let result = {
            let client_guard = self.client.read().await;
            match client_guard.as_ref() {
                Some(client) => {
                    // 将工作流数据转换为HashMap<String, serde_json::Value>
                    let workflow_map: HashMap<String, serde_json::Value> = workflow.workflow_data
                        .into_iter()
                        .map(|(k, v)| (k, serde_json::to_value(v).unwrap_or(serde_json::Value::Null)))
                        .collect();

                    // 创建提示请求
                    let prompt_request = PromptRequest {
                        prompt: workflow_map,
                        client_id: Some(execution_id.clone()),
                        extra_data: None,
                    };

                    client.http().queue_prompt(&prompt_request).await
                }
                None => return Err(anyhow!("ComfyUI 客户端未初始化")),
            }
        };

        match result {
            Ok(response) => {
                let prompt_id = response.prompt_id;
                info!("工作流提交成功，prompt_id: {}", prompt_id);

                // 更新执行记录
                let mut updated_execution = execution;
                updated_execution.prompt_id = prompt_id.clone();
                updated_execution.status = ExecutionStatus::Running;

                self.repository.update_execution(&updated_execution)?;

                Ok(updated_execution)
            }
            Err(e) => {
                error!("工作流执行失败: {}", e);

                // 更新执行记录为失败状态
                let mut failed_execution = execution;
                failed_execution.status = ExecutionStatus::Failed;
                failed_execution.error_message = Some(e.to_string());
                failed_execution.completed_at = Some(chrono::Utc::now());

                self.repository.update_execution(&failed_execution)?;

                Err(anyhow!("工作流执行失败: {}", e))
            }
        }
    }

    /// 执行模板
    pub async fn execute_template(&self, request: ExecuteTemplateRequest) -> Result<ExecutionModel> {
        info!("执行模板: {}", request.template_id);

        // TODO: 实现模板执行逻辑
        // 需要重新设计 API 结构或适配现有结构

        Err(anyhow!("模板执行功能暂未实现 - 需要重新设计 API 结构"))
    }

    /// 取消执行
    pub async fn cancel_execution(&self, execution_id: String) -> Result<String> {
        info!("取消执行: {}", execution_id);

        // 获取执行记录
        let execution = match self.repository.get_execution(&execution_id) {
            Ok(Some(execution)) => execution,
            Ok(None) => return Err(anyhow!("执行记录不存在: {}", execution_id)),
            Err(e) => return Err(anyhow!("获取执行记录失败: {}", e)),
        };

        // 检查执行状态
        match execution.status {
            ExecutionStatus::Completed | ExecutionStatus::Failed | ExecutionStatus::Cancelled => {
                return Err(anyhow!("执行已完成，无法取消"));
            }
            _ => {}
        }

        // 从队列管理器取消任务
        if let Err(e) = self.queue_manager.cancel_task(&execution_id).await {
            warn!("从队列取消任务失败: {}", e);
        }

        // 如果有 prompt_id，尝试从 ComfyUI 取消
        if !execution.prompt_id.is_empty() {
            let client_guard = self.client.read().await;
            if let Some(client) = client_guard.as_ref() {
                if let Err(e) = client.http().cancel_prompt(&execution.prompt_id).await {
                    warn!("从 ComfyUI 取消任务失败: {}", e);
                }
            }
        }

        // 更新执行状态
        let mut cancelled_execution = execution;
        cancelled_execution.status = ExecutionStatus::Cancelled;
        cancelled_execution.completed_at = Some(chrono::Utc::now());

        match self.repository.update_execution(&cancelled_execution) {
            Ok(_) => {
                info!("执行取消成功: {}", execution_id);
                Ok("执行取消成功".to_string())
            }
            Err(e) => {
                error!("更新执行状态失败: {}", e);
                Err(anyhow!("更新执行状态失败: {}", e))
            }
        }
    }

    /// 获取执行历史
    pub async fn get_execution_history(&self, limit: Option<u32>) -> Result<Vec<ExecutionModel>> {
        debug!("获取执行历史");

        match self.repository.list_executions(limit, None) {
            Ok(executions) => {
                debug!("获取到 {} 个执行记录", executions.len());
                Ok(executions)
            }
            Err(e) => {
                error!("获取执行历史失败: {}", e);
                Err(anyhow!("获取执行历史失败: {}", e))
            }
        }
    }

    /// 获取执行状态
    pub async fn get_execution_status(&self, execution_id: String) -> Result<ExecutionModel> {
        debug!("获取执行状态: {}", execution_id);

        match self.repository.get_execution(&execution_id) {
            Ok(Some(execution)) => Ok(execution),
            Ok(None) => Err(anyhow!("执行记录不存在: {}", execution_id)),
            Err(e) => {
                error!("获取执行状态失败: {}", e);
                Err(anyhow!("获取执行状态失败: {}", e))
            }
        }
    }

    /// 清理已完成的执行记录
    pub async fn cleanup_completed_executions(&self) -> Result<String> {
        info!("清理已完成的执行记录");

        // TODO: 实现清理逻辑
        // 当前 repository 没有 cleanup_completed_executions 方法

        Err(anyhow!("清理功能暂未实现 - 需要在 repository 中添加相应方法"))
    }
}
