"""
素材分类管理服务 V2
基于 PostgreSQL 数据库的素材分类管理，提供更好的性能和数据一致性
"""

import uuid
from typing import List, Dict, Optional
from dataclasses import asdict
from datetime import datetime

from python_core.utils.logger import logger
from python_core.database.types import ResourceCategory
from python_core.database.resource_category_postgres import resource_category_table


class ResourceCategoryManagerV2:
    """素材分类管理器 V2 - 基于 PostgreSQL"""
    
    def __init__(self, user_id: str = "default"):
        """
        初始化分类管理器
        
        Args:
            user_id: 用户ID，用于权限控制
        """
        self.user_id = user_id
        self.category_table = resource_category_table
    
    def get_all_categories(self, include_cloud: bool = True) -> List[Dict]:
        """
        获取所有分类
        
        Args:
            include_cloud: 是否包含云端公共分类
            
        Returns:
            分类列表
        """
        try:
            categories = self.category_table.get_categories_by_user(
                self.user_id, 
                include_cloud=include_cloud
            )
            return [asdict(category) for category in categories]
        except Exception as e:
            logger.error(f"Failed to get all categories: {e}")
            return []
    
    def get_category_by_id(self, category_id: str) -> Optional[Dict]:
        """
        根据ID获取分类
        
        Args:
            category_id: 分类ID
            
        Returns:
            分类信息，如果不存在返回None
        """
        try:
            category = self.category_table.get_category_by_id(category_id)
            if category and category.is_active:
                return asdict(category)
            return None
        except Exception as e:
            logger.error(f"Failed to get category by ID {category_id}: {e}")
            return None
    
    def get_category_by_title(self, title: str) -> Optional[Dict]:
        """
        根据标题获取分类
        
        Args:
            title: 分类标题
            
        Returns:
            分类信息，如果不存在返回None
        """
        try:
            category = self.category_table.get_category_by_title(title, self.user_id)
            if category and category.is_active:
                return asdict(category)
            return None
        except Exception as e:
            logger.error(f"Failed to get category by title {title}: {e}")
            return None
    
    def create_category(self, title: str, ai_prompt: str = "", color: str = "#FF5733", 
                       is_cloud: bool = False) -> Dict:
        """
        创建新分类
        
        Args:
            title: 分类标题
            ai_prompt: AI识别提示词
            color: 展示颜色（hex格式）
            is_cloud: 是否为云端公共分类
            
        Returns:
            创建的分类信息
        """
        try:
            now = datetime.now().isoformat()
            new_category = ResourceCategory(
                id=str(uuid.uuid4()),
                title=title,
                ai_prompt=ai_prompt,
                color=color,
                is_cloud=is_cloud,
                user_id=self.user_id,
                is_active=True,
                created_at=now,
                updated_at=now
            )
            
            category_id = self.category_table.create_category(new_category)
            
            # 获取创建后的分类信息
            created_category = self.category_table.get_category_by_id(category_id)
            if created_category:
                logger.info(f"Created new category: {title} (ID: {category_id})")
                return asdict(created_category)
            else:
                raise Exception("Failed to retrieve created category")
                
        except Exception as e:
            logger.error(f"Failed to create category {title}: {e}")
            raise
    
    def update_category(self, category_id: str, title: str = None,
                       ai_prompt: str = None, color: str = None, 
                       is_active: bool = None) -> Optional[Dict]:
        """
        更新分类
        
        Args:
            category_id: 分类ID
            title: 新标题
            ai_prompt: 新AI提示词
            color: 新颜色
            is_active: 新状态
            
        Returns:
            更新后的分类信息，如果失败返回None
        """
        try:
            # 构建更新字典
            updates = {}
            if title is not None:
                updates["title"] = title
            if ai_prompt is not None:
                updates["ai_prompt"] = ai_prompt
            if color is not None:
                updates["color"] = color
            if is_active is not None:
                updates["is_active"] = is_active
            
            if not updates:
                logger.warning("No fields to update")
                return None
            
            # 执行更新
            success = self.category_table.update_category(category_id, updates)
            if success:
                # 获取更新后的分类信息
                updated_category = self.category_table.get_category_by_id(category_id)
                if updated_category:
                    logger.info(f"Updated category: {category_id}")
                    return asdict(updated_category)
            
            return None
            
        except Exception as e:
            logger.error(f"Failed to update category {category_id}: {e}")
            return None
    
    def delete_category(self, category_id: str, hard_delete: bool = True) -> bool:
        """
        删除分类
        
        Args:
            category_id: 分类ID
            hard_delete: 是否硬删除（True）或软删除（False）
            
        Returns:
            删除成功返回True
        """
        try:
            success = self.category_table.delete_category(category_id, hard_delete=hard_delete)
            if success:
                delete_type = "hard deleted" if hard_delete else "soft deleted"
                logger.info(f"Category {delete_type}: {category_id}")
            return success
            
        except Exception as e:
            logger.error(f"Failed to delete category {category_id}: {e}")
            return False
    
    def search_categories(self, keyword: str, include_cloud: bool = True) -> List[Dict]:
        """
        搜索分类
        
        Args:
            keyword: 搜索关键词
            include_cloud: 是否包含云端公共分类
            
        Returns:
            匹配的分类列表
        """
        try:
            categories = self.category_table.search_categories(
                keyword, 
                self.user_id, 
                include_cloud=include_cloud
            )
            return [asdict(category) for category in categories]
            
        except Exception as e:
            logger.error(f"Failed to search categories with keyword {keyword}: {e}")
            return []
    
    def get_categories_by_color(self, color: str, include_cloud: bool = True) -> List[Dict]:
        """
        根据颜色获取分类
        
        Args:
            color: 颜色值（hex格式）
            include_cloud: 是否包含云端公共分类
            
        Returns:
            匹配的分类列表
        """
        try:
            categories = self.category_table.get_categories_by_color(
                color, 
                self.user_id, 
                include_cloud=include_cloud
            )
            return [asdict(category) for category in categories]
            
        except Exception as e:
            logger.error(f"Failed to get categories by color {color}: {e}")
            return []
    
    def get_cloud_categories(self) -> List[Dict]:
        """
        获取云端公共分类
        
        Returns:
            云端分类列表
        """
        try:
            categories = self.category_table.get_cloud_categories()
            return [asdict(category) for category in categories]
            
        except Exception as e:
            logger.error(f"Failed to get cloud categories: {e}")
            return []
    
    def get_category_count(self, include_cloud: bool = True) -> int:
        """
        获取分类数量
        
        Args:
            include_cloud: 是否包含云端公共分类
            
        Returns:
            分类数量
        """
        try:
            return self.category_table.get_category_count(self.user_id, include_cloud)
        except Exception as e:
            logger.error(f"Failed to get category count: {e}")
            return 0
    
    def activate_category(self, category_id: str) -> bool:
        """
        激活分类
        
        Args:
            category_id: 分类ID
            
        Returns:
            激活成功返回True
        """
        try:
            return self.category_table.activate_category(category_id)
        except Exception as e:
            logger.error(f"Failed to activate category {category_id}: {e}")
            return False
    
    def deactivate_category(self, category_id: str) -> bool:
        """
        停用分类
        
        Args:
            category_id: 分类ID
            
        Returns:
            停用成功返回True
        """
        try:
            return self.category_table.deactivate_category(category_id)
        except Exception as e:
            logger.error(f"Failed to deactivate category {category_id}: {e}")
            return False
    
    def batch_create_categories(self, categories_data: List[Dict]) -> Dict:
        """
        批量创建分类
        
        Args:
            categories_data: 分类数据列表，每个元素包含 title, ai_prompt, color 等字段
            
        Returns:
            创建结果统计
        """
        try:
            categories = []
            now = datetime.now().isoformat()
            
            for data in categories_data:
                category = ResourceCategory(
                    id=str(uuid.uuid4()),
                    title=data.get("title", ""),
                    ai_prompt=data.get("ai_prompt", ""),
                    color=data.get("color", "#FF5733"),
                    is_cloud=data.get("is_cloud", False),
                    user_id=self.user_id,
                    is_active=True,
                    created_at=now,
                    updated_at=now
                )
                categories.append(category)
            
            result = self.category_table.batch_create_categories(categories)
            logger.info(f"Batch create completed: {result['success']} success, {result['failed']} failed")
            return result
            
        except Exception as e:
            logger.error(f"Failed to batch create categories: {e}")
            return {
                "total": len(categories_data),
                "success": 0,
                "failed": len(categories_data),
                "error": str(e)
            }


# 创建全局管理器实例（使用默认用户）
resource_category_manager_v2 = ResourceCategoryManagerV2()
