from __future__ import annotations

from niannian.skills.context import SkillInjectContext, skill_matches_context
from niannian.skills.loader import SkillLoader


def inject_skills(
    loader: SkillLoader,
    trigger: str,
    *,
    max_chars: int = 4000,
    names: list[str] | None = None,
    context: SkillInjectContext | None = None,
) -> str:
    """按 trigger 拼接 Skill 正文，供 Chat/ingest prompt 注入。"""
    parts: list[str] = []
    total = 0
    skills = loader.list_skills()
    if names:
        skills = [s for s in skills if s.name in names]
    for skill in skills:
        if not skill.enabled:
            continue
        if not skill_matches_context(skill, context):
            continue
        if trigger not in skill.triggers and trigger != "all":
            continue
        block = f"## Skill: {skill.name}\n{skill.body}"
        if total + len(block) > max_chars:
            break
        parts.append(block)
        total += len(block)
    return "\n\n".join(parts)
