from __future__ import annotations

from pathlib import Path
from typing import Any

import yaml

_PROMPTS_DIR = Path(__file__).resolve().parent / "prompts"
_cache: dict[str, dict[str, Any]] = {}


def load_prompt(name: str) -> dict[str, Any]:
    """读取 prompts/{name}.yaml，缓存于进程内。"""
    if name in _cache:
        return _cache[name]
    path = _PROMPTS_DIR / f"{name}.yaml"
    if not path.is_file():
        _cache[name] = {}
        return _cache[name]
    with path.open(encoding="utf-8") as f:
        data = yaml.safe_load(f) or {}
    _cache[name] = data
    return data


def render_prompt(name: str, **kwargs: Any) -> str:
    """渲染 prompt 模板中的 {placeholder}。"""
    tpl = load_prompt(name)
    template = str(tpl.get("template") or tpl.get("system") or "")
    try:
        return template.format(**kwargs)
    except KeyError:
        return template
