//! ComfyUI V2 模板管理命令
//! 基于新的模板引擎的 Tauri 命令

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tauri::State;
use tracing::{info, warn, error, debug};

use crate::app_state::AppState;
use crate::business::services::template_engine::{TemplateEngine, CacheStats};
use crate::data::models::comfyui::{
    TemplateModel, ParameterValues, ValidationResult,
    ParameterSchema, ParameterType,
};

// ==================== 请求和响应类型 ====================

/// ComfyUI V2 模板创建请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTemplateRequest {
    pub name: String,
    pub category: Option<String>,
    pub description: Option<String>,
    pub template_data: comfyui_sdk::types::WorkflowTemplateData,
    pub parameter_schema: HashMap<String, ParameterSchema>,
    pub tags: Vec<String>,
    pub author: Option<String>,
}

/// 模板更新请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateTemplateRequest {
    pub id: String,
    pub name: Option<String>,
    pub category: Option<String>,
    pub description: Option<String>,
    pub template_data: Option<comfyui_sdk::types::WorkflowTemplateData>,
    pub parameter_schema: Option<HashMap<String, ParameterSchema>>,
    pub tags: Option<Vec<String>>,
    pub author: Option<String>,
    pub enabled: Option<bool>,
}

/// 模板响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateResponse {
    pub id: String,
    pub name: String,
    pub category: Option<String>,
    pub description: Option<String>,
    pub parameter_schema: HashMap<String, ParameterSchema>,
    pub created_at: String,
    pub updated_at: String,
    pub enabled: bool,
    pub tags: Vec<String>,
    pub author: Option<String>,
    pub version: String,
}

/// 模板实例创建请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTemplateInstanceRequest {
    pub template_id: String,
    pub parameters: ParameterValues,
}

/// 模板实例响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateInstanceResponse {
    pub instance_id: String,
    pub template_id: String,
    pub workflow_data: HashMap<String, serde_json::Value>,
    pub parameters: ParameterValues,
    pub created_at: String,
}

/// 参数验证请求
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateParametersRequest {
    pub template_id: String,
    pub parameters: ParameterValues,
}

// ==================== 模板管理命令 ====================

/// 创建模板
#[tauri::command]
pub async fn comfyui_v2_create_template(
    request: CreateTemplateRequest,
    state: State<'_, AppState>,
) -> Result<TemplateResponse, String> {
    info!("Command: comfyui_v2_create_template - {}", request.name);

    let service_manager = get_service_manager(&state).await?;
    let template_engine = service_manager.get_template_engine().await
        .map_err(|e| format!("获取模板引擎失败: {}", e))?;

    // 创建模板模型
    let mut template = TemplateModel::new(
        request.name,
        request.template_data,
        request.parameter_schema,
    );

    // 设置可选字段
    template.category = request.category;
    template.description = request.description;
    template.tags = request.tags;
    template.author = request.author;

    // 保存模板
    template_engine.create_template(template.clone()).await
        .map_err(|e| format!("创建模板失败: {}", e))?;

    Ok(convert_template_model(&template))
}

/// 获取模板列表
#[tauri::command]
pub async fn comfyui_v2_list_templates(
    enabled_only: Option<bool>,
    state: State<'_, AppState>,
) -> Result<Vec<TemplateResponse>, String> {
    info!("Command: comfyui_v2_list_templates");

    let service_manager = get_service_manager(&state).await?;
    let template_engine = service_manager.get_template_engine().await
        .map_err(|e| format!("获取模板引擎失败: {}", e))?;

    let templates = template_engine.list_templates(enabled_only.unwrap_or(true)).await
        .map_err(|e| format!("获取模板列表失败: {}", e))?;

    let responses = templates.iter().map(convert_template_model).collect();
    Ok(responses)
}

/// 获取单个模板
#[tauri::command]
pub async fn comfyui_v2_get_template(
    template_id: String,
    state: State<'_, AppState>,
) -> Result<TemplateResponse, String> {
    info!("Command: comfyui_v2_get_template - {}", template_id);

    // TODO: 从模板引擎获取模板
    Err("模板不存在".to_string())
}

/// 更新模板
#[tauri::command]
pub async fn comfyui_v2_update_template(
    request: UpdateTemplateRequest,
    state: State<'_, AppState>,
) -> Result<TemplateResponse, String> {
    info!("Command: comfyui_v2_update_template - {}", request.id);

    // TODO: 更新模板
    Err("功能暂未实现".to_string())
}

/// 删除模板
#[tauri::command]
pub async fn comfyui_v2_delete_template(
    template_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_delete_template - {}", template_id);

    // TODO: 删除模板
    Ok("模板删除成功".to_string())
}

/// 按分类获取模板
#[tauri::command]
pub async fn comfyui_v2_get_templates_by_category(
    category: String,
    state: State<'_, AppState>,
) -> Result<Vec<TemplateResponse>, String> {
    info!("Command: comfyui_v2_get_templates_by_category - {}", category);

    // TODO: 按分类获取模板
    Ok(Vec::new())
}

/// 搜索模板
#[tauri::command]
pub async fn comfyui_v2_search_templates(
    query: String,
    state: State<'_, AppState>,
) -> Result<Vec<TemplateResponse>, String> {
    info!("Command: comfyui_v2_search_templates - {}", query);

    // TODO: 搜索模板
    Ok(Vec::new())
}

// ==================== 模板实例管理命令 ====================

/// 创建模板实例
#[tauri::command]
pub async fn comfyui_v2_create_template_instance(
    request: CreateTemplateInstanceRequest,
    state: State<'_, AppState>,
) -> Result<TemplateInstanceResponse, String> {
    info!("Command: comfyui_v2_create_template_instance - {}", request.template_id);

    // TODO: 创建模板实例
    Err("功能暂未实现".to_string())
}

/// 预览模板实例（不执行）
#[tauri::command]
pub async fn comfyui_v2_preview_template_instance(
    request: CreateTemplateInstanceRequest,
    state: State<'_, AppState>,
) -> Result<HashMap<String, serde_json::Value>, String> {
    info!("Command: comfyui_v2_preview_template_instance - {}", request.template_id);

    // TODO: 预览模板实例
    Ok(HashMap::new())
}

/// 验证模板参数
#[tauri::command]
pub async fn comfyui_v2_validate_template_parameters(
    request: ValidateParametersRequest,
    state: State<'_, AppState>,
) -> Result<ValidationResult, String> {
    info!("Command: comfyui_v2_validate_template_parameters - {}", request.template_id);

    let service_manager = get_service_manager(&state).await?;
    let template_engine = service_manager.get_template_engine().await
        .map_err(|e| format!("获取模板引擎失败: {}", e))?;

    let validation = template_engine.validate_parameters(&request.template_id, &request.parameters).await
        .map_err(|e| format!("参数验证失败: {}", e))?;

    Ok(validation)
}

/// 获取模板参数定义
#[tauri::command]
pub async fn comfyui_v2_get_template_parameter_schema(
    template_id: String,
    state: State<'_, AppState>,
) -> Result<HashMap<String, ParameterSchema>, String> {
    info!("Command: comfyui_v2_get_template_parameter_schema - {}", template_id);

    // TODO: 获取参数定义
    Ok(HashMap::new())
}

// ==================== 模板缓存管理命令 ====================

/// 获取模板缓存统计
#[tauri::command]
pub async fn comfyui_v2_get_template_cache_stats(
    state: State<'_, AppState>,
) -> Result<CacheStats, String> {
    info!("Command: comfyui_v2_get_template_cache_stats");

    // TODO: 获取缓存统计
    Ok(CacheStats {
        cached_templates: 0,
        cache_keys: Vec::new(),
    })
}

/// 清除模板缓存
#[tauri::command]
pub async fn comfyui_v2_clear_template_cache(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_clear_template_cache");

    // TODO: 清除缓存
    Ok("缓存清除成功".to_string())
}

/// 预热模板缓存
#[tauri::command]
pub async fn comfyui_v2_warm_template_cache(
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_warm_template_cache");

    // TODO: 预热缓存
    Ok("缓存预热成功".to_string())
}

// ==================== 模板导入导出命令 ====================

/// 导出模板
#[tauri::command]
pub async fn comfyui_v2_export_template(
    template_id: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_export_template - {}", template_id);

    // TODO: 导出模板
    Err("功能暂未实现".to_string())
}

/// 导入模板
#[tauri::command]
pub async fn comfyui_v2_import_template(
    template_json: String,
    state: State<'_, AppState>,
) -> Result<String, String> {
    info!("Command: comfyui_v2_import_template");

    // TODO: 导入模板
    Err("功能暂未实现".to_string())
}

// ==================== 辅助函数 ====================

// ==================== 辅助函数 ====================

/// 获取服务管理器
async fn get_service_manager(state: &State<'_, AppState>) -> Result<std::sync::Arc<crate::business::services::service_manager::ServiceManager>, String> {
    state.get_comfyui_manager().await
        .map_err(|e| format!("获取ComfyUI服务管理器失败: {}", e))
}

/// 获取配置管理器
async fn get_config_manager(state: &State<'_, AppState>) -> Result<std::sync::Arc<crate::business::services::config_manager::ConfigManager>, String> {
    state.get_config_manager().await
        .map_err(|e| format!("获取配置管理器失败: {}", e))
}

/// 转换模板模型为响应
fn convert_template_model(template: &TemplateModel) -> TemplateResponse {
    TemplateResponse {
        id: template.id.clone(),
        name: template.name.clone(),
        category: template.category.clone(),
        description: template.description.clone(),
        parameter_schema: template.parameter_schema.clone(),
        created_at: template.created_at.to_rfc3339(),
        updated_at: template.updated_at.to_rfc3339(),
        enabled: template.enabled,
        tags: template.tags.clone(),
        author: template.author.clone(),
        version: template.version.clone(),
    }
}
