"""
资源分类管理CLI命令
"""

from typing import Optional
import typer
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
import json
import re

from python_core.services.resource_category_manager import ResourceCategoryManager, ResourceCategory
from python_core.utils.logger import logger

console = Console()
category_app = typer.Typer(name="category", help="资源分类管理命令")


def validate_color(color: str) -> bool:
    """验证颜色格式（hex格式）"""
    pattern = r'^#[0-9A-Fa-f]{6}$'
    return bool(re.match(pattern, color))


@category_app.command("list")
def list_categories(
    include_inactive: bool = typer.Option(False, "--include-inactive", "-i", help="包含已禁用的分类"),
    limit: int = typer.Option(20, "--limit", "-l", help="显示数量限制"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    format_output: str = typer.Option("table", "--format", "-f", help="输出格式: table, json")
):
    """列出所有资源分类"""
    
    try:
        console.print(f"📋 [bold blue]资源分类列表[/bold blue]")
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 获取分类列表
        categories = manager.get_all_categories()
        
        # 过滤非活跃分类
        if not include_inactive:
            categories = [cat for cat in categories if cat.get('is_active', True)]
        
        if not categories:
            console.print("📭 没有分类")
            return
        
        # 限制显示数量
        total_count = len(categories)
        if len(categories) > limit:
            categories = categories[:limit]
            console.print(f"📊 显示前 {limit} 个分类（共 {total_count} 个）")
        else:
            console.print(f"📊 共 {total_count} 个分类")
        
        if format_output == "json":
            # JSON格式输出
            console.print(json.dumps(categories, ensure_ascii=False, indent=2))
            return
        
        # 表格格式输出
        table = Table(title="资源分类列表")
        table.add_column("ID", style="cyan", width=12)
        table.add_column("标题", style="green")
        table.add_column("AI提示词", style="yellow")
        table.add_column("颜色", style="magenta")
        table.add_column("状态", style="blue")
        table.add_column("创建时间", style="dim")
        
        if verbose:
            table.add_column("更新时间", style="dim")
        
        for category in categories:
            # 状态
            status = "✅ 启用" if category.get('is_active', True) else "❌ 禁用"
            
            # 格式化创建时间
            created_at = category.get('created_at', '')
            if 'T' in created_at:
                created_at = created_at.split('T')[0] + ' ' + created_at.split('T')[1][:8]
            
            # 颜色显示
            color = category.get('color', '')
            color_display = f"[{color}]●[/{color}] {color}" if color else color
            
            row = [
                category.get('id', '')[:12],
                category.get('title', ''),
                category.get('ai_prompt', '')[:30] + ('...' if len(category.get('ai_prompt', '')) > 30 else ''),
                color_display,
                status,
                created_at
            ]
            
            if verbose:
                updated_at = category.get('updated_at', '')
                if 'T' in updated_at:
                    updated_at = updated_at.split('T')[0] + ' ' + updated_at.split('T')[1][:8]
                row.append(updated_at)
            
            table.add_row(*row)
        
        console.print(table)
        
    except Exception as e:
        console.print(f"[red]❌ 获取分类列表失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("create")
def create_category(
    title: str = typer.Argument(..., help="分类标题"),
    ai_prompt: str = typer.Argument(..., help="AI识别提示词"),
    color: str = typer.Argument(..., help="展示颜色（hex格式，如 #FF5733）"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出")
):
    """创建新的资源分类"""
    
    try:
        console.print(f"🆕 [bold blue]创建资源分类[/bold blue]")
        console.print(f"标题: {title}")
        console.print(f"AI提示词: {ai_prompt}")
        console.print(f"颜色: {color}")
        
        # 验证颜色格式
        if not validate_color(color):
            console.print(f"[red]❌ 颜色格式无效: {color}[/red]")
            console.print("颜色必须是hex格式，如: #FF5733")
            raise typer.Exit(1)
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 创建分类
        result = manager.create_category(title, ai_prompt, color)
        
        console.print(f"\n✅ [bold green]分类创建成功![/bold green]")
        console.print(f"分类ID: {result['id']}")
        console.print(f"创建时间: {result['created_at']}")
        
        if verbose:
            # 显示分类详细信息
            category_info = f"""
🆔 分类ID: {result['id']}
📝 标题: {result['title']}
🤖 AI提示词: {result['ai_prompt']}
🎨 颜色: {result['color']}
📅 创建时间: {result['created_at']}
🔄 更新时间: {result['updated_at']}
✅ 状态: {'启用' if result['is_active'] else '禁用'}
            """
            
            panel = Panel(category_info.strip(), title="分类详情", border_style="green")
            console.print(panel)
        
    except Exception as e:
        console.print(f"[red]❌ 创建分类失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("get")
def get_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出"),
    format_output: str = typer.Option("panel", "--format", "-f", help="输出格式: panel, json")
):
    """获取分类详情"""
    
    try:
        console.print(f"🔍 [bold blue]获取分类详情[/bold blue]")
        console.print(f"分类ID: {category_id}")
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 获取分类
        category = manager.get_category_by_id(category_id)
        
        if not category:
            console.print(f"[red]❌ 未找到分类: {category_id}[/red]")
            raise typer.Exit(1)
        
        if format_output == "json":
            # JSON格式输出
            console.print(json.dumps(category, ensure_ascii=False, indent=2))
            return
        
        # 面板格式输出
        console.print(f"\n✅ [bold green]分类详情[/bold green]")
        
        # 基本信息
        basic_info = f"""
🆔 分类ID: {category.get('id', '')}
📝 标题: {category.get('title', '')}
🤖 AI提示词: {category.get('ai_prompt', '')}
🎨 颜色: {category.get('color', '')}
📅 创建时间: {category.get('created_at', '')}
🔄 更新时间: {category.get('updated_at', '')}
✅ 状态: {'启用' if category.get('is_active', True) else '禁用'}
        """
        
        panel = Panel(basic_info.strip(), title="分类基本信息", border_style="green")
        console.print(panel)
        
        if verbose:
            # 显示颜色预览
            color = category.get('color', '')
            if color:
                color_info = f"""
🎨 颜色预览: [{color}]████████[/{color}] {color}
                """
                color_panel = Panel(color_info.strip(), title="颜色预览", border_style="blue")
                console.print(color_panel)
        
    except Exception as e:
        console.print(f"[red]❌ 获取分类详情失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("update")
def update_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    title: Optional[str] = typer.Option(None, "--title", "-t", help="新的标题"),
    ai_prompt: Optional[str] = typer.Option(None, "--ai-prompt", "-p", help="新的AI提示词"),
    color: Optional[str] = typer.Option(None, "--color", "-c", help="新的颜色（hex格式）"),
    active: Optional[bool] = typer.Option(None, "--active", "-a", help="是否启用"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出")
):
    """更新分类信息"""
    
    try:
        console.print(f"🔄 [bold blue]更新分类[/bold blue]")
        console.print(f"分类ID: {category_id}")
        
        # 验证至少有一个更新参数
        if not any([title, ai_prompt, color, active is not None]):
            console.print(f"[red]❌ 请至少提供一个要更新的参数[/red]")
            raise typer.Exit(1)
        
        # 验证颜色格式（如果提供）
        if color and not validate_color(color):
            console.print(f"[red]❌ 颜色格式无效: {color}[/red]")
            console.print("颜色必须是hex格式，如: #FF5733")
            raise typer.Exit(1)
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 更新分类
        result = manager.update_category(
            category_id=category_id,
            title=title,
            ai_prompt=ai_prompt,
            color=color,
            is_active=active
        )
        
        if not result:
            console.print(f"[red]❌ 未找到分类或更新失败: {category_id}[/red]")
            raise typer.Exit(1)
        
        console.print(f"\n✅ [bold green]分类更新成功![/bold green]")
        console.print(f"更新时间: {result['updated_at']}")
        
        if verbose:
            # 显示更新后的分类信息
            category_info = f"""
🆔 分类ID: {result['id']}
📝 标题: {result['title']}
🤖 AI提示词: {result['ai_prompt']}
🎨 颜色: {result['color']}
📅 创建时间: {result['created_at']}
🔄 更新时间: {result['updated_at']}
✅ 状态: {'启用' if result['is_active'] else '禁用'}
            """
            
            panel = Panel(category_info.strip(), title="更新后的分类信息", border_style="green")
            console.print(panel)
        
    except Exception as e:
        console.print(f"[red]❌ 更新分类失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("delete")
def delete_category(
    category_id: str = typer.Argument(..., help="分类ID"),
    force: bool = typer.Option(False, "--force", "-f", help="强制删除，不询问确认")
):
    """删除分类"""
    
    try:
        console.print(f"🗑️ [bold red]删除分类[/bold red]")
        console.print(f"分类ID: {category_id}")
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 获取分类信息
        category = manager.get_category_by_id(category_id)
        if not category:
            console.print(f"[red]❌ 未找到分类: {category_id}[/red]")
            raise typer.Exit(1)
        
        console.print(f"分类标题: {category.get('title', 'Unknown')}")
        console.print(f"AI提示词: {category.get('ai_prompt', 'Unknown')}")
        
        # 确认删除
        if not force:
            confirm = typer.confirm("确定要删除这个分类吗？此操作不可恢复。")
            if not confirm:
                console.print("❌ 操作已取消")
                return
        
        # 删除分类
        success = manager.delete_category(category_id)
        
        if success:
            console.print(f"✅ [bold green]分类删除成功[/bold green]")
        else:
            console.print(f"[red]❌ 分类删除失败[/red]")
            raise typer.Exit(1)
        
    except Exception as e:
        console.print(f"[red]❌ 删除分类失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("search")
def search_categories(
    keyword: str = typer.Argument(..., help="搜索关键词"),
    limit: int = typer.Option(10, "--limit", "-l", help="显示数量限制"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="详细输出")
):
    """搜索分类"""
    
    try:
        console.print(f"🔍 [bold blue]搜索分类[/bold blue]")
        console.print(f"关键词: {keyword}")
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 搜索分类
        categories = manager.search_categories(keyword)
        
        if not categories:
            console.print(f"📭 没有找到匹配 '{keyword}' 的分类")
            return
        
        console.print(f"✅ 找到 {len(categories)} 个匹配的分类")
        
        # 限制显示数量
        if len(categories) > limit:
            categories = categories[:limit]
            console.print(f"📊 显示前 {limit} 个结果")
        
        # 创建表格
        table = Table(title=f"搜索结果: {keyword}")
        table.add_column("ID", style="cyan", width=12)
        table.add_column("标题", style="green")
        table.add_column("AI提示词", style="yellow")
        table.add_column("颜色", style="magenta")
        table.add_column("状态", style="blue")
        
        if verbose:
            table.add_column("创建时间", style="dim")
        
        for category in categories:
            status = "✅ 启用" if category.get('is_active', True) else "❌ 禁用"
            
            # 颜色显示
            color = category.get('color', '')
            color_display = f"[{color}]●[/{color}] {color}" if color else color
            
            row = [
                category.get('id', '')[:12],
                category.get('title', ''),
                category.get('ai_prompt', '')[:30] + ('...' if len(category.get('ai_prompt', '')) > 30 else ''),
                color_display,
                status
            ]
            
            if verbose:
                created_at = category.get('created_at', '')
                if 'T' in created_at:
                    created_at = created_at.split('T')[0] + ' ' + created_at.split('T')[1][:8]
                row.append(created_at)
            
            table.add_row(*row)
        
        console.print(table)
        
    except Exception as e:
        console.print(f"[red]❌ 搜索分类失败: {str(e)}[/red]")
        raise typer.Exit(1)


@category_app.command("stats")
def show_stats():
    """显示分类统计信息"""
    
    try:
        console.print(f"📊 [bold blue]分类统计信息[/bold blue]")
        
        # 创建分类管理器
        manager = ResourceCategoryManager()
        
        # 获取所有分类
        categories = manager.get_all_categories()
        
        if not categories:
            console.print("📭 没有分类")
            return
        
        # 计算统计信息
        total_categories = len(categories)
        active_categories = len([cat for cat in categories if cat.get('is_active', True)])
        inactive_categories = total_categories - active_categories
        
        # 颜色统计
        colors = {}
        for category in categories:
            color = category.get('color', '')
            if color:
                colors[color] = colors.get(color, 0) + 1
        
        # 创建统计面板
        stats_content = f"""
📈 [bold green]总体统计[/bold green]
   分类总数: {total_categories}
   启用分类: {active_categories}
   禁用分类: {inactive_categories}
   使用的颜色: {len(colors)}
        """
        
        stats_panel = Panel(stats_content.strip(), title="分类统计", border_style="green")
        console.print(stats_panel)
        
        # 显示最近的分类
        recent_categories = sorted(categories, key=lambda x: x.get('created_at', ''), reverse=True)[:5]
        
        if recent_categories:
            console.print(f"\n🕒 [bold green]最近创建的分类[/bold green]")
            
            recent_table = Table()
            recent_table.add_column("标题", style="green")
            recent_table.add_column("颜色", style="magenta")
            recent_table.add_column("创建时间", style="dim")
            
            for category in recent_categories:
                color = category.get('color', '')
                color_display = f"[{color}]●[/{color}] {color}" if color else color
                
                created_at = category.get('created_at', '')
                if 'T' in created_at:
                    created_at = created_at.split('T')[0] + ' ' + created_at.split('T')[1][:8]
                
                recent_table.add_row(
                    category.get('title', 'Unknown'),
                    color_display,
                    created_at
                )
            
            console.print(recent_table)
        
        # 显示颜色使用统计
        if colors:
            console.print(f"\n🎨 [bold green]颜色使用统计[/bold green]")
            
            color_table = Table()
            color_table.add_column("颜色", style="magenta")
            color_table.add_column("使用次数", style="cyan")
            
            for color, count in sorted(colors.items(), key=lambda x: x[1], reverse=True):
                color_display = f"[{color}]●[/{color}] {color}"
                color_table.add_row(color_display, str(count))
            
            console.print(color_table)
        
    except Exception as e:
        console.print(f"[red]❌ 获取统计信息失败: {str(e)}[/red]")
        raise typer.Exit(1)


if __name__ == "__main__":
    category_app()
