"""
Roneia Client - 本地 Skill 执行器（简化版）

负责:
- 执行来自云端的工具调用请求
- 处理权限验证
"""

import logging
from typing import Any, Dict, List, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from .permission_ui import PermissionManager

from roneia_core.builtin_skills import local_file, web_search, screen_capture


logger = logging.getLogger(__name__)


# Skill 名称 -> 模块映射
SKILL_MODULES = {
    "local_file": local_file,
    "web_search": web_search,
    "screen_capture": screen_capture,
}


class LocalSkillExecutor:
    """
    本地 Skill 执行器（简化版）

    直接使用内置 Skill 模块执行工具调用。
    """

    def __init__(
        self,
        permission_manager: "PermissionManager",
    ):
        """
        初始化本地 Skill 执行器

        Args:
            permission_manager: 权限管理器
        """
        self._permission_manager = permission_manager
        self._initialized = False

    async def initialize(self) -> None:
        """初始化执行器"""
        if self._initialized:
            return

        logger.info("Initializing local skill executor...")
        logger.info(f"Available skills: {list(SKILL_MODULES.keys())}")
        self._initialized = True
        logger.info("Local skill executor initialized")

    async def shutdown(self) -> None:
        """关闭执行器"""
        logger.info("Shutting down local skill executor...")
        self._initialized = False
        logger.info("Local skill executor shutdown complete")

    async def execute_tool(
        self,
        skill_name: str,
        tool_name: str,
        arguments: Dict[str, Any],
        permission: Optional[str] = None,
        purpose: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        执行工具调用

        Args:
            skill_name: Skill 名称
            tool_name: 工具名称
            arguments: 调用参数
            permission: 所需权限（由服务器指定）
            purpose: 操作目的（用于权限提示）

        Returns:
            工具执行结果
        """
        if not self._initialized:
            await self.initialize()

        # 检查 Skill 是否存在
        module = SKILL_MODULES.get(skill_name)
        if not module:
            return {
                "success": False,
                "error": f"Skill 不存在: {skill_name}",
            }

        # 检查工具是否存在
        tool_func = module.TOOLS.get(tool_name)
        if not tool_func:
            return {
                "success": False,
                "error": f"工具不存在: {skill_name}.{tool_name}",
            }

        # 如果服务器指定了权限要求，先请求权限
        if permission:
            granted = await self._permission_manager.check_and_request(
                skill_name,
                permission,
                reason=f"工具 {tool_name} 需要此权限",
                purpose=purpose or f"执行 {tool_name}",
            )
            if not granted:
                return {
                    "success": False,
                    "error": f"权限被拒绝: {permission}",
                }

        # 执行工具
        try:
            logger.info(f"Executing: {skill_name}.{tool_name}")
            result = await tool_func(**arguments)
            return result
        except Exception as e:
            logger.error(f"Tool execution error: {e}")
            return {
                "success": False,
                "error": f"执行失败: {str(e)}",
            }

    def get_loaded_skills(self) -> List[str]:
        """获取可用的 Skill 列表"""
        return list(SKILL_MODULES.keys())

    def get_skill_list(self) -> List[Dict[str, Any]]:
        """
        获取 Skill 列表（简化版，不包含工具详情）

        Returns:
            Skill 名称列表
        """
        return [{"name": name} for name in SKILL_MODULES.keys()]
