"""
测试数据管理工具（简化版）
"""

import asyncio
from typing import List, Dict, Any, Callable
from httpx import AsyncClient
from loguru import logger


class TestDataManager:
    """测试数据管理器"""
    
    def __init__(self, client: AsyncClient):
        self.client = client
        self._users: List[int] = []
        self._roles: List[int] = []
        self._menus: List[int] = []
        self._dictionaries: List[int] = []
        self._dict_types: List[int] = []
        self._configs: List[int] = []
        self._notices: List[int] = []
        self._files: List[int] = []
        self._messages: List[int] = []
    
    def add_user(self, user_id: int):
        """添加用户到清理列表"""
        self._users.append(user_id)
    
    def add_role(self, role_id: int):
        """添加角色到清理列表"""
        self._roles.append(role_id)
    
    def add_menu(self, menu_id: int):
        """添加菜单到清理列表"""
        self._menus.append(menu_id)
    
    def add_dictionary(self, dict_id: int):
        """添加字典到清理列表"""
        self._dictionaries.append(dict_id)
    
    def add_dict_type(self, dict_type_id: int):
        """添加字典类型到清理列表"""
        self._dict_types.append(dict_type_id)
    
    def add_config(self, config_id: int):
        """添加系统配置到清理列表"""
        self._configs.append(config_id)
    
    def add_notice(self, notice_id: int):
        """添加系统公告到清理列表"""
        self._notices.append(notice_id)
    
    def add_file(self, file_id: int):
        """添加文件到清理列表"""
        self._files.append(file_id)
    
    def add_message(self, message_id: int):
        """添加消息到清理列表"""
        self._messages.append(message_id)
    
    async def cleanup_all(self):
        """清理所有测试数据"""
        logger.info("Starting test data cleanup...")
        
        cleanup_tasks = []
        
        if self._messages:
            cleanup_tasks.extend([self._delete_message(msg_id) for msg_id in self._messages])
            self._messages.clear()
        
        if self._files:
            cleanup_tasks.extend([self._delete_file(file_id) for file_id in self._files])
            self._files.clear()
        
        if self._notices:
            cleanup_tasks.extend([self._delete_notice(notice_id) for notice_id in self._notices])
            self._notices.clear()
        
        if self._configs:
            cleanup_tasks.extend([self._delete_config(config_id) for config_id in self._configs])
            self._configs.clear()
        
        if self._dictionaries:
            cleanup_tasks.extend([self._delete_dictionary(dict_id) for dict_id in self._dictionaries])
            self._dictionaries.clear()
        
        if self._dict_types:
            cleanup_tasks.extend([self._delete_dict_type(dict_type_id) for dict_type_id in self._dict_types])
            self._dict_types.clear()
        
        if self._users:
            cleanup_tasks.extend([self._delete_user(user_id) for user_id in self._users])
            self._users.clear()
        
        if self._roles:
            cleanup_tasks.extend([self._delete_role(role_id) for role_id in self._roles])
            self._roles.clear()
        
        if self._menus:
            cleanup_tasks.extend([self._delete_menu(menu_id) for menu_id in self._menus])
            self._menus.clear()
        
        if cleanup_tasks:
            results = await asyncio.gather(*cleanup_tasks, return_exceptions=True)
            failed_count = sum(1 for r in results if isinstance(r, Exception))
            if failed_count > 0:
                logger.warning(f"Failed to cleanup {failed_count} resources")
        
        logger.info("Test data cleanup completed")
    
    async def _delete_user(self, user_id: int):
        """删除用户"""
        try:
            await self.client.delete(f"/api/users/{user_id}")
            logger.info(f"Cleaned up user {user_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup user {user_id}: {e}")
    
    async def _delete_role(self, role_id: int):
        """删除角色"""
        try:
            await self.client.delete(f"/api/roles/{role_id}")
            logger.info(f"Cleaned up role {role_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup role {role_id}: {e}")
    
    async def _delete_menu(self, menu_id: int):
        """删除菜单"""
        try:
            await self.client.delete(f"/api/menus/{menu_id}")
            logger.info(f"Cleaned up menu {menu_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup menu {menu_id}: {e}")
    
    async def _delete_dictionary(self, dict_id: int):
        """删除字典"""
        try:
            await self.client.delete(f"/api/dictionaries/{dict_id}")
            logger.info(f"Cleaned up dictionary {dict_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup dictionary {dict_id}: {e}")
    
    async def _delete_dict_type(self, dict_type_id: int):
        """删除字典类型"""
        try:
            await self.client.delete(f"/api/dict/types/{dict_type_id}")
            logger.info(f"Cleaned up dict type {dict_type_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup dict type {dict_type_id}: {e}")
    
    async def _delete_config(self, config_id: int):
        """删除系统配置"""
        try:
            await self.client.delete(f"/api/config/{config_id}")
            logger.info(f"Cleaned up config {config_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup config {config_id}: {e}")
    
    async def _delete_notice(self, notice_id: int):
        """删除系统公告"""
        try:
            await self.client.delete(f"/api/notices/{notice_id}")
            logger.info(f"Cleaned up notice {notice_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup notice {notice_id}: {e}")
    
    async def _delete_file(self, file_id: int):
        """删除文件"""
        try:
            await self.client.delete(f"/api/files/{file_id}")
            logger.info(f"Cleaned up file {file_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup file {file_id}: {e}")
    
    async def _delete_message(self, message_id: int):
        """删除消息"""
        try:
            await self.client.delete(f"/api/messages/{message_id}")
            logger.info(f"Cleaned up message {message_id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup message {message_id}: {e}")
    
    def get_stats(self) -> Dict[str, int]:
        """获取统计信息"""
        return {
            "users": len(self._users),
            "roles": len(self._roles),
            "menus": len(self._menus),
            "dictionaries": len(self._dictionaries),
            "dict_types": len(self._dict_types),
            "configs": len(self._configs),
            "notices": len(self._notices),
            "files": len(self._files),
            "messages": len(self._messages)
        }
    
    def has_data(self) -> bool:
        """检查是否有待清理数据"""
        return any([
            self._users, self._roles, self._menus,
            self._dictionaries, self._dict_types, self._configs,
            self._notices, self._files, self._messages
        ])