"""
素材分类管理 CLI 命令
"""

import typer
import json
from typing import Optional, List, Dict, Any
from dataclasses import asdict

from python_core.utils.logger import logger
from python_core.utils.jsonrpc import create_response_handler
from python_core.services.resource_category_manager_v2 import ResourceCategoryManagerV2

# 创建子应用
resource_category_app = typer.Typer(help="素材分类管理命令")


@resource_category_app.command("list")
def list_categories(
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    include_cloud: bool = typer.Option(True, "--include-cloud/--no-include-cloud", help="是否包含云端分类"),
    limit: int = typer.Option(100, "--limit", help="最大返回数量"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """获取所有素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        categories = manager.get_all_categories(include_cloud=include_cloud)
        
        # 限制返回数量
        if limit > 0:
            categories = categories[:limit]
        
        response.success(categories)
        
    except Exception as e:
        logger.error(f"获取分类列表失败: {e}")
        response.error(-32603, f"获取分类列表失败: {str(e)}")


@resource_category_app.command("get")
def get_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """根据ID获取素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        category = manager.get_category_by_id(category_id)
        
        if category:
            response.success(category)
        else:
            response.error(-32603, f"分类不存在: {category_id}")
            
    except Exception as e:
        logger.error(f"获取分类失败: {e}")
        response.error(-32603, f"获取分类失败: {str(e)}")


@resource_category_app.command("create")
def create_category(
    title: str = typer.Argument(..., help="分类标题"),
    ai_prompt: Optional[str] = typer.Option("", "--ai-prompt", help="AI识别提示词"),
    color: Optional[str] = typer.Option("#FF5733", "--color", help="展示颜色"),
    is_cloud: bool = typer.Option(False, "--is-cloud", help="是否为云端分类"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """创建新的素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        category = manager.create_category(
            title=title,
            ai_prompt=ai_prompt,
            color=color,
            is_cloud=is_cloud
        )
        
        response.success(category)
        
    except Exception as e:
        logger.error(f"创建分类失败: {e}")
        response.error(-32603, f"创建分类失败: {str(e)}")


@resource_category_app.command("update")
def update_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    title: Optional[str] = typer.Option(None, "--title", help="新标题"),
    ai_prompt: Optional[str] = typer.Option(None, "--ai-prompt", help="新AI提示词"),
    color: Optional[str] = typer.Option(None, "--color", help="新颜色"),
    activate: bool = typer.Option(False, "--activate", help="激活分类"),
    deactivate: bool = typer.Option(False, "--deactivate", help="停用分类"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """更新素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        
        # 处理激活/停用状态
        is_active = None
        if activate and deactivate:
            response.error(-32602, "不能同时指定激活和停用")
            return
        elif activate:
            is_active = True
        elif deactivate:
            is_active = False
        
        category = manager.update_category(
            category_id=category_id,
            title=title,
            ai_prompt=ai_prompt,
            color=color,
            is_active=is_active
        )
        
        if category:
            response.success(category)
        else:
            response.error(-32603, f"更新分类失败: {category_id}")
            
    except Exception as e:
        logger.error(f"更新分类失败: {e}")
        response.error(-32603, f"更新分类失败: {str(e)}")


@resource_category_app.command("delete")
def delete_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    hard_delete: bool = typer.Option(True, "--hard-delete/--soft-delete", help="硬删除或软删除"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """删除素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        success = manager.delete_category(category_id, hard_delete=hard_delete)
        
        if success:
            delete_type = "硬删除" if hard_delete else "软删除"
            response.success({"message": f"分类{delete_type}成功", "category_id": category_id})
        else:
            response.error(-32603, f"删除分类失败: {category_id}")
            
    except Exception as e:
        logger.error(f"删除分类失败: {e}")
        response.error(-32603, f"删除分类失败: {str(e)}")


@resource_category_app.command("search")
def search_categories(
    query: str = typer.Argument(..., help="搜索关键词"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    include_cloud: bool = typer.Option(True, "--include-cloud/--no-include-cloud", help="是否包含云端分类"),
    limit: int = typer.Option(50, "--limit", help="最大返回数量"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """搜索素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        categories = manager.search_categories(query, include_cloud=include_cloud)
        
        # 限制返回数量
        if limit > 0:
            categories = categories[:limit]
        
        response.success(categories)
        
    except Exception as e:
        logger.error(f"搜索分类失败: {e}")
        response.error(-32603, f"搜索分类失败: {str(e)}")


@resource_category_app.command("by-color")
def get_categories_by_color(
    color: str = typer.Argument(..., help="颜色值（hex格式）"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    include_cloud: bool = typer.Option(True, "--include-cloud/--no-include-cloud", help="是否包含云端分类"),
    limit: int = typer.Option(50, "--limit", help="最大返回数量"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """根据颜色获取素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        categories = manager.get_categories_by_color(color, include_cloud=include_cloud)
        
        # 限制返回数量
        if limit > 0:
            categories = categories[:limit]
        
        response.success(categories)
        
    except Exception as e:
        logger.error(f"按颜色获取分类失败: {e}")
        response.error(-32603, f"按颜色获取分类失败: {str(e)}")


@resource_category_app.command("cloud")
def get_cloud_categories(
    limit: int = typer.Option(100, "--limit", help="最大返回数量"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """获取云端素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2()
        categories = manager.get_cloud_categories()
        
        # 限制返回数量
        if limit > 0:
            categories = categories[:limit]
        
        response.success(categories)
        
    except Exception as e:
        logger.error(f"获取云端分类失败: {e}")
        response.error(-32603, f"获取云端分类失败: {str(e)}")


@resource_category_app.command("count")
def get_category_count(
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    include_cloud: bool = typer.Option(True, "--include-cloud/--no-include-cloud", help="是否包含云端分类"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """获取素材分类数量"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        count = manager.get_category_count(include_cloud=include_cloud)
        
        response.success({"count": count})
        
    except Exception as e:
        logger.error(f"获取分类数量失败: {e}")
        response.error(-32603, f"获取分类数量失败: {str(e)}")


@resource_category_app.command("activate")
def activate_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """激活素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        success = manager.activate_category(category_id)
        
        if success:
            response.success({"message": "分类激活成功", "category_id": category_id})
        else:
            response.error(-32603, f"激活分类失败: {category_id}")
            
    except Exception as e:
        logger.error(f"激活分类失败: {e}")
        response.error(-32603, f"激活分类失败: {str(e)}")


@resource_category_app.command("deactivate")
def deactivate_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """停用素材分类"""
    response = create_response_handler()
    try:
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        success = manager.deactivate_category(category_id)
        
        if success:
            response.success({"message": "分类停用成功", "category_id": category_id})
        else:
            response.error(-32603, f"停用分类失败: {category_id}")
            
    except Exception as e:
        logger.error(f"停用分类失败: {e}")
        response.error(-32603, f"停用分类失败: {str(e)}")


@resource_category_app.command("batch-create")
def batch_create_categories(
    data: str = typer.Option(..., "--data", help="批量创建数据（JSON格式）"),
    user_id: Optional[str] = typer.Option(None, "--user-id", help="用户ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    json_output: bool = typer.Option(True, "--json", help="JSON格式输出")
):
    """批量创建素材分类"""
    response = create_response_handler()
    try:
        # 解析批量数据
        categories_data = json.loads(data)
        
        manager = ResourceCategoryManagerV2(user_id=user_id or "default")
        result = manager.batch_create_categories(categories_data)
        
        response.success(result)
        
    except json.JSONDecodeError as e:
        logger.error(f"解析批量数据失败: {e}")
        response.error(-32602, f"解析批量数据失败: {str(e)}")
    except Exception as e:
        logger.error(f"批量创建分类失败: {e}")
        response.error(-32603, f"批量创建分类失败: {str(e)}")
