"""Expert template routes - 列出可用的专家模板（用于私董会 @board 模式）"""

from fastapi import APIRouter, HTTPException, Request

from agentkit.experts.registry import ExpertTemplateRegistry

router = APIRouter(tags=["experts"])

# 团队模板（非单个专家），不在专家选择列表中展示
_TEAM_TEMPLATES = frozenset({"private_board", "dev_team"})


def _get_template_registry(request: Request) -> ExpertTemplateRegistry:
    registry = getattr(request.app.state, "expert_template_registry", None)
    if registry is None:
        return ExpertTemplateRegistry()
    return registry


def _serialize_expert(template) -> dict:
    """序列化 ExpertTemplate 为前端可用的精简字典。

    只暴露私董会 UI 需要的字段，避免泄露完整 prompt/llm 配置。
    """
    config = template.config
    return {
        "name": template.name,
        "description": template.description,
        "is_builtin": template.is_builtin,
        "avatar": config.avatar,
        "color": config.color,
        "persona": config.persona,
        "thinking_style": config.thinking_style,
        "speaking_style": config.speaking_style,
        "decision_framework": config.decision_framework,
    }


@router.get("/experts")
async def list_experts(req: Request):
    """列出所有可用的专家模板（排除团队模板）。

    返回的专家可用于私董会 @board 模式的专家选择。
    """
    registry = _get_template_registry(req)
    experts = [_serialize_expert(t) for t in registry.list() if t.name not in _TEAM_TEMPLATES]
    return {"experts": experts, "total": len(experts)}


@router.get("/experts/{name}")
async def get_expert(name: str, req: Request):
    """获取单个专家模板详情。"""
    registry = _get_template_registry(req)
    template = registry.get(name)
    if template is None or name in _TEAM_TEMPLATES:
        raise HTTPException(status_code=404, detail=f"Expert '{name}' not found")
    return _serialize_expert(template)
