"""ExpertTemplateRegistry - Expert 模板注册中心"""

from __future__ import annotations

import logging
import os

import yaml

from agentkit.core.exceptions import ConfigValidationError
from agentkit.experts.config import ExpertTemplate

logger = logging.getLogger(__name__)


class ExpertTemplateRegistry:
    """Expert 模板注册中心，管理 ExpertTemplate 的注册、发现与加载

    支持：
    - 注册/获取模板
    - 按名称或描述搜索模板（大小写不敏感）
    - 从 YAML 文件或目录批量加载模板
    """

    def __init__(self) -> None:
        self._templates: dict[str, ExpertTemplate] = {}

    def register(self, template: ExpertTemplate) -> None:
        """注册模板，同名覆盖

        Args:
            template: ExpertTemplate 实例
        """
        self._templates[template.name] = template
        logger.info(f"ExpertTemplate '{template.name}' registered")

    def get(self, name: str) -> ExpertTemplate | None:
        """按名称获取模板

        Args:
            name: 模板名称

        Returns:
            ExpertTemplate 实例，不存在时返回 None
        """
        return self._templates.get(name)

    def list(self) -> list[ExpertTemplate]:
        """列出所有已注册模板"""
        return list(self._templates.values())

    def search(self, query: str) -> list[ExpertTemplate]:
        """按名称或描述搜索模板（大小写不敏感子串匹配）

        Args:
            query: 搜索关键词

        Returns:
            匹配的 ExpertTemplate 列表
        """
        query_lower = query.lower()
        results: list[ExpertTemplate] = []
        for template in self._templates.values():
            if query_lower in template.name.lower() or query_lower in template.description.lower():
                results.append(template)
        return results

    def load_from_yaml(self, path: str) -> ExpertTemplate:
        """从单个 YAML 文件加载 ExpertTemplate

        YAML 格式::

            name: analyst
            description: "数据分析师"
            is_builtin: false
            config:
              name: analyst
              agent_type: analyst
              persona: "善于数据分析的专家"
              thinking_style: "逻辑推理"
              collaboration_strategy: "cooperative"
              bound_skills:
                - data_query
                - chart_gen
              avatar: "📊"
              color: "#52c41a"
              is_lead: false

        Args:
            path: YAML 文件路径

        Returns:
            加载的 ExpertTemplate 实例

        Raises:
            ConfigValidationError: YAML 格式不合法
        """
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
        if not isinstance(data, dict):
            raise ConfigValidationError(
                agent_name="unknown",
                key="config",
                reason=f"YAML config must be a mapping, got {type(data)}",
            )
        template = ExpertTemplate.from_dict(data)
        self.register(template)
        return template

    def load_from_directory(self, path: str) -> list[ExpertTemplate]:
        """从目录批量加载 ExpertTemplate YAML 文件

        扫描目录下所有 .yaml / .yml 文件并加载为 ExpertTemplate。

        Args:
            path: 目录路径

        Returns:
            加载的 ExpertTemplate 列表
        """
        loaded: list[ExpertTemplate] = []
        if not os.path.isdir(path):
            logger.warning(f"Directory '{path}' does not exist, skipping")
            return loaded

        for filename in sorted(os.listdir(path)):
            if filename.endswith((".yaml", ".yml")):
                filepath = os.path.join(path, filename)
                try:
                    template = self.load_from_yaml(filepath)
                    loaded.append(template)
                except Exception as e:
                    logger.warning(f"Failed to load ExpertTemplate from '{filepath}': {e}")
        return loaded
