use tauri::{command, State};
use tracing::{info, error};
use serde_json::Value;

use crate::app_state::AppState;
use crate::business::services::workflow_management_service::{
    WorkflowManagementService, WorkflowMetadata, WorkflowValidationResult
};
use crate::config::AppConfig;

/// 扫描工作流目录
/// 遵循 Tauri 开发规范的命令设计原则
#[command]
pub async fn scan_workflows(
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowMetadata>, String> {
    info!("扫描工作流目录");

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 扫描工作流
    match service.scan_workflows().await {
        Ok(workflows) => {
            info!("扫描完成，找到 {} 个工作流", workflows.len());
            Ok(workflows)
        }
        Err(e) => {
            error!("扫描工作流失败: {}", e);
            Err(format!("扫描工作流失败: {}", e))
        }
    }
}

/// 验证工作流文件
#[command]
pub async fn validate_workflow_file(
    state: State<'_, AppState>,
    file_path: String,
) -> Result<WorkflowValidationResult, String> {
    info!("验证工作流文件: {}", file_path);

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 读取工作流文件
    let content = tokio::fs::read_to_string(&file_path).await
        .map_err(|e| format!("读取工作流文件失败: {}", e))?;

    let workflow: Value = serde_json::from_str(&content)
        .map_err(|e| format!("解析工作流JSON失败: {}", e))?;

    // 验证工作流
    match service.validate_workflow(&workflow).await {
        Ok(result) => {
            info!("工作流验证完成: 有效={}, 错误数={}", result.is_valid, result.errors.len());
            Ok(result)
        }
        Err(e) => {
            error!("验证工作流失败: {}", e);
            Err(format!("验证工作流失败: {}", e))
        }
    }
}

/// 保存工作流文件
#[command]
pub async fn save_workflow_file(
    state: State<'_, AppState>,
    name: String,
    workflow: Value,
) -> Result<String, String> {
    info!("保存工作流文件: {}", name);

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 保存工作流
    match service.save_workflow(&name, &workflow).await {
        Ok(file_path) => {
            info!("工作流保存成功: {}", file_path);
            Ok(file_path)
        }
        Err(e) => {
            error!("保存工作流失败: {}", e);
            Err(format!("保存工作流失败: {}", e))
        }
    }
}

/// 删除工作流文件
#[command]
pub async fn delete_workflow_file(
    state: State<'_, AppState>,
    file_path: String,
) -> Result<(), String> {
    info!("删除工作流文件: {}", file_path);

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 删除工作流
    match service.delete_workflow(&file_path).await {
        Ok(()) => {
            info!("工作流删除成功: {}", file_path);
            Ok(())
        }
        Err(e) => {
            error!("删除工作流失败: {}", e);
            Err(format!("删除工作流失败: {}", e))
        }
    }
}

/// 复制工作流文件
#[command]
pub async fn copy_workflow_file(
    state: State<'_, AppState>,
    source_path: String,
    new_name: String,
) -> Result<String, String> {
    info!("复制工作流文件: {} -> {}", source_path, new_name);

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 复制工作流
    match service.copy_workflow(&source_path, &new_name).await {
        Ok(new_file_path) => {
            info!("工作流复制成功: {}", new_file_path);
            Ok(new_file_path)
        }
        Err(e) => {
            error!("复制工作流失败: {}", e);
            Err(format!("复制工作流失败: {}", e))
        }
    }
}

/// 获取工作流目录路径
#[command]
pub async fn get_workflow_directory(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("获取工作流目录路径");

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    let directory_path = service.get_workflow_directory().to_string_lossy().to_string();
    info!("工作流目录路径: {}", directory_path);
    Ok(directory_path)
}

/// 设置工作流目录路径
#[command]
pub async fn set_workflow_directory(
    state: State<'_, AppState>,
    directory: String,
) -> Result<(), String> {
    info!("设置工作流目录路径: {}", directory);

    // 创建工作流管理服务
    let mut service = WorkflowManagementService::new(Some(directory.clone()))
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 设置目录
    match service.set_workflow_directory(directory.clone()).await {
        Ok(()) => {
            info!("工作流目录设置成功: {}", directory);
            
            // 更新配置
            let mut config = AppConfig::load();
            let mut comfyui_settings = config.get_comfyui_settings().clone();
            comfyui_settings.workflow_directory = Some(directory);
            config.update_comfyui_settings(comfyui_settings);
            
            if let Err(e) = config.save() {
                error!("保存配置失败: {}", e);
                return Err(format!("保存配置失败: {}", e));
            }
            
            Ok(())
        }
        Err(e) => {
            error!("设置工作流目录失败: {}", e);
            Err(format!("设置工作流目录失败: {}", e))
        }
    }
}

/// 加载工作流内容
#[command]
pub async fn load_workflow_content(
    state: State<'_, AppState>,
    file_path: String,
) -> Result<Value, String> {
    info!("加载工作流内容: {}", file_path);

    // 读取文件内容
    let content = tokio::fs::read_to_string(&file_path).await
        .map_err(|e| format!("读取工作流文件失败: {}", e))?;

    // 解析JSON
    let workflow: Value = serde_json::from_str(&content)
        .map_err(|e| format!("解析工作流JSON失败: {}", e))?;

    info!("工作流内容加载成功");
    Ok(workflow)
}

/// 获取工作流统计信息
#[command]
pub async fn get_workflow_statistics(
    state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
    info!("获取工作流统计信息");

    // 获取配置
    let config = AppConfig::load();
    let workflow_directory = config.get_comfyui_settings().workflow_directory.clone();

    // 创建工作流管理服务
    let service = WorkflowManagementService::new(workflow_directory)
        .map_err(|e| format!("创建工作流管理服务失败: {}", e))?;

    // 扫描工作流
    let workflows = service.scan_workflows().await
        .map_err(|e| format!("扫描工作流失败: {}", e))?;

    let total_count = workflows.len();
    let valid_count = workflows.iter().filter(|w| w.is_valid).count();
    let invalid_count = total_count - valid_count;
    let total_size: u64 = workflows.iter().map(|w| w.file_size).sum();

    let statistics = serde_json::json!({
        "total_count": total_count,
        "valid_count": valid_count,
        "invalid_count": invalid_count,
        "total_size_bytes": total_size,
        "directory_path": service.get_workflow_directory().to_string_lossy()
    });

    info!("工作流统计信息: {}", statistics);
    Ok(statistics)
}
