"""资源管理器 - 统一管理 AskTable 资源的 CRUD 操作"""

from typing import Optional, Callable, Any
from asktable import Asktable

from .utils import console, get_logger

logger = get_logger(__name__)


class ResourceManager:
    """统一管理 Datasource/Bot/Chat 资源的创建和清理"""

    def __init__(self, client: Asktable):
        self.client = client

    def cleanup_existing(
        self,
        resource_type: str,
        name: str,
        list_fn: Callable[[], list],
        delete_fn: Callable[[str], None]
    ) -> None:
        """通用资源清理逻辑

        Args:
            resource_type: 资源类型名称（用于日志）
            name: 资源名称
            list_fn: 列出资源的函数
            delete_fn: 删除资源的函数（接收资源 ID）
        """
        console.print(f"  [cyan]检查同名{resource_type}...[/cyan]")

        try:
            existing = list_fn()
            for item in existing:
                if item.name == name:
                    console.print(f"  [yellow]⚠[/yellow] 发现同名{resource_type}: [dim]{item.id}[/dim]")
                    console.print(f"  [cyan]删除旧{resource_type}...[/cyan]")
                    delete_fn(item.id)
                    console.print(f"  [green]✓[/green] 已删除旧{resource_type}")
                    logger.info(f"Deleted existing {resource_type}: {item.id}")
        except Exception as e:
            logger.warning(f"Failed to cleanup {resource_type}: {e}")

    def cleanup_datasource(self, name: str) -> None:
        """清理同名数据源"""
        self.cleanup_existing(
            "数据源",
            name,
            lambda: self.client.datasources.list(),
            lambda id: self.client.datasources.delete(datasource_id=id)
        )

    def cleanup_bot(self, name: str) -> None:
        """清理同名机器人"""
        self.cleanup_existing(
            "机器人",
            name,
            lambda: self.client.bots.list(),
            lambda id: self.client.bots.delete(bot_id=id)
        )

    def cleanup_chat(self, name: str) -> None:
        """清理同名对话"""
        self.cleanup_existing(
            "对话",
            name,
            lambda: self.client.chats.list(),
            lambda id: self.client.chats.delete(chat_id=id)
        )
