"""Built-in prompt-skills（能力插件）— 首启自动播种到 skill 注册表。

与 builtin_packs 同构：源在 ``agentexample/skills/<id>/skill.yml``（相对仓库根，
也接受运行 cwd 下同名目录）。每个 id 已注册则跳过；逐个失败被捕获不影响其余；
也不让启动钩子崩溃。

这样「作业批改」等能力插件能随产品分发、开箱即用，而不必让用户在「工具与连接」
页手动逐条创建。
"""
from __future__ import annotations

import os
from pathlib import Path

from agentpaas.observability.logging import logger

# 内置能力插件 ID 列表（对应 agentexample/skills/<id>/skill.yml）
BUILTIN_SKILL_IDS: list[str] = [
    "assignment-grader",
]


def _find_skills_src() -> Path | None:
    """从本文件向上找 ``agentexample/skills/``（同 builtin_packs 的解析方式）。"""
    here = Path(__file__).resolve().parent
    for _ in range(8):
        candidate = here / "agentexample" / "skills"
        if candidate.is_dir():
            return candidate
        here = here.parent
    cwd_candidate = Path(os.getcwd()) / "agentexample" / "skills"
    if cwd_candidate.is_dir():
        return cwd_candidate
    return None


def ensure_builtin_skills_installed() -> None:
    """把未注册的内置能力插件写进 skill 注册表。每次启动调用都安全（幂等）。"""
    from agentpaas.engine import skill_registry

    src = _find_skills_src()
    if not src:
        logger.debug(
            "ensure_builtin_skills_installed: agentexample/skills/ not found "
            "(running outside repo is normal); skipping"
        )
        return

    import yaml

    for skill_id in BUILTIN_SKILL_IDS:
        try:
            if skill_registry.get_skill(skill_id):
                logger.debug(f"builtin skill already installed: {skill_id}")
                continue

            yml = src / skill_id / "skill.yml"
            if not yml.is_file():
                logger.debug(f"builtin skill source not found: {yml}; skipping")
                continue

            with open(yml, encoding="utf-8") as f:
                spec = yaml.safe_load(f) or {}
            spec.setdefault("name", skill_id)

            skill_registry.upsert_skill(spec)
            logger.info(f"auto-installed builtin skill: {skill_id}")
        except Exception as e:  # pragma: no cover (per-skill best-effort)
            logger.warning(f"builtin skill install failed for {skill_id}: {e}")
