use crate::data::models::workflow_template::WorkflowTemplate;
use crate::data::models::workflow_execution_record::{
    WorkflowExecutionRecord, CreateExecutionRecordRequest, ExecutionStatus, ErrorDetails
};
use crate::data::models::workflow_execution_environment::WorkflowExecutionEnvironment;
use crate::data::repositories::workflow_template_repository::WorkflowTemplateRepository;
use crate::data::repositories::workflow_execution_record_repository::WorkflowExecutionRecordRepository;
use crate::data::repositories::workflow_execution_environment_repository::WorkflowExecutionEnvironmentRepository;
use crate::infrastructure::comfyui_service::ComfyuiInfrastructureService;
use crate::infrastructure::database::Database;
use anyhow::{Result, anyhow};
use serde_json::Value;
use std::sync::Arc;
use tracing::{info, debug, warn};

/// 通用工作流执行服务
/// 
/// 这是多工作流系统的核心服务，能够执行任何类型的AI工作流
/// 支持本地ComfyUI、云端Modal、云端RunPod等多种执行环境
/// 实现了统一的执行流程、进度回调和错误处理
#[derive(Clone)]
pub struct UniversalWorkflowService {
    database: Arc<Database>,
    comfyui_service: Arc<ComfyuiInfrastructureService>,
    workflow_template_repository: WorkflowTemplateRepository,
    workflow_execution_record_repository: WorkflowExecutionRecordRepository,
    workflow_execution_environment_repository: WorkflowExecutionEnvironmentRepository,
    // 可以添加其他执行环境的服务
    // modal_service: Arc<ModalService>,
    // runpod_service: Arc<RunPodService>,
}

/// 工作流执行请求
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecuteWorkflowRequest {
    /// 工作流模板ID或base_name
    pub workflow_identifier: String,
    /// 工作流版本（可选，默认使用最新版本）
    pub version: Option<String>,
    /// 输入数据
    pub input_data: Value,
    /// 指定执行环境ID（可选，系统会自动选择最佳环境）
    pub environment_id: Option<i64>,
    /// 用户ID
    pub user_id: Option<String>,
    /// 会话ID
    pub session_id: Option<String>,
    /// 元数据
    pub metadata: Option<Value>,
}

/// 工作流执行响应
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecuteWorkflowResponse {
    /// 执行记录ID
    pub execution_id: i64,
    /// 执行状态
    pub status: ExecutionStatus,
    /// 进度（0-100）
    pub progress: i32,
    /// 输出数据（如果已完成）
    pub output_data: Option<Value>,
    /// 错误信息（如果失败）
    pub error_message: Option<String>,
    /// ComfyUI任务ID（如果使用ComfyUI）
    pub comfyui_prompt_id: Option<String>,
}

/// 执行进度回调
pub type ProgressCallback = Box<dyn Fn(i64, i32, Option<String>) + Send + Sync>;

impl UniversalWorkflowService {
    /// 创建新的通用工作流服务
    pub fn new(
        database: Arc<Database>,
        comfyui_service: Arc<ComfyuiInfrastructureService>,
        workflow_template_repository: WorkflowTemplateRepository,
        workflow_execution_record_repository: WorkflowExecutionRecordRepository,
        workflow_execution_environment_repository: WorkflowExecutionEnvironmentRepository,
    ) -> Self {
        Self {
            database,
            comfyui_service,
            workflow_template_repository,
            workflow_execution_record_repository,
            workflow_execution_environment_repository,
        }
    }

    /// 执行工作流
    /// 
    /// 这是核心方法，实现了统一的工作流执行流程：
    /// 1. 验证工作流模板和输入数据
    /// 2. 选择最佳执行环境
    /// 3. 创建执行记录
    /// 4. 执行工作流
    /// 5. 更新执行状态和结果
    pub async fn execute_workflow(
        &self,
        request: ExecuteWorkflowRequest,
    ) -> Result<ExecuteWorkflowResponse> {
        info!("开始执行工作流: {}", request.workflow_identifier);
        info!("执行请求详情: identifier='{}', version={:?}, environment_id={:?}",
              request.workflow_identifier, request.version, request.environment_id);

        // 1. 获取工作流模板
        let template = self.get_workflow_template(&request.workflow_identifier, request.version.as_deref()).await?;
        info!("成功获取工作流模板: ID={}, 名称='{}', 类型={:?}",
              template.id.unwrap_or(-1), template.name, template.workflow_type);
        
        // 2. 验证输入数据
        template.validate_input(&request.input_data).map_err(|e| anyhow!(e))?;

        // 3. 选择执行环境
        let environment = self.select_execution_environment(&template, request.environment_id).await?;

        // 4. 创建执行记录
        let execution_record = self.create_execution_record(&template, &environment, &request).await?;
        let execution_id = execution_record.id.unwrap();

        // 5. 开始执行
        let mut record = execution_record;
        record.start_execution();
        self.update_execution_record(&record).await?;

        // 6. 根据环境类型执行工作流
        let result = match environment.environment_type {
            crate::data::models::workflow_execution_environment::EnvironmentType::LocalComfyui => {
                self.execute_on_comfyui(&template, &environment, &request, execution_id).await
            }
        };

        // 7. 更新执行结果
        match result {
            Ok(output_data) => {
                record.complete_execution(output_data.clone());
                self.update_execution_record(&record).await?;
                
                Ok(ExecuteWorkflowResponse {
                    execution_id,
                    status: ExecutionStatus::Completed,
                    progress: 100,
                    output_data: Some(output_data),
                    error_message: None,
                    comfyui_prompt_id: record.comfyui_prompt_id,
                })
            }
            Err(error) => {
                let error_details = ErrorDetails {
                    error_type: "execution_error".to_string(),
                    error_code: None,
                    stack_trace: Some(format!("{:?}", error)),
                    context: None,
                    retry_count: Some(0),
                    is_retryable: true,
                };
                
                record.fail_execution(error.to_string(), Some(error_details));
                self.update_execution_record(&record).await?;
                
                Ok(ExecuteWorkflowResponse {
                    execution_id,
                    status: ExecutionStatus::Failed,
                    progress: 0,
                    output_data: None,
                    error_message: Some(error.to_string()),
                    comfyui_prompt_id: record.comfyui_prompt_id,
                })
            }
        }
    }

    /// 获取工作流模板
    async fn get_workflow_template(
        &self,
        identifier: &str,
        version: Option<&str>,
    ) -> Result<WorkflowTemplate> {
        info!("正在查找工作流模板: identifier='{}', version={:?}", identifier, version);

        // 首先尝试按ID查询（如果identifier是数字）
        if let Ok(id) = identifier.parse::<i64>() {
            info!("尝试按ID查询工作流模板: {}", id);
            if let Some(template) = self.workflow_template_repository.find_by_id(id)? {
                info!("成功找到工作流模板: ID={}, 名称='{}', 类型={:?}",
                      template.id.unwrap_or(-1), template.name, template.workflow_type);
                return Ok(template);
            } else {
                warn!("未找到ID为 {} 的工作流模板", id);
            }
        } else {
            info!("identifier '{}' 不是有效的数字ID，尝试按base_name查询", identifier);
        }

        // 按base_name查询
        if let Some(version) = version {
            // 查询指定版本
            info!("按base_name和版本查询: base_name='{}', version='{}'", identifier, version);
            let templates = self.workflow_template_repository.find_by_base_name(identifier)?;
            info!("找到 {} 个base_name为 '{}' 的模板", templates.len(), identifier);

            for template in templates {
                if template.version == version {
                    info!("找到匹配版本的模板: ID={}, 名称='{}'",
                          template.id.unwrap_or(-1), template.name);
                    return Ok(template);
                }
            }
            return Err(anyhow!("未找到工作流模板: {} 版本 {}", identifier, version));
        } else {
            // 查询最新版本
            info!("按base_name查询最新版本: '{}'", identifier);
            if let Some(template) = self.workflow_template_repository.get_latest_version(identifier)? {
                info!("找到最新版本模板: ID={}, 名称='{}', 版本='{}'",
                      template.id.unwrap_or(-1), template.name, template.version);
                return Ok(template);
            } else {
                warn!("未找到base_name为 '{}' 的模板", identifier);
            }
        }

        // 如果都没找到，列出所有可用的模板进行调试
        let all_templates = self.workflow_template_repository.find_all(None)?;
        warn!("未找到工作流模板 '{}', 数据库中共有 {} 个模板:", identifier, all_templates.len());
        for template in &all_templates {
            warn!("  模板: ID={}, 名称='{}', base_name='{}', 版本='{}', 类型={:?}",
                  template.id.unwrap_or(-1), template.name, template.base_name,
                  template.version, template.workflow_type);
        }

        Err(anyhow!("未找到工作流模板: {}", identifier))
    }

    /// 选择最佳执行环境
    async fn select_execution_environment(
        &self,
        template: &WorkflowTemplate,
        preferred_environment_id: Option<i64>,
    ) -> Result<WorkflowExecutionEnvironment> {
        // 如果指定了环境ID，直接使用
        if let Some(env_id) = preferred_environment_id {
            if let Some(environment) = self.workflow_execution_environment_repository.find_by_id(env_id)? {
                if environment.is_active && environment.is_available {
                    return Ok(environment);
                } else {
                    return Err(anyhow!("指定的执行环境不可用，ID: {}", env_id));
                }
            } else {
                return Err(anyhow!("未找到指定的执行环境，ID: {}", env_id));
            }
        }

        // 自动选择最佳环境
        // 获取支持当前工作流类型的可用环境，按优先级排序
        let workflow_type_str = template.workflow_type.to_string();
        info!("正在查找支持工作流类型 '{}' 的执行环境", workflow_type_str);

        let available_environments = self.workflow_execution_environment_repository
            .find_available_environments(Some(&workflow_type_str))?;

        info!("找到 {} 个支持工作流类型 '{}' 的可用执行环境", available_environments.len(), workflow_type_str);

        if available_environments.is_empty() {
            // 获取所有执行环境进行调试
            let all_environments = self.workflow_execution_environment_repository.find_all(None)?;
            warn!("没有找到支持工作流类型 '{}' 的执行环境", workflow_type_str);
            warn!("数据库中共有 {} 个执行环境:", all_environments.len());

            for env in &all_environments {
                warn!("  环境: {} (ID: {:?})", env.name, env.id);
                warn!("    类型: {:?}", env.environment_type);
                warn!("    是否活跃: {}", env.is_active);
                warn!("    是否可用: {}", env.is_available);
                warn!("    健康状态: {:?}", env.health_status);
                warn!("    支持的工作流类型: {:?}", env.supported_workflow_types);
            }

            return Err(anyhow!("没有可用的执行环境支持工作流类型: {:?}", template.workflow_type));
        }

        // 选择优先级最高的环境
        let best_environment = available_environments.into_iter().next().unwrap();
        info!("自动选择执行环境: {} (优先级: {})", best_environment.name, best_environment.priority);

        Ok(best_environment)
    }

    /// 创建执行记录
    async fn create_execution_record(
        &self,
        template: &WorkflowTemplate,
        environment: &WorkflowExecutionEnvironment,
        request: &ExecuteWorkflowRequest,
    ) -> Result<WorkflowExecutionRecord> {
        let create_request = CreateExecutionRecordRequest {
            workflow_template_id: template.id.unwrap(),
            workflow_name: template.name.clone(),
            workflow_version: template.version.clone(),
            execution_environment_id: environment.id,
            execution_environment_name: Some(environment.name.clone()),
            input_data_json: request.input_data.clone(),
            user_id: request.user_id.clone(),
            session_id: request.session_id.clone(),
            metadata_json: request.metadata.clone(),
            tags: None,
        };

        let record = WorkflowExecutionRecord::new(create_request);

        // 保存到数据库并返回带ID的记录
        let record_id = self.workflow_execution_record_repository.create(&record)?;

        // 查询保存的记录
        let saved_record = self.workflow_execution_record_repository.find_by_id(record_id)?
            .ok_or_else(|| anyhow!("创建的执行记录未找到，ID: {}", record_id))?;

        info!("成功创建执行记录，ID: {}", record_id);
        Ok(saved_record)
    }

    /// 更新执行记录
    async fn update_execution_record(&self, record: &WorkflowExecutionRecord) -> Result<()> {
        self.workflow_execution_record_repository.update(record)?;
        debug!("成功更新执行记录: {:?}", record.id);
        Ok(())
    }

    /// 在ComfyUI上执行工作流
    async fn execute_on_comfyui(
        &self,
        template: &WorkflowTemplate,
        environment: &WorkflowExecutionEnvironment,
        request: &ExecuteWorkflowRequest,
        execution_id: i64,
    ) -> Result<Value> {
        info!("在ComfyUI环境执行工作流: {}", template.name);

        // 构建ComfyUI执行请求
        let comfyui_request = crate::data::models::comfyui::ExecuteWorkflowRequest {
            base_name: template.base_name.clone(),
            version: Some(template.version.clone()),
            request_data: request.input_data.clone(),
        };

        // 执行工作流
        let response = self.comfyui_service.execute_workflow(comfyui_request).await?;

        // 返回结果
        Ok(serde_json::to_value(response)?)
    }

    /// 获取执行状态
    pub async fn get_execution_status(&self, execution_id: i64) -> Result<ExecuteWorkflowResponse> {
        // 从数据库查询执行记录
        let record = self.workflow_execution_record_repository.find_by_id(execution_id)?
            .ok_or_else(|| anyhow!("执行记录未找到，ID: {}", execution_id))?;

        Ok(ExecuteWorkflowResponse {
            execution_id,
            status: record.status,
            progress: record.progress,
            output_data: record.output_data_json,
            error_message: record.error_message,
            comfyui_prompt_id: record.comfyui_prompt_id,
        })
    }

    /// 取消执行
    pub async fn cancel_execution(&self, execution_id: i64) -> Result<()> {
        // 查询执行记录
        let mut record = self.workflow_execution_record_repository.find_by_id(execution_id)?
            .ok_or_else(|| anyhow!("执行记录未找到，ID: {}", execution_id))?;

        // 检查是否可以取消
        match record.status {
            ExecutionStatus::Pending | ExecutionStatus::Running => {
                // 更新状态为已取消
                record.status = ExecutionStatus::Cancelled;
                record.completed_at = Some(chrono::Utc::now());

                // 计算执行时长
                if let Some(started_at) = record.started_at {
                    let duration = chrono::Utc::now().signed_duration_since(started_at);
                    record.duration_seconds = Some(duration.num_seconds() as i32);
                }

                // 更新数据库
                self.workflow_execution_record_repository.update(&record)?;

                info!("成功取消执行: {}", execution_id);
                Ok(())
            }
            _ => {
                Err(anyhow!("执行记录状态不允许取消，当前状态: {:?}", record.status))
            }
        }
    }
}
