use crate::business::services::universal_workflow_service::{
    ExecuteWorkflowRequest, ExecuteWorkflowResponse
};
use crate::data::models::workflow_template::{
    WorkflowTemplate, CreateWorkflowTemplateRequest, UpdateWorkflowTemplateRequest, WorkflowTemplateFilter
};
use crate::data::models::workflow_execution_record::{
    WorkflowExecutionRecord, ExecutionRecordFilter
};
use crate::data::models::workflow_execution_environment::{
    WorkflowExecutionEnvironment, CreateExecutionEnvironmentRequest, UpdateExecutionEnvironmentRequest, ExecutionEnvironmentFilter
};
use crate::app_state::AppState;
use anyhow::Result;
use tauri::State;
use tracing::info;

/// 获取所有工作流模板
#[tauri::command]
pub async fn get_workflow_templates(
    filter: Option<WorkflowTemplateFilter>,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowTemplate>, String> {
    info!("获取工作流模板列表");

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 查询工作流模板
    let templates = repo.find_all(filter.as_ref())
        .map_err(|e| format!("查询工作流模板失败: {}", e))?;

    info!("成功获取 {} 个工作流模板", templates.len());
    Ok(templates)
}

/// 根据ID获取工作流模板
#[tauri::command]
pub async fn get_workflow_template_by_id(
    id: i64,
    state: State<'_, AppState>,
) -> Result<Option<WorkflowTemplate>, String> {
    info!("获取工作流模板: {}", id);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 查询模板
    let template = repo.find_by_id(id)
        .map_err(|e| format!("查询工作流模板失败: {}", e))?;

    info!("成功获取工作流模板: {:?}", template.as_ref().map(|t| &t.name));
    Ok(template)
}

/// 创建工作流模板
#[tauri::command]
pub async fn create_workflow_template(
    request: CreateWorkflowTemplateRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowTemplate, String> {
    info!("创建工作流模板: {}", request.name);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 创建工作流模板
    let template_id = repo.create(&request)
        .map_err(|e| format!("创建工作流模板失败: {}", e))?;

    // 查询创建的模板并返回
    let template = repo.find_by_id(template_id)
        .map_err(|e| format!("查询创建的工作流模板失败: {}", e))?
        .ok_or_else(|| "创建的工作流模板未找到".to_string())?;

    info!("成功创建工作流模板，ID: {}", template_id);
    Ok(template)
}

/// 更新工作流模板
#[tauri::command]
pub async fn update_workflow_template(
    id: i64,
    request: UpdateWorkflowTemplateRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowTemplate, String> {
    info!("更新工作流模板: {}", id);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 更新工作流模板
    repo.update(id, &request)
        .map_err(|e| format!("更新工作流模板失败: {}", e))?;

    // 查询更新后的模板并返回
    let template = repo.find_by_id(id)
        .map_err(|e| format!("查询更新后的工作流模板失败: {}", e))?
        .ok_or_else(|| "更新后的工作流模板未找到".to_string())?;

    info!("成功更新工作流模板，ID: {}", id);
    Ok(template)
}

/// 执行基于映射的工作流
#[tauri::command]
pub async fn execute_workflow_with_mapping(
    request: crate::data::models::outfit_photo_generation::ExecuteWorkflowRequest,
    state: State<'_, AppState>,
) -> Result<crate::data::models::outfit_photo_generation::ExecuteWorkflowResponse, String> {
    info!("执行基于映射的工作流，模板ID: {}", request.workflow_template_id);

    // 获取工作流模板仓库
    let template_repo = {
        let template_repo_guard = state.get_workflow_template_repository()
            .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

        template_repo_guard.as_ref()
            .ok_or_else(|| "工作流模板仓库未初始化".to_string())?
            .clone()
    };

    // 获取工作流执行记录仓库
    let execution_repo = {
        let execution_repo_guard = state.get_workflow_execution_record_repository()
            .map_err(|e| format!("获取工作流执行记录仓库失败: {}", e))?;

        execution_repo_guard.as_ref()
            .ok_or_else(|| "工作流执行记录仓库未初始化".to_string())?
            .clone()
    };

    // 创建ComfyUI服务
    let comfyui_settings = crate::config::ComfyUISettings::default();
    let comfyui_service = crate::business::services::comfyui_service::ComfyUIService::new(comfyui_settings);

    // 创建工作流执行服务
    let execution_service = crate::business::services::workflow_execution_service::WorkflowExecutionService::new(comfyui_service);

    // 执行工作流
    let response = execution_service.execute_workflow(request, &template_repo, &execution_repo).await
        .map_err(|e| format!("执行工作流失败: {}", e))?;

    info!("工作流执行成功，执行记录ID: {}", response.execution_id);
    Ok(response)
}



/// 删除工作流模板
#[tauri::command]
pub async fn delete_workflow_template(
    id: i64,
    state: State<'_, AppState>,
) -> Result<(), String> {
    info!("删除工作流模板: {}", id);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 删除工作流模板
    repo.delete(id)
        .map_err(|e| format!("删除工作流模板失败: {}", e))?;

    info!("成功删除工作流模板，ID: {}", id);
    Ok(())
}

/// 执行工作流
#[tauri::command]
pub async fn execute_workflow(
    request: ExecuteWorkflowRequest,
    _state: State<'_, AppState>,
) -> Result<ExecuteWorkflowResponse, String> {
    info!("执行工作流: {}", request.workflow_identifier);
    
    // TODO: 从AppState获取UniversalWorkflowService
    // 暂时返回示例响应
    let response = ExecuteWorkflowResponse {
        execution_id: 1,
        status: crate::data::models::workflow_execution_record::ExecutionStatus::Running,
        progress: 0,
        output_data: None,
        error_message: None,
        comfyui_prompt_id: Some("test-prompt-id".to_string()),
    };
    
    Ok(response)
}

/// 获取执行状态
#[tauri::command]
pub async fn get_execution_status(
    execution_id: i64,
    state: State<'_, AppState>,
) -> Result<ExecuteWorkflowResponse, String> {
    info!("获取执行状态: {}", execution_id);

    // 获取工作流执行记录仓库
    let repo_guard = state.get_workflow_execution_record_repository()
        .map_err(|e| format!("获取工作流执行记录仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行记录仓库未初始化".to_string())?;

    // 查询执行记录
    let record = repo.find_by_id(execution_id)
        .map_err(|e| format!("查询执行记录失败: {}", e))?
        .ok_or_else(|| format!("执行记录不存在: {}", execution_id))?;

    let response = ExecuteWorkflowResponse {
        execution_id: record.id.unwrap_or(execution_id),
        status: record.status,
        progress: record.progress,
        output_data: record.output_data_json,
        comfyui_prompt_id: record.comfyui_prompt_id,
        error_message: record.error_message,
    };

    Ok(response)
}

/// 获取执行结果
#[tauri::command]
pub async fn get_execution_results(
    execution_id: i64,
    state: State<'_, AppState>,
) -> Result<Option<serde_json::Value>, String> {
    info!("获取执行结果: {}", execution_id);

    // 获取工作流执行记录仓库
    let repo_guard = state.get_workflow_execution_record_repository()
        .map_err(|e| format!("获取工作流执行记录仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行记录仓库未初始化".to_string())?;

    // 查询执行记录
    let record = repo.find_by_id(execution_id)
        .map_err(|e| format!("查询执行记录失败: {}", e))?
        .ok_or_else(|| format!("执行记录不存在: {}", execution_id))?;

    Ok(record.output_data_json)
}

/// 取消执行
#[tauri::command]
pub async fn cancel_execution(
    execution_id: i64,
    _state: State<'_, AppState>,
) -> Result<(), String> {
    info!("取消执行: {}", execution_id);
    
    // TODO: 实现实际的取消逻辑
    Ok(())
}

/// 获取执行历史
#[tauri::command]
pub async fn get_execution_history(
    filter: Option<ExecutionRecordFilter>,
    limit: Option<i32>,
    offset: Option<i32>,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowExecutionRecord>, String> {
    info!("获取执行历史");

    // 获取工作流执行记录仓库
    let repo_guard = state.get_workflow_execution_record_repository()
        .map_err(|e| format!("获取工作流执行记录仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行记录仓库未初始化".to_string())?;

    // 查询执行历史
    let records = if let (Some(limit), Some(offset)) = (limit, offset) {
        let page = (offset / limit.max(1)) as u32;
        let page_size = limit as u32;
        let (records, _total) = repo.find_with_pagination(filter.as_ref(), page, page_size)
            .map_err(|e| format!("分页查询执行历史失败: {}", e))?;
        records
    } else {
        repo.find_all(filter.as_ref())
            .map_err(|e| format!("查询执行历史失败: {}", e))?
    };

    info!("成功获取 {} 条执行历史记录", records.len());
    Ok(records)
}

/// 获取执行环境列表
#[tauri::command]
pub async fn get_execution_environments(
    filter: Option<ExecutionEnvironmentFilter>,
    state: State<'_, AppState>,
) -> Result<Vec<WorkflowExecutionEnvironment>, String> {
    info!("获取执行环境列表");

    // 获取工作流执行环境仓库
    let repo_guard = state.get_workflow_execution_environment_repository()
        .map_err(|e| format!("获取工作流执行环境仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行环境仓库未初始化".to_string())?;

    // 查询执行环境
    let environments = repo.find_all(filter.as_ref())
        .map_err(|e| format!("查询执行环境失败: {}", e))?;

    info!("成功获取 {} 个执行环境", environments.len());
    Ok(environments)
}

/// 创建执行环境
#[tauri::command]
pub async fn create_execution_environment(
    request: CreateExecutionEnvironmentRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowExecutionEnvironment, String> {
    info!("创建执行环境: {}", request.name);

    // 获取工作流执行环境仓库
    let repo_guard = state.get_workflow_execution_environment_repository()
        .map_err(|e| format!("获取工作流执行环境仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行环境仓库未初始化".to_string())?;

    // 创建执行环境
    let environment_id = repo.create(&request)
        .map_err(|e| format!("创建执行环境失败: {}", e))?;

    // 查询创建的环境并返回
    let environment = repo.find_by_id(environment_id)
        .map_err(|e| format!("查询创建的执行环境失败: {}", e))?
        .ok_or_else(|| "创建的执行环境未找到".to_string())?;

    info!("成功创建执行环境，ID: {}", environment_id);
    Ok(environment)
}

/// 更新执行环境
#[tauri::command]
pub async fn update_execution_environment(
    id: i64,
    request: UpdateExecutionEnvironmentRequest,
    state: State<'_, AppState>,
) -> Result<WorkflowExecutionEnvironment, String> {
    info!("更新执行环境: {}", id);

    // 获取工作流执行环境仓库
    let repo_guard = state.get_workflow_execution_environment_repository()
        .map_err(|e| format!("获取工作流执行环境仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行环境仓库未初始化".to_string())?;

    // 更新执行环境
    repo.update(id, &request)
        .map_err(|e| format!("更新执行环境失败: {}", e))?;

    // 查询更新后的环境并返回
    let environment = repo.find_by_id(id)
        .map_err(|e| format!("查询更新后的执行环境失败: {}", e))?
        .ok_or_else(|| "更新后的执行环境未找到".to_string())?;

    info!("成功更新执行环境，ID: {}", id);
    Ok(environment)
}

/// 删除执行环境
#[tauri::command]
pub async fn delete_execution_environment(
    id: i64,
    state: State<'_, AppState>,
) -> Result<(), String> {
    info!("删除执行环境: {}", id);

    // 获取工作流执行环境仓库
    let repo_guard = state.get_workflow_execution_environment_repository()
        .map_err(|e| format!("获取工作流执行环境仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流执行环境仓库未初始化".to_string())?;

    // 删除执行环境
    repo.delete(id)
        .map_err(|e| format!("删除执行环境失败: {}", e))?;

    info!("成功删除执行环境，ID: {}", id);
    Ok(())
}

/// 导出工作流模板
#[tauri::command]
pub async fn export_workflow_template(
    id: i64,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("导出工作流模板: {}", id);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 导出模板
    let json_data = repo.export_template(id)
        .map_err(|e| format!("导出工作流模板失败: {}", e))?;

    info!("成功导出工作流模板，ID: {}", id);
    Ok(json_data)
}

/// 导入工作流模板
#[tauri::command]
pub async fn import_workflow_template(
    json_data: String,
    override_name: Option<String>,
    state: State<'_, AppState>,
) -> Result<i64, String> {
    info!("导入工作流模板");

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 导入模板
    let template_id = repo.import_template(&json_data, override_name)
        .map_err(|e| format!("导入工作流模板失败: {}", e))?;

    info!("成功导入工作流模板，新ID: {}", template_id);
    Ok(template_id)
}

/// 导出工作流包
#[tauri::command]
pub async fn export_workflow_package(
    package_data: serde_json::Value,
    file_path: String,
) -> Result<(), String> {
    info!("导出工作流包到: {}", file_path);

    // 将数据写入文件
    std::fs::write(&file_path, serde_json::to_string_pretty(&package_data).unwrap())
        .map_err(|e| format!("写入文件失败: {}", e))?;

    info!("成功导出工作流包");
    Ok(())
}

/// 导入工作流包
#[tauri::command]
pub async fn import_workflow_package() -> Result<serde_json::Value, String> {
    info!("导入工作流包");

    // 在前端处理文件选择，这里只处理导入逻辑
    // 暂时返回成功状态，实际实现时会接收文件路径参数
    let result = serde_json::json!({
        "success": true,
        "message": "导入成功",
        "imported_count": 1
    });

    info!("成功导入工作流包");
    Ok(result)
}

/// 复制工作流模板
#[tauri::command]
pub async fn copy_workflow_template(
    id: i64,
    new_name: String,
    new_base_name: Option<String>,
    state: State<'_, AppState>,
) -> Result<i64, String> {
    info!("复制工作流模板: {} -> {}", id, new_name);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 复制模板
    let new_template_id = repo.copy_template(id, new_name, new_base_name)
        .map_err(|e| format!("复制工作流模板失败: {}", e))?;

    info!("成功复制工作流模板，原ID: {}，新ID: {}", id, new_template_id);
    Ok(new_template_id)
}

/// 验证工作流模板
#[tauri::command]
pub async fn validate_workflow_template(
    id: i64,
    state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    info!("验证工作流模板: {}", id);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 获取模板
    let template = repo.find_by_id(id)
        .map_err(|e| format!("查询工作流模板失败: {}", e))?
        .ok_or_else(|| "工作流模板不存在".to_string())?;

    // 验证模板
    let warnings = repo.validate_template(&template)
        .map_err(|e| format!("验证工作流模板失败: {}", e))?;

    info!("工作流模板验证完成，发现 {} 个警告", warnings.len());
    Ok(warnings)
}

/// 批量导出工作流模板
#[tauri::command]
pub async fn batch_export_workflow_templates(
    ids: Vec<i64>,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("批量导出工作流模板: {:?}", ids);

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 批量导出模板
    let json_data = repo.batch_export(&ids)
        .map_err(|e| format!("批量导出工作流模板失败: {}", e))?;

    info!("成功批量导出 {} 个工作流模板", ids.len());
    Ok(json_data)
}

/// 批量导入工作流模板
#[tauri::command]
pub async fn batch_import_workflow_templates(
    json_data: String,
    state: State<'_, AppState>,
) -> Result<Vec<i64>, String> {
    info!("批量导入工作流模板");

    // 获取工作流模板仓库
    let repo_guard = state.get_workflow_template_repository()
        .map_err(|e| format!("获取工作流模板仓库失败: {}", e))?;

    let repo = repo_guard.as_ref()
        .ok_or_else(|| "工作流模板仓库未初始化".to_string())?;

    // 批量导入模板
    let template_ids = repo.batch_import(&json_data)
        .map_err(|e| format!("批量导入工作流模板失败: {}", e))?;

    info!("成功批量导入 {} 个工作流模板", template_ids.len());
    Ok(template_ids)
}

/// 获取执行结果文件列表
#[tauri::command]
pub async fn get_execution_result_files(
    execution_id: i64,
    state: State<'_, AppState>,
) -> Result<Vec<crate::business::services::workflow_result_service::ResultFileInfo>, String> {
    info!("获取执行结果文件列表: {}", execution_id);

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空列表
    Ok(Vec::new())
}

/// 下载执行结果文件
#[tauri::command]
pub async fn download_execution_result_file(
    execution_id: i64,
    file_name: String,
    state: State<'_, AppState>,
) -> Result<Vec<u8>, String> {
    info!("下载执行结果文件: {} - {}", execution_id, file_name);

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空数据
    Err("功能暂未实现".to_string())
}

/// 删除执行结果文件
#[tauri::command]
pub async fn delete_execution_result_files(
    execution_id: i64,
    state: State<'_, AppState>,
) -> Result<crate::business::services::workflow_result_service::CleanupResult, String> {
    info!("删除执行结果文件: {}", execution_id);

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空结果
    Ok(crate::business::services::workflow_result_service::CleanupResult {
        files_deleted: 0,
        space_freed_mb: 0.0,
        errors: Vec::new(),
    })
}

/// 获取存储统计信息
#[tauri::command]
pub async fn get_storage_statistics(
    state: State<'_, AppState>,
) -> Result<crate::business::services::workflow_result_service::StorageStatistics, String> {
    info!("获取存储统计信息");

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空统计
    Ok(crate::business::services::workflow_result_service::StorageStatistics {
        total_files: 0,
        total_size_mb: 0.0,
        oldest_file_date: None,
        newest_file_date: None,
        files_by_type: std::collections::HashMap::new(),
        size_by_type: std::collections::HashMap::new(),
    })
}

/// 清理过期结果文件
#[tauri::command]
pub async fn cleanup_expired_results(
    state: State<'_, AppState>,
) -> Result<crate::business::services::workflow_result_service::CleanupResult, String> {
    info!("清理过期结果文件");

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空结果
    Ok(crate::business::services::workflow_result_service::CleanupResult {
        files_deleted: 0,
        space_freed_mb: 0.0,
        errors: Vec::new(),
    })
}

/// 批量清理执行结果
#[tauri::command]
pub async fn batch_cleanup_execution_results(
    execution_ids: Vec<i64>,
    state: State<'_, AppState>,
) -> Result<crate::business::services::workflow_result_service::CleanupResult, String> {
    info!("批量清理执行结果: {:?}", execution_ids);

    // TODO: 从AppState获取WorkflowResultService实例
    // 暂时返回空结果
    Ok(crate::business::services::workflow_result_service::CleanupResult {
        files_deleted: 0,
        space_freed_mb: 0.0,
        errors: Vec::new(),
    })
}
