"""工具组管理 — 管理需要配合使用的工具集合"""

from __future__ import annotations

import json
import logging
from pathlib import Path

from pydantic import BaseModel, Field

from tool_agent.config import settings
from tool_agent.models import BackendRuntime

logger = logging.getLogger(__name__)


class ToolGroup(BaseModel):
    """工具组 — 需要配合使用的工具集合"""
    group_id: str = Field(..., description="工具组 ID")
    name: str = Field(..., description="工具组名称")
    description: str = Field(..., description="工具组描述")
    category: BackendRuntime = Field(..., description="后端执行环境")
    tool_ids: list[str] = Field(default_factory=list, description="组内工具 ID 列表")
    usage_order: list[str] | None = Field(None, description="推荐使用顺序")
    usage_example: str | None = Field(None, description="使用示例")


class ToolGroupManager:
    """工具组管理器"""

    def __init__(self) -> None:
        self._path = settings.data_dir / "groups.json"
        self._groups: dict[str, ToolGroup] = {}
        self._load()

    def _load(self) -> None:
        """加载工具组配置"""
        if self._path.exists():
            try:
                data = json.loads(self._path.read_text(encoding="utf-8"))
                for item in data.get("groups", []):
                    group = ToolGroup(**item)
                    self._groups[group.group_id] = group
                logger.info(f"Loaded {len(self._groups)} tool groups")
            except Exception as e:
                logger.error(f"Failed to load groups: {e}")

    def get_group(self, group_id: str) -> ToolGroup | None:
        """获取指定工具组"""
        return self._groups.get(group_id)

    def list_all(self) -> list[ToolGroup]:
        """列出所有工具组"""
        return list(self._groups.values())

    def list_by_category(self, category: BackendRuntime) -> list[ToolGroup]:
        """按分类列出工具组"""
        return [g for g in self._groups.values() if g.category == category]

    def find_groups_for_tool(self, tool_id: str) -> list[ToolGroup]:
        """查找包含指定工具的所有工具组"""
        return [g for g in self._groups.values() if tool_id in g.tool_ids]
