# -*- coding: utf-8 -*-
"""LangChain 集成：将 Skills 转为 load_skill Tool，支持渐进式披露。"""

from typing import TYPE_CHECKING

from langchain_core.tools import tool

from .loader import SkillsLoader

if TYPE_CHECKING:
    from langchain_core.tools import BaseTool


def create_load_skill_tool(loader: SkillsLoader) -> "BaseTool":
    """
    创建一个 `load_skill` Tool，供 LangChain agent 使用。

    渐进式披露流程：
    1. Agent 启动时只看到 Tool 的 description（列出可用 skills 的 name + description）
    2. Agent 根据用户意图决定是否调用 load_skill(skill_name=...)
    3. 只有调用时才加载该 skill 的完整内容，注入到上下文中

    Returns:
        LangChain BaseTool，调用时传入 skill_name 返回完整 SKILL.md 内容
    """
    summaries = loader.get_skill_summaries()
    skills_list = "\n".join(
        f"- {s['name']}: {s['description'][:80]}{'...' if len(s['description']) > 80 else ''}"
        for s in summaries
    )
    description = f"""Load a specialized skill by name. Call this when the user's request matches one of the available skills.
Returns the skill's full instructions and context. Use the returned content to guide your response.

Available skills:
{skills_list}
"""

    @tool(description=description)
    def load_skill(skill_name: str) -> str:
        """Load a skill by name and return its full content."""
        content = loader.load_skill_content(skill_name)
        if content is None:
            return f"Skill '{skill_name}' not found. Available: {', '.join(loader.list_skill_names())}"
        return content

    return load_skill


def to_langchain_tools(loader: SkillsLoader):
    """
    将 skills 转为 LangChain Tools 列表。

    默认返回 [load_skill] Tool，实现渐进式披露。
    若需要直接可执行的 tools（例如 skill 绑定脚本），可在此扩展。
    """
    return [create_load_skill_tool(loader)]
