/**
 * ResourceCategory 命令封装
 * 统一使用 execute_python_cli_command 模式
 */

use serde::{Deserialize, Serialize};
use tauri::{command, AppHandle};
use crate::python_executor::execute_python_command;

#[derive(Debug, Serialize, Deserialize)]
pub struct ResourceCategoryResponse {
    pub success: bool,
    pub message: String,
    pub data: Option<serde_json::Value>,
    pub output: Option<String>,
    pub error: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryListRequest {
    pub user_id: Option<String>,
    pub include_cloud: Option<bool>,
    pub limit: Option<i32>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryGetRequest {
    pub category_id: String,
    pub user_id: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryCreateRequest {
    pub title: String,
    pub ai_prompt: Option<String>,
    pub color: Option<String>,
    pub is_cloud: Option<bool>,
    pub user_id: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryUpdateRequest {
    pub category_id: String,
    pub title: Option<String>,
    pub ai_prompt: Option<String>,
    pub color: Option<String>,
    pub is_active: Option<bool>,
    pub user_id: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryDeleteRequest {
    pub category_id: String,
    pub hard_delete: Option<bool>,
    pub user_id: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategorySearchRequest {
    pub query: String,
    pub user_id: Option<String>,
    pub include_cloud: Option<bool>,
    pub limit: Option<i32>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryColorRequest {
    pub color: String,
    pub user_id: Option<String>,
    pub include_cloud: Option<bool>,
    pub limit: Option<i32>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Deserialize)]
pub struct CategoryBatchCreateRequest {
    pub categories: Vec<CategoryBatchItem>,
    pub user_id: Option<String>,
    pub verbose: Option<bool>,
    pub json_output: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CategoryBatchItem {
    pub title: String,
    pub ai_prompt: Option<String>,
    pub color: Option<String>,
    pub is_cloud: Option<bool>,
}

// 保持向后兼容的旧结构体
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateCategoryRequest {
    pub title: String,
    pub ai_prompt: String,
    pub color: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateCategoryRequest {
    pub title: Option<String>,
    pub ai_prompt: Option<String>,
    pub color: Option<String>,
    pub is_active: Option<bool>,
}

/// 执行Python CLI命令的通用函数（统一模式）
async fn execute_python_cli_command(
    app: AppHandle,
    command_args: Vec<String>,
) -> Result<ResourceCategoryResponse, String> {
    // 构建完整的命令参数
    let mut args = vec!["-m".to_string(), "python_core.cli".to_string()];
    args.extend(command_args);

    println!("Executing ResourceCategory CLI: python {}", args.join(" "));

    match execute_python_command(app, &args, None).await {
        Ok(output) => {
            // 尝试解析JSON响应
            if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&output) {
                Ok(ResourceCategoryResponse {
                    success: true,
                    message: "素材分类命令执行成功".to_string(),
                    data: Some(json_value),
                    output: Some(output),
                    error: None,
                })
            } else {
                // 如果不是JSON，直接返回文本输出
                Ok(ResourceCategoryResponse {
                    success: true,
                    message: "素材分类命令执行成功".to_string(),
                    data: None,
                    output: Some(output),
                    error: None,
                })
            }
        }
        Err(error) => {
            Ok(ResourceCategoryResponse {
                success: false,
                message: "素材分类命令执行失败".to_string(),
                data: None,
                output: None,
                error: Some(error),
            })
        }
    }
}

/// 获取所有资源分类（新版本，使用CLI模式）
#[command]
pub async fn get_all_resource_categories_cli(
    app: AppHandle,
    request: CategoryListRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "list".to_string()];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.include_cloud.unwrap_or(true) {
        args.push("--include-cloud".to_string());
    }

    if let Some(limit) = request.limit {
        args.push("--limit".to_string());
        args.push(limit.to_string());
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 获取所有资源分类（保持向后兼容）
#[command]
pub async fn get_all_resource_categories(app: AppHandle) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "get_all_categories".to_string(),
    ];

    execute_python_command(app, &args, None).await
}

/// 根据ID获取资源分类（新版本，使用CLI模式）
#[command]
pub async fn get_resource_category_by_id_cli(
    app: AppHandle,
    request: CategoryGetRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "get".to_string(), request.category_id];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 根据ID获取资源分类（保持向后兼容）
#[command]
pub async fn get_resource_category_by_id(app: AppHandle, category_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "get_category_by_id".to_string(),
        category_id,
    ];

    execute_python_command(app, &args, None).await
}

/// 创建新的资源分类（新版本，使用CLI模式）
#[command]
pub async fn create_resource_category_cli(
    app: AppHandle,
    request: CategoryCreateRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "create".to_string(), request.title];

    if let Some(ai_prompt) = request.ai_prompt {
        args.push("--ai-prompt".to_string());
        args.push(ai_prompt);
    }

    if let Some(color) = request.color {
        args.push("--color".to_string());
        args.push(color);
    }

    if request.is_cloud.unwrap_or(false) {
        args.push("--is-cloud".to_string());
    }

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 创建新的资源分类（保持向后兼容）
#[command]
pub async fn create_resource_category(app: AppHandle, request: CreateCategoryRequest) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "create_category".to_string(),
        request.title,
        request.ai_prompt,
        request.color,
    ];

    execute_python_command(app, &args, None).await
}

/// 更新资源分类（新版本，使用CLI模式）
#[command]
pub async fn update_resource_category_cli(
    app: AppHandle,
    request: CategoryUpdateRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "update".to_string(), request.category_id];

    if let Some(title) = request.title {
        args.push("--title".to_string());
        args.push(title);
    }

    if let Some(ai_prompt) = request.ai_prompt {
        args.push("--ai-prompt".to_string());
        args.push(ai_prompt);
    }

    if let Some(color) = request.color {
        args.push("--color".to_string());
        args.push(color);
    }

    if let Some(is_active) = request.is_active {
        if is_active {
            args.push("--activate".to_string());
        } else {
            args.push("--deactivate".to_string());
        }
    }

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 更新资源分类（保持向后兼容）
#[command]
pub async fn update_resource_category(
    app: AppHandle,
    category_id: String,
    request: UpdateCategoryRequest,
) -> Result<String, String> {
    let request_json = serde_json::to_string(&request)
        .map_err(|e| format!("Failed to serialize request: {}", e))?;

    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "update_category".to_string(),
        category_id,
        request_json,
    ];

    execute_python_command(app, &args, None).await
}

/// 删除资源分类（新版本，使用CLI模式）
#[command]
pub async fn delete_resource_category_cli(
    app: AppHandle,
    request: CategoryDeleteRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "delete".to_string(), request.category_id];

    if request.hard_delete.unwrap_or(true) {
        args.push("--hard-delete".to_string());
    }

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 删除资源分类（保持向后兼容）
#[command]
pub async fn delete_resource_category(app: AppHandle, category_id: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "delete_category".to_string(),
        category_id,
    ];

    execute_python_command(app, &args, None).await
}

/// 搜索资源分类（新版本，使用CLI模式）
#[command]
pub async fn search_resource_categories_cli(
    app: AppHandle,
    request: CategorySearchRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "search".to_string(), request.query];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.include_cloud.unwrap_or(true) {
        args.push("--include-cloud".to_string());
    }

    if let Some(limit) = request.limit {
        args.push("--limit".to_string());
        args.push(limit.to_string());
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 搜索资源分类（保持向后兼容）
#[command]
pub async fn search_resource_categories(app: AppHandle, keyword: String) -> Result<String, String> {
    let args = vec![
        "-m".to_string(),
        "python_core.services.resource_category_manager".to_string(),
        "search_categories".to_string(),
        keyword,
    ];

    execute_python_command(app, &args, None).await
}

/// 按颜色获取资源分类（新版本，使用CLI模式）
#[command]
pub async fn get_resource_categories_by_color_cli(
    app: AppHandle,
    request: CategoryColorRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "by-color".to_string(), request.color];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.include_cloud.unwrap_or(true) {
        args.push("--include-cloud".to_string());
    }

    if let Some(limit) = request.limit {
        args.push("--limit".to_string());
        args.push(limit.to_string());
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 获取云端资源分类（新版本，使用CLI模式）
#[command]
pub async fn get_cloud_resource_categories_cli(
    app: AppHandle,
    request: CategoryListRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "cloud".to_string()];

    if let Some(limit) = request.limit {
        args.push("--limit".to_string());
        args.push(limit.to_string());
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 批量创建资源分类（新版本，使用CLI模式）
#[command]
pub async fn batch_create_resource_categories_cli(
    app: AppHandle,
    request: CategoryBatchCreateRequest,
) -> Result<ResourceCategoryResponse, String> {
    // 将批量数据序列化为JSON
    let categories_json = serde_json::to_string(&request.categories)
        .map_err(|e| format!("Failed to serialize categories: {}", e))?;

    let mut args = vec!["resource-category".to_string(), "batch-create".to_string()];

    // 通过临时文件传递批量数据
    args.push("--data".to_string());
    args.push(categories_json);

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 获取资源分类数量（新版本，使用CLI模式）
#[command]
pub async fn get_resource_category_count_cli(
    app: AppHandle,
    request: CategoryListRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "count".to_string()];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.include_cloud.unwrap_or(true) {
        args.push("--include-cloud".to_string());
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 激活资源分类（新版本，使用CLI模式）
#[command]
pub async fn activate_resource_category_cli(
    app: AppHandle,
    request: CategoryGetRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "activate".to_string(), request.category_id];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}

/// 停用资源分类（新版本，使用CLI模式）
#[command]
pub async fn deactivate_resource_category_cli(
    app: AppHandle,
    request: CategoryGetRequest,
) -> Result<ResourceCategoryResponse, String> {
    let mut args = vec!["resource-category".to_string(), "deactivate".to_string(), request.category_id];

    if let Some(user_id) = request.user_id {
        args.push("--user-id".to_string());
        args.push(user_id);
    }

    if request.verbose.unwrap_or(false) {
        args.push("--verbose".to_string());
    }

    if request.json_output.unwrap_or(true) {
        args.push("--json".to_string());
    }

    execute_python_cli_command(app, args).await
}
