use tauri::{command, State, AppHandle, Emitter};
use tracing::{info, error, warn};
use std::sync::Arc;
use anyhow::Result;
use chrono::Utc;

use crate::app_state::AppState;
use crate::data::models::outfit_photo_generation::{
    OutfitPhotoGenerationRequest, OutfitPhotoGenerationResponse, GenerationStatus, WorkflowProgress
};
use crate::business::services::outfit_photo_generation_service::{
    OutfitPhotoGenerationService, create_outfit_photo_prompt_id_based_progress_callback
};
use crate::business::services::cloud_upload_service::CloudUploadService;
use crate::config::AppConfig;

/// 创建穿搭照片生成任务
/// 遵循 Tauri 开发规范的命令设计原则
#[command]
pub async fn create_outfit_photo_generation_task(
    request: OutfitPhotoGenerationRequest,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("创建穿搭照片生成任务: {:?}", request);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 创建生成任务
    match service.create_generation_task(request).await {
        Ok(generation) => {
            info!("穿搭照片生成任务创建成功: {}", generation.id);
            Ok(generation.id)
        }
        Err(e) => {
            error!("创建穿搭照片生成任务失败: {}", e);
            Err(format!("创建任务失败: {}", e))
        }
    }
}

/// 执行穿搭照片生成
#[command]
pub async fn execute_outfit_photo_generation(
    generation_id: String,
    app_handle: AppHandle,
    state: State<'_, AppState>,
) -> Result<OutfitPhotoGenerationResponse, String> {
    info!("执行穿搭照片生成: {}", generation_id);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 创建进度回调函数，用于发送进度事件
    let app_handle_clone = app_handle.clone();
    let generation_id_clone = generation_id.clone();
    let progress_callback = move |progress: crate::data::models::outfit_photo_generation::WorkflowProgress| {
        let progress_event = serde_json::json!({
            "type": "generation_progress",
            "generation_id": generation_id_clone,
            "current_step": progress.current_step,
            "total_steps": progress.total_steps,
            "progress_percentage": progress.progress_percentage,
            "status_message": progress.status_message,
            "current_node_id": progress.current_node_id
        });

        if let Err(e) = app_handle_clone.emit("outfit_generation_progress", &progress_event) {
            error!("发送生成进度事件失败: {}", e);
        }
    };

    // 执行生成任务
    match service.execute_generation(&generation_id, progress_callback).await {
        Ok(response) => {
            info!("穿搭照片生成完成: {}", generation_id);

            // 发送完成事件
            let completion_event = serde_json::json!({
                "type": "generation_completed",
                "generation_id": generation_id,
                "status": response.status,
                "result_image_urls": response.result_image_urls,
                "generation_time_ms": response.generation_time_ms
            });

            if let Err(e) = app_handle.emit("outfit_generation_completed", &completion_event) {
                error!("发送生成完成事件失败: {}", e);
            }

            Ok(response)
        }
        Err(e) => {
            error!("执行穿搭照片生成失败: {}", e);

            // 发送失败事件
            let error_event = serde_json::json!({
                "type": "generation_failed",
                "generation_id": generation_id,
                "error_message": e.to_string()
            });

            if let Err(emit_err) = app_handle.emit("outfit_generation_failed", &error_event) {
                error!("发送生成失败事件失败: {}", emit_err);
            }

            Err(format!("执行生成失败: {}", e))
        }
    }
}

/// 批量执行穿搭照片生成
#[command]
pub async fn execute_outfit_photo_generation_batch(
    requests: Vec<OutfitPhotoGenerationRequest>,
    app_handle: AppHandle,
    state: State<'_, AppState>,
) -> Result<Vec<OutfitPhotoGenerationResponse>, String> {
    info!("开始批量执行穿搭照片生成，共 {} 个请求", requests.len());

    if requests.is_empty() {
        return Ok(Vec::new());
    }

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database.clone(),
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 创建基于 prompt_id 的进度回调函数
    let progress_callback = create_outfit_photo_prompt_id_based_progress_callback(
        database.clone(),
        app_handle.clone(),
    );

    // 执行批量生成（使用基于 prompt_id 的方法）
    match service.generate_batch_with_prompt_id_callback(requests, progress_callback).await {
        Ok(responses) => {
            info!("批量穿搭照片生成完成，共 {} 个响应", responses.len());

            // 发送批量完成事件
            let completion_event = serde_json::json!({
                "type": "batch_completed",
                "total": responses.len(),
                "successful": responses.iter().filter(|r| r.status == GenerationStatus::Completed).count(),
                "failed": responses.iter().filter(|r| r.status == GenerationStatus::Failed).count()
            });

            if let Err(e) = app_handle.emit("outfit_generation_batch_completed", &completion_event) {
                error!("发送批量完成事件失败: {}", e);
            }

            Ok(responses)
        }
        Err(e) => {
            error!("批量执行穿搭照片生成失败: {}", e);

            // 发送批量失败事件
            let error_event = serde_json::json!({
                "type": "batch_failed",
                "error_message": e.to_string()
            });

            if let Err(emit_err) = app_handle.emit("outfit_generation_batch_failed", &error_event) {
                error!("发送批量失败事件失败: {}", emit_err);
            }

            Err(format!("批量执行失败: {}", e))
        }
    }
}

/// 重试失败的穿搭照片生成
#[command]
pub async fn retry_outfit_photo_generation(
    generation_id: String,
    state: State<'_, AppState>,
) -> Result<OutfitPhotoGenerationResponse, String> {
    info!("重试穿搭照片生成: {}", generation_id);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 重试生成任务
    match service.retry_failed_uploads(&generation_id).await {
        Ok(response) => {
            info!("穿搭照片生成重试完成: {}", generation_id);
            Ok(response)
        }
        Err(e) => {
            error!("重试穿搭照片生成失败: {}", e);
            Err(format!("重试失败: {}", e))
        }
    }
}

/// 清理失败的生成记录
#[command]
pub async fn cleanup_failed_outfit_generations(
    max_age_hours: u64,
    state: State<'_, AppState>,
) -> Result<usize, String> {
    info!("清理 {} 小时前的失败生成记录", max_age_hours);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 执行清理操作
    match service.cleanup_failed_generations(max_age_hours).await {
        Ok(cleaned_count) => {
            info!("清理完成，共清理 {} 条记录", cleaned_count);
            Ok(cleaned_count)
        }
        Err(e) => {
            error!("清理失败生成记录失败: {}", e);
            Err(format!("清理失败: {}", e))
        }
    }
}

/// 获取云端上传状态统计
#[command]
pub async fn get_cloud_upload_statistics(
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("获取云端上传状态统计");

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 直接从数据库获取统计信息
    let database = state.get_database();
    let outfit_repo = match crate::data::repositories::outfit_photo_generation_repository::OutfitPhotoGenerationRepository::new(database) {
        Ok(repo) => repo,
        Err(e) => {
            error!("创建仓库失败: {}", e);
            return Err(format!("创建仓库失败: {}", e));
        }
    };

    // 获取所有生成记录进行统计
    match outfit_repo.get_all() {
        Ok(generations) => {
            let total_uploads = generations.len();
            let successful_uploads = generations.iter().filter(|g| g.status == GenerationStatus::Completed).count();
            let failed_uploads = generations.iter().filter(|g| g.status == GenerationStatus::Failed).count();
            let pending_uploads = generations.iter().filter(|g| g.status == GenerationStatus::Pending || g.status == GenerationStatus::Processing).count();

            let total_size_bytes: u64 = generations.iter()
                .map(|g| g.result_image_urls.len() as u64 * 1024 * 1024) // 估算每张图片1MB
                .sum();

            let average_upload_time_ms = if successful_uploads > 0 {
                generations.iter()
                    .filter_map(|g| g.generation_time_ms)
                    .sum::<u64>() / successful_uploads as u64
            } else {
                0
            };

            let last_upload_time = generations.iter()
                .filter(|g| g.status == GenerationStatus::Completed)
                .max_by_key(|g| g.updated_at)
                .map(|g| g.updated_at.to_rfc3339());

            let statistics = serde_json::json!({
                "total_uploads": total_uploads,
                "successful_uploads": successful_uploads,
                "failed_uploads": failed_uploads,
                "pending_uploads": pending_uploads,
                "total_size_bytes": total_size_bytes,
                "average_upload_time_ms": average_upload_time_ms,
                "last_upload_time": last_upload_time
            });

            Ok(statistics)
        }
        Err(e) => {
            error!("获取云端上传统计失败: {}", e);

            // 返回默认统计信息
            let statistics = serde_json::json!({
                "total_uploads": 0,
                "successful_uploads": 0,
                "failed_uploads": 0,
                "pending_uploads": 0,
                "total_size_bytes": 0,
                "average_upload_time_ms": 0,
                "last_upload_time": null,
                "error": e.to_string()
            });

            Ok(statistics)
        }
    }
}

/// 测试云端上传连接
#[command]
pub async fn test_cloud_upload_connection(
    _state: State<'_, AppState>,
) -> Result<bool, String> {
    info!("测试云端上传连接");

    // 创建云上传服务
    let cloud_upload_service = CloudUploadService::new();

    // 测试连接 - 通过创建一个简单的HTTP客户端测试基础URL的可达性
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(10))
        .build()
        .map_err(|e| format!("创建HTTP客户端失败: {}", e))?;

    let base_url = cloud_upload_service.get_base_url();

    match client.get(base_url).send().await {
        Ok(response) => {
            // 只要能收到响应就认为连接成功，不管状态码
            info!("云端上传连接测试成功，状态码: {}", response.status());
            Ok(true)
        }
        Err(e) => {
            warn!("云端上传连接测试失败: {}", e);
            Ok(false) // 连接失败但不返回错误，返回false表示连接不可用
        }
    }
}

/// 获取 ComfyUI 设置
#[command]
pub async fn get_comfyui_settings(
    _state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    let config = crate::config::AppConfig::load();
    let settings = config.get_comfyui_settings();

    match serde_json::to_value(settings) {
        Ok(value) => Ok(value),
        Err(e) => {
            error!("序列化 ComfyUI 设置失败: {}", e);
            Err(format!("获取 ComfyUI 设置失败: {}", e))
        }
    }
}

/// 更新 ComfyUI 设置
#[command]
pub async fn update_comfyui_settings(
    settings: serde_json::Value,
    _state: State<'_, AppState>,
) -> Result<(), String> {
    info!("更新 ComfyUI 设置: {:?}", settings);

    let comfyui_settings = match serde_json::from_value(settings) {
        Ok(settings) => settings,
        Err(e) => {
            error!("反序列化 ComfyUI 设置失败: {}", e);
            return Err(format!("无效的 ComfyUI 设置: {}", e));
        }
    };

    let mut config = crate::config::AppConfig::load();
    config.update_comfyui_settings(comfyui_settings);

    match config.save() {
        Ok(_) => {
            info!("ComfyUI 设置保存成功");
            Ok(())
        }
        Err(e) => {
            error!("保存 ComfyUI 设置失败: {}", e);
            Err(format!("保存 ComfyUI 设置失败: {}", e))
        }
    }
}

/// 测试 ComfyUI 连接
#[command]
pub async fn test_comfyui_connection(
    _state: State<'_, AppState>,
) -> Result<bool, String> {
    info!("测试 ComfyUI 连接");

    let config = crate::config::AppConfig::load();
    let settings = config.get_comfyui_settings().clone();

    if !settings.enabled {
        return Err("ComfyUI 功能未启用".to_string());
    }

    let service = crate::business::services::comfyui_service::ComfyUIService::new(settings);

    match service.check_connection().await {
        Ok(connected) => {
            if connected {
                info!("ComfyUI 连接测试成功");
            } else {
                info!("ComfyUI 连接测试失败");
            }
            Ok(connected)
        }
        Err(e) => {
            error!("ComfyUI 连接测试出错: {}", e);
            Err(format!("ComfyUI 连接测试失败: {}", e))
        }
    }
}

/// 获取穿搭照片生成历史记录
#[command]
pub async fn get_outfit_photo_generation_history(
    project_id: String,
    limit: Option<u32>,
    offset: Option<u32>,
    state: State<'_, AppState>,
) -> Result<Vec<serde_json::Value>, String> {
    info!("获取穿搭照片生成历史记录: project_id={}, limit={:?}, offset={:?}",
          project_id, limit, offset);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 直接从数据库获取历史记录
    let database = state.get_database();
    let outfit_repo = match crate::data::repositories::outfit_photo_generation_repository::OutfitPhotoGenerationRepository::new(database) {
        Ok(repo) => repo,
        Err(e) => {
            error!("创建仓库失败: {}", e);
            return Err(format!("创建仓库失败: {}", e));
        }
    };

    // 获取历史记录
    let generations = if let (Some(limit), Some(offset)) = (limit, offset) {
        outfit_repo.get_by_project_id_paginated(&project_id, limit, offset)
    } else {
        outfit_repo.get_by_project_id(&project_id)
    };

    match generations {
        Ok(generations) => {
            let history: Vec<serde_json::Value> = generations
                .into_iter()
                .map(|gen| serde_json::json!({
                    "id": gen.id,
                    "project_id": gen.project_id,
                    "model_id": gen.model_id,
                    "product_image_path": gen.product_image_path,
                    "product_image_url": gen.product_image_url,
                    "prompt": gen.prompt,
                    "negative_prompt": gen.negative_prompt,
                    "status": gen.status,
                    "result_image_urls": gen.result_image_urls,
                    "error_message": gen.error_message,
                    "generation_time_ms": gen.generation_time_ms,
                    "created_at": gen.created_at,
                    "updated_at": gen.updated_at
                }))
                .collect();

            Ok(history)
        }
        Err(e) => {
            error!("获取穿搭照片生成历史记录失败: {}", e);
            Err(format!("获取历史记录失败: {}", e))
        }
    }
}

/// 删除穿搭照片生成记录
#[command]
pub async fn delete_outfit_photo_generation(
    generation_id: String,
    state: State<'_, AppState>,
) -> Result<(), String> {
    info!("删除穿搭照片生成记录: {}", generation_id);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 不需要创建服务，直接使用仓库操作

    // 直接从数据库删除生成记录
    let database = state.get_database();
    let outfit_repo = match crate::data::repositories::outfit_photo_generation_repository::OutfitPhotoGenerationRepository::new(database) {
        Ok(repo) => repo,
        Err(e) => {
            error!("创建仓库失败: {}", e);
            return Err(format!("创建仓库失败: {}", e));
        }
    };

    // 删除生成记录
    match outfit_repo.delete(&generation_id) {
        Ok(_) => {
            info!("穿搭照片生成记录删除成功: {}", generation_id);
            Ok(())
        }
        Err(e) => {
            error!("删除穿搭照片生成记录失败: {}", e);
            Err(format!("删除记录失败: {}", e))
        }
    }
}

/// 重新生成穿搭照片
#[command]
pub async fn regenerate_outfit_photo(
    generation_id: String,
    app_handle: AppHandle,
    state: State<'_, AppState>,
) -> Result<OutfitPhotoGenerationResponse, String> {
    info!("重新生成穿搭照片: {}", generation_id);

    // 获取数据库连接
    let database = state.get_database();

    // 创建云上传服务
    let config = Arc::new(tokio::sync::Mutex::new(AppConfig::load()));
    let cloud_upload_service = Arc::new(CloudUploadService::new());

    // 创建穿搭照片生成服务
    let service = match OutfitPhotoGenerationService::new(
        database,
        config,
        cloud_upload_service,
    ) {
        Ok(service) => service,
        Err(e) => {
            error!("创建穿搭照片生成服务失败: {}", e);
            return Err(format!("创建服务失败: {}", e));
        }
    };

    // 创建进度回调函数
    let app_handle_clone = app_handle.clone();
    let generation_id_clone = generation_id.clone();
    let progress_callback = move |progress: crate::data::models::outfit_photo_generation::WorkflowProgress| {
        let progress_event = serde_json::json!({
            "type": "regeneration_progress",
            "generation_id": generation_id_clone,
            "current_step": progress.current_step,
            "total_steps": progress.total_steps,
            "progress_percentage": progress.progress_percentage,
            "status_message": progress.status_message,
            "current_node_id": progress.current_node_id
        });

        if let Err(e) = app_handle_clone.emit("outfit_regeneration_progress", &progress_event) {
            error!("发送重新生成进度事件失败: {}", e);
        }
    };

    // 重新生成穿搭照片 - 先获取原始记录，然后重新执行生成
    let database = state.get_database();
    let outfit_repo = match crate::data::repositories::outfit_photo_generation_repository::OutfitPhotoGenerationRepository::new(database.clone()) {
        Ok(repo) => repo,
        Err(e) => {
            error!("创建仓库失败: {}", e);
            return Err(format!("创建仓库失败: {}", e));
        }
    };

    // 验证生成记录存在
    match outfit_repo.get_by_id(&generation_id) {
        Ok(Some(_gen)) => {
            // 记录存在，继续执行
        }
        Ok(None) => {
            return Err("生成记录不存在".to_string());
        }
        Err(e) => {
            error!("获取生成记录失败: {}", e);
            return Err(format!("获取生成记录失败: {}", e));
        }
    };

    // 重新执行生成
    match service.execute_generation(&generation_id, progress_callback).await {
        Ok(response) => {
            info!("穿搭照片重新生成完成: {}", generation_id);

            // 发送完成事件
            let completion_event = serde_json::json!({
                "type": "regeneration_completed",
                "generation_id": generation_id,
                "status": response.status,
                "result_image_urls": response.result_image_urls,
                "generation_time_ms": response.generation_time_ms
            });

            if let Err(e) = app_handle.emit("outfit_regeneration_completed", &completion_event) {
                error!("发送重新生成完成事件失败: {}", e);
            }

            Ok(response)
        }
        Err(e) => {
            error!("重新生成穿搭照片失败: {}", e);

            // 发送失败事件
            let error_event = serde_json::json!({
                "type": "regeneration_failed",
                "generation_id": generation_id,
                "error_message": e.to_string()
            });

            if let Err(emit_err) = app_handle.emit("outfit_regeneration_failed", &error_event) {
                error!("发送重新生成失败事件失败: {}", emit_err);
            }

            Err(format!("重新生成失败: {}", e))
        }
    }
}

/// 取消穿搭照片生成
#[command]
pub async fn cancel_outfit_photo_generation(
    generation_id: String,
    state: State<'_, AppState>,
) -> Result<(), String> {
    info!("取消穿搭照片生成: {}", generation_id);

    // 获取数据库连接
    let database = state.get_database();

    // 不需要创建服务，直接使用仓库操作

    // 取消生成任务 - 直接更新数据库状态为已取消
    let database = state.get_database();
    let outfit_repo = match crate::data::repositories::outfit_photo_generation_repository::OutfitPhotoGenerationRepository::new(database) {
        Ok(repo) => repo,
        Err(e) => {
            error!("创建仓库失败: {}", e);
            return Err(format!("创建仓库失败: {}", e));
        }
    };

    // 获取生成记录并更新状态
    match outfit_repo.get_by_id(&generation_id) {
        Ok(Some(mut generation)) => {
            // 只有处理中或等待中的任务才能取消
            if generation.status == GenerationStatus::Processing || generation.status == GenerationStatus::Pending {
                generation.update_status(GenerationStatus::Cancelled);
                generation.error_message = Some("用户取消".to_string());

                match outfit_repo.update(&generation) {
                    Ok(_) => {
                        info!("穿搭照片生成已取消: {}", generation_id);
                        Ok(())
                    }
                    Err(e) => {
                        error!("更新生成记录失败: {}", e);
                        Err(format!("更新记录失败: {}", e))
                    }
                }
            } else {
                Err(format!("无法取消状态为 {:?} 的生成任务", generation.status))
            }
        }
        Ok(None) => Err("生成记录不存在".to_string()),
        Err(e) => {
            error!("获取生成记录失败: {}", e);
            Err(format!("获取生成记录失败: {}", e))
        }
    }
}

/// 获取工作流列表
#[command]
pub async fn get_workflow_list(
    _state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    info!("获取工作流列表");

    let config = crate::config::AppConfig::load();
    let workflow_dir = config.get_comfyui_settings().workflow_directory
        .as_deref()
        .unwrap_or("workflows");

    match std::fs::read_dir(workflow_dir) {
        Ok(entries) => {
            let mut workflows = Vec::new();
            for entry in entries {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if path.extension().and_then(|s| s.to_str()) == Some("json") {
                        if let Some(filename) = path.file_name().and_then(|s| s.to_str()) {
                            workflows.push(filename.to_string());
                        }
                    }
                }
            }
            Ok(workflows)
        }
        Err(e) => {
            error!("读取工作流目录失败: {}", e);
            Err(format!("读取工作流目录失败: {}", e))
        }
    }
}
