# 中文注释：
# 文件：echobot/agent/tools/dir_manager.py
# 说明：运行时目录管理工具，用于动态添加/删除允许执行的目录。

"""Runtime Directory Manager Tool.

此工具允许 echobot 在运行时动态添加或删除允许 exec 工具操作的目录。
"""

from typing import Any

from echobot.agent.tools.base import Tool
from echobot.agent.tools.shell import (
    add_runtime_allowed_dir,
    get_runtime_allowed_dirs,
    remove_runtime_allowed_dir,
)


class DirManagerTool(Tool):
    """
    运行时目录管理工具

    允许在运行时动态添加或删除允许 exec 工具操作的目录。

    工具元数据：
    - 名称：manage_allowed_dirs
    - 描述：Add or remove directories from the allowed exec list at runtime.

    使用示例：
        await registry.execute("manage_allowed_dirs", {
            "action": "add",
            "path": "/home/user/myproject"
        })
    """

    name = "manage_allowed_dirs"
    description = "Add or remove directories from the allowed exec list at runtime."
    parameters = {
        "type": "object",
        "properties": {
            "action": {
                "type": "string",
                "description": "Action to perform: 'add', 'remove', or 'list'",
                "enum": ["add", "remove", "list"]
            },
            "path": {
                "type": "string",
                "description": "Directory path to add or remove (required for add/remove actions)"
            }
        },
        "required": ["action"]
    }

    async def execute(self, action: str, path: str | None = None, **kwargs: Any) -> str:
        """
        执行目录管理操作

        Args:
            action: 操作类型：add, remove, list
            path: 目录路径（add/remove 需要）

        Returns:
            str: 操作结果
        """
        if action == "list":
            dirs = get_runtime_allowed_dirs()
            if not dirs:
                return "当前没有额外配置的运行时目录。默认可在 home 目录下操作。"
            return "当前允许的目录列表：\n" + "\n".join(f"- {d}" for d in dirs)

        if action == "add":
            if not path:
                return "Error: path is required for add action"
            add_runtime_allowed_dir(path)
            dirs = get_runtime_allowed_dirs()
            return f"已添加目录: {path}\n当前允许的目录：\n" + "\n".join(f"- {d}" for d in dirs)

        if action == "remove":
            if not path:
                return "Error: path is required for remove action"
            ok = remove_runtime_allowed_dir(path)
            if not ok:
                return f"目录不在允许列表中: {path}"
            dirs = get_runtime_allowed_dirs()
            return f"已移除目录: {path}\n当前允许的目录：\n" + "\n".join(f"- {d}" for d in dirs)

        return f"Unknown action: {action}. Use 'add', 'remove', or 'list'."
