use std::sync::Arc;
use tempfile::TempDir;
use chrono::Utc;

use crate::infrastructure::database::Database;
use crate::data::models::workflow_template::{WorkflowTemplate, WorkflowType, CreateWorkflowTemplateRequest};
use crate::data::models::workflow_execution_record::{WorkflowExecutionRecord, ExecutionStatus, CreateExecutionRecordRequest};
use crate::data::models::workflow_execution_environment::{WorkflowExecutionEnvironment, EnvironmentType, HealthStatus, CreateExecutionEnvironmentRequest};

/// 测试工具类
/// 提供测试数据创建和数据库初始化功能
pub struct TestUtils;

impl TestUtils {
    /// 创建测试数据库
    pub async fn create_test_database() -> anyhow::Result<(Arc<Database>, TempDir)> {
        let temp_dir = tempfile::tempdir()?;
        let _db_path = temp_dir.path().join("test.db");

        let database = Database::new()?;
        database.run_migrations()?;
        
        Ok((Arc::new(database), temp_dir))
    }

    /// 创建测试工作流模板
    pub fn create_test_workflow_template() -> WorkflowTemplate {
        WorkflowTemplate {
            id: Some(1),
            name: "测试工作流模板".to_string(),
            base_name: "test_workflow".to_string(),
            version: "1.0".to_string(),
            workflow_type: WorkflowType::OutfitGeneration,
            description: Some("这是一个测试工作流模板".to_string()),
            comfyui_workflow_json: serde_json::json!({
                "nodes": [],
                "links": []
            }),
            ui_config_json: serde_json::json!({
                "form_fields": [
                    {
                        "name": "input_image",
                        "type": "image_upload",
                        "label": "输入图片",
                        "required": true
                    }
                ]
            }),
            execution_config_json: Some(serde_json::json!({
                "timeout_seconds": 600,
                "retry_attempts": 3
            })),
            input_schema_json: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "input_image": {"type": "string"}
                }
            })),
            output_schema_json: Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "output_image": {"type": "string"}
                }
            })),
            is_active: true,
            is_published: true,
            tags: Some(vec!["测试".to_string(), "AI生成".to_string()]),
            category: Some("测试分类".to_string()),
            author: Some("测试用户".to_string()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    /// 创建测试工作流模板创建请求
    pub fn create_test_workflow_template_request() -> CreateWorkflowTemplateRequest {
        CreateWorkflowTemplateRequest {
            name: "测试工作流模板".to_string(),
            base_name: "test_workflow".to_string(),
            version: "1.0".to_string(),
            workflow_type: WorkflowType::OutfitGeneration,
            description: Some("这是一个测试工作流模板".to_string()),
            comfyui_workflow_json: serde_json::json!({
                "nodes": [],
                "links": []
            }),
            ui_config_json: serde_json::json!({
                "form_fields": []
            }),
            execution_config_json: Some(serde_json::json!({
                "timeout_seconds": 600
            })),
            input_schema_json: Some(serde_json::json!({})),
            output_schema_json: Some(serde_json::json!({})),
            tags: Some(vec!["测试".to_string()]),
            category: Some("测试分类".to_string()),
            author: Some("测试用户".to_string()),
        }
    }

    /// 创建测试执行记录
    pub fn create_test_execution_record() -> WorkflowExecutionRecord {
        WorkflowExecutionRecord {
            id: Some(1),
            workflow_template_id: 1,
            workflow_name: "测试工作流".to_string(),
            workflow_version: "1.0".to_string(),
            execution_environment_id: Some(1),
            execution_environment_name: Some("测试环境".to_string()),
            input_data_json: serde_json::json!({
                "input_image": "test_image.jpg"
            }),
            output_data_json: Some(serde_json::json!({
                "output_image": "output_image.jpg"
            })),
            status: ExecutionStatus::Completed,
            progress: 100,
            comfyui_prompt_id: Some("test-prompt-123".to_string()),
            comfyui_workflow_name: Some("test_workflow".to_string()),
            started_at: Some(Utc::now()),
            completed_at: Some(Utc::now()),
            duration_seconds: Some(120),
            error_message: None,
            error_details_json: None,
            user_id: Some("test_user".to_string()),
            session_id: Some("test_session".to_string()),
            metadata_json: Some(serde_json::json!({
                "test_metadata": "value"
            })),
            tags: Some(vec!["测试".to_string()]),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    /// 创建测试执行记录创建请求
    pub fn create_test_execution_record_request() -> CreateExecutionRecordRequest {
        CreateExecutionRecordRequest {
            workflow_template_id: 1,
            workflow_name: "测试工作流".to_string(),
            workflow_version: "1.0".to_string(),
            execution_environment_id: Some(1),
            execution_environment_name: Some("测试环境".to_string()),
            input_data_json: serde_json::json!({
                "input_image": "test_image.jpg"
            }),
            user_id: Some("test_user".to_string()),
            session_id: Some("test_session".to_string()),
            metadata_json: Some(serde_json::json!({
                "test_metadata": "value"
            })),
            tags: Some(vec!["测试".to_string()]),
        }
    }

    /// 创建测试执行环境
    pub fn create_test_execution_environment() -> WorkflowExecutionEnvironment {
        WorkflowExecutionEnvironment {
            id: Some(1),
            name: "测试执行环境".to_string(),
            environment_type: EnvironmentType::LocalComfyui,
            description: Some("这是一个测试执行环境".to_string()),
            base_url: "http://localhost:8188".to_string(),
            api_key: Some("test_api_key".to_string()),
            connection_config_json: Some(serde_json::json!({
                "timeout": 30000
            })),
            supported_workflow_types: vec!["outfit_generation".to_string()],
            max_concurrent_jobs: 4,
            priority: 100,
            is_active: true,
            is_available: true,
            last_health_check: Some(Utc::now()),
            health_status: HealthStatus::Healthy,
            average_response_time_ms: Some(5000),
            success_rate: 0.95,
            total_executions: 100,
            failed_executions: 5,
            max_memory_mb: Some(8192),
            max_execution_time_seconds: Some(3600),
            metadata_json: Some(serde_json::json!({
                "test_metadata": "value"
            })),
            tags: Some(vec!["测试".to_string()]),
            created_at: Utc::now(),
            updated_at: Utc::now(),
        }
    }

    /// 创建测试执行环境创建请求
    pub fn create_test_execution_environment_request() -> CreateExecutionEnvironmentRequest {
        CreateExecutionEnvironmentRequest {
            name: "测试执行环境".to_string(),
            environment_type: EnvironmentType::LocalComfyui,
            description: Some("这是一个测试执行环境".to_string()),
            base_url: "http://localhost:8188".to_string(),
            api_key: Some("test_api_key".to_string()),
            connection_config_json: Some(serde_json::json!({
                "timeout": 30000
            })),
            supported_workflow_types: vec!["outfit_generation".to_string()],
            max_concurrent_jobs: Some(4),
            priority: Some(100),
            max_memory_mb: Some(8192),
            max_execution_time_seconds: Some(3600),
            metadata_json: Some(serde_json::json!({
                "test_metadata": "value"
            })),
            tags: Some(vec!["测试".to_string()]),
        }
    }

    /// 创建多个测试工作流模板
    pub fn create_multiple_test_templates(count: usize) -> Vec<CreateWorkflowTemplateRequest> {
        (0..count).map(|i| {
            let mut request = Self::create_test_workflow_template_request();
            request.name = format!("测试工作流模板 {}", i + 1);
            request.base_name = format!("test_workflow_{}", i + 1);
            request
        }).collect()
    }

    /// 创建多个测试执行记录
    pub fn create_multiple_test_execution_records(count: usize, template_id: i64) -> Vec<CreateExecutionRecordRequest> {
        (0..count).map(|i| {
            let mut request = Self::create_test_execution_record_request();
            request.workflow_template_id = template_id;
            request.workflow_name = format!("测试工作流 {}", i + 1);
            request
        }).collect()
    }

    /// 等待异步操作完成
    pub async fn wait_for_async_operation() {
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }

    /// 清理测试数据
    pub async fn cleanup_test_data(database: &Database) -> anyhow::Result<()> {
        // 清理所有测试数据
        let conn = database.acquire_from_pool()?;
        
        conn.execute("DELETE FROM workflow_execution_records", [])?;
        conn.execute("DELETE FROM workflow_templates", [])?;
        conn.execute("DELETE FROM workflow_execution_environments", [])?;
        
        Ok(())
    }
}
