"""
素材分类管理服务
管理素材分类信息，包括分类标题、AI识别提示词和展示颜色
"""

import json
import uuid
from pathlib import Path
from typing import List, Dict, Optional
from dataclasses import dataclass, asdict
from datetime import datetime

from python_core.config import settings
from python_core.utils.logger import logger
from python_core.utils.jsonrpc import create_response_handler


@dataclass
class ResourceCategory:
    """素材分类数据结构"""
    id: str
    title: str  # 分类标题
    ai_prompt: str  # AI识别提示词
    color: str  # 展示颜色 (hex格式，如 #FF5733)
    created_at: str
    updated_at: str
    is_active: bool = True


class ResourceCategoryManager:
    """素材分类管理器"""
    
    def __init__(self):
        self.cache_dir = settings.temp_dir / "cache"
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        
        # 分类数据文件
        self.categories_file = self.cache_dir / "resource_category.json"
        self.categories = self._load_categories()
    
    def _load_categories(self) -> List[ResourceCategory]:
        """加载分类数据"""
        if self.categories_file.exists():
            try:
                with open(self.categories_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    return [ResourceCategory(**item) for item in data]
            except Exception as e:
                logger.error(f"Failed to load categories: {e}")
                return self._create_default_categories()
        else:
            return self._create_default_categories()
    
    def _create_default_categories(self) -> List[ResourceCategory]:
        """创建默认分类"""
        default_categories = []
        self._save_categories(default_categories)
        return default_categories
    
    def _save_categories(self, categories: List[ResourceCategory] = None):
        """保存分类数据"""
        if categories is None:
            categories = self.categories
        
        try:
            data = [asdict(category) for category in categories]
            with open(self.categories_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            logger.info(f"Categories saved to {self.categories_file}")
        except Exception as e:
            logger.error(f"Failed to save categories: {e}")
            raise
    
    def get_all_categories(self) -> List[Dict]:
        """获取所有分类"""
        return [asdict(category) for category in self.categories]
    
    def get_category_by_id(self, category_id: str) -> Optional[Dict]:
        """根据ID获取分类"""
        for category in self.categories:
            if category.id == category_id and category.is_active:
                return asdict(category)
        return None
    
    def create_category(self, title: str, ai_prompt: str, color: str) -> Dict:
        """创建新分类"""
        now = datetime.now().isoformat()
        new_category = ResourceCategory(
            id=str(uuid.uuid4()),
            title=title,
            ai_prompt=ai_prompt,
            color=color,
            created_at=now,
            updated_at=now
        )
        
        self.categories.append(new_category)
        self._save_categories()
        
        logger.info(f"Created new category: {title}")
        return asdict(new_category)
    
    def update_category(self, category_id: str, title: str = None,
                       ai_prompt: str = None, color: str = None, is_active: bool = None) -> Optional[Dict]:
        """更新分类"""
        for i, category in enumerate(self.categories):
            if category.id == category_id:
                if title is not None:
                    category.title = title
                if ai_prompt is not None:
                    category.ai_prompt = ai_prompt
                if color is not None:
                    category.color = color
                if is_active is not None:
                    category.is_active = is_active
                category.updated_at = datetime.now().isoformat()

                self.categories[i] = category
                self._save_categories()

                logger.info(f"Updated category: {category_id}")
                return asdict(category)
        return None
    
    def delete_category(self, category_id: str) -> bool:
        """删除分类（真删除）"""
        for i, category in enumerate(self.categories):
            if category.id == category_id:
                # 真删除：从列表中移除
                deleted_category = self.categories.pop(i)
                self._save_categories()

                logger.info(f"Deleted category: {category_id} - {deleted_category.title}")
                return True
        return False
    
    def search_categories(self, keyword: str) -> List[Dict]:
        """搜索分类"""
        keyword = keyword.lower()
        results = []
        
        for category in self.categories:
            if (keyword in category.title.lower() or keyword in category.ai_prompt.lower()):
                results.append(asdict(category))
        
        return results


# 全局实例
resource_category_manager = ResourceCategoryManager()


def main():
    """命令行接口 - 使用JSON-RPC协议"""
    import sys
    import json

    # 创建响应处理器
    rpc = create_response_handler()

    if len(sys.argv) < 2:
        rpc.error("INVALID_REQUEST", "No command specified")
        return

    command = sys.argv[1]

    try:
        if command == "get_all_categories":
            categories = resource_category_manager.get_all_categories()
            rpc.success(categories)

        elif command == "get_category_by_id":
            if len(sys.argv) < 3:
                rpc.error("INVALID_REQUEST", "Category ID required")
                return
            category_id = sys.argv[2]
            category = resource_category_manager.get_category_by_id(category_id)
            if category:
                rpc.success(category)
            else:
                rpc.error("NOT_FOUND", "Category not found")

        elif command == "create_category":
            if len(sys.argv) < 5:
                rpc.error("INVALID_REQUEST", "Title, prompt and color required")
                return
            title, ai_prompt, color = sys.argv[2], sys.argv[3], sys.argv[4]
            result = resource_category_manager.create_category(title, ai_prompt, color)
            rpc.success(result)

        elif command == "update_category":
            if len(sys.argv) < 4:
                rpc.error("INVALID_REQUEST", "Category ID and update data required")
                return
            category_id = sys.argv[2]
            update_data = json.loads(sys.argv[3])
            result = resource_category_manager.update_category(
                category_id,
                update_data.get('title'),
                update_data.get('ai_prompt'),
                update_data.get('color'),
                update_data.get('is_active')
            )
            if result:
                rpc.success(result)
            else:
                rpc.error("NOT_FOUND", "Category not found")

        elif command == "delete_category":
            if len(sys.argv) < 3:
                rpc.error("INVALID_REQUEST", "Category ID required")
                return
            category_id = sys.argv[2]
            success = resource_category_manager.delete_category(category_id)
            rpc.success(success)

        elif command == "search_categories":
            if len(sys.argv) < 3:
                rpc.error("INVALID_REQUEST", "Search keyword required")
                return
            keyword = sys.argv[2]
            results = resource_category_manager.search_categories(keyword)
            rpc.success(results)

        else:
            rpc.error("INVALID_REQUEST", f"Unknown command: {command}")

    except Exception as e:
        logger.error(f"Command execution failed: {e}")
        rpc.error("INTERNAL_ERROR", str(e))


if __name__ == "__main__":
    main()
