"""Multi-Agent 配置模型"""

from typing import List, Optional

from pydantic import BaseModel, Field


class SubAgentConfig(BaseModel):
    """子 Agent 配置"""

    name: str = Field(..., description="唯一标识符")
    description: str = Field(..., description="描述，用于主 Agent 选择")
    system_prompt: Optional[str] = Field(default=None, description="内联系统提示词")
    system_prompt_file: Optional[str] = Field(default=None, description="外部文件路径")
    memory_enabled: bool = Field(default=True, description="是否启用独立记忆")
    max_iterations: int = Field(default=10, description="最大迭代次数")


def load_agents_from_yaml(config_path: str) -> List[SubAgentConfig]:
    """从 YAML 文件加载子 Agent 配置

    Args:
        config_path: YAML 配置文件路径

    Returns:
        子 Agent 配置列表
    """
    import os
    import yaml

    # 获取配置文件的目录，用于解析相对路径
    config_dir = os.path.dirname(os.path.abspath(config_path))

    with open(config_path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f)

    agents = []
    for agent_data in data.get("agents", []):
        # 处理外部文件引用
        if agent_data.get("system_prompt_file"):
            file_path = agent_data["system_prompt_file"]
            # 如果是相对路径，基于配置文件目录解析
            if not os.path.isabs(file_path):
                file_path = os.path.join(config_dir, file_path)

            try:
                with open(file_path, "r", encoding="utf-8") as pf:
                    agent_data["system_prompt"] = pf.read()
            except FileNotFoundError:
                raise FileNotFoundError(f"Prompt file not found: {file_path}")
            del agent_data["system_prompt_file"]

        agents.append(SubAgentConfig(**agent_data))

    return agents
