"""实现层 - YAML提示词加载器"""
import yaml
import os
from pathlib import Path
from typing import Dict, Any
from jinja2 import Template
from ...interfaces.prompt_loader import PromptLoader


class YamlPromptLoader(PromptLoader):
    """YAML提示词加载器"""

    def __init__(self, prompts_dir: str = "config/prompts"):
        """
        初始化加载器

        Args:
            prompts_dir: 提示词目录路径
        """
        self.prompts_dir = Path(prompts_dir)
        self._prompt_cache: Dict[str, Dict[str, str]] = {}

    def load_prompt(self, prompt_name: str) -> Dict[str, str]:
        """
        加载提示词

        Args:
            prompt_name: 提示词名称（对应YAML文件名，不含扩展名）

        Returns:
            包含 system 和 user_template 的字典
        """
        # 检查缓存
        if prompt_name in self._prompt_cache:
            return self._prompt_cache[prompt_name]

        # 构建文件路径
        prompt_file = self.prompts_dir / f"{prompt_name}.yaml"

        if not prompt_file.exists():
            raise FileNotFoundError(f"提示词文件不存在: {prompt_file}")

        # 加载YAML文件
        with open(prompt_file, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)

        # 解析提示词
        result = {
            "name": data.get("name", prompt_name),
            "description": data.get("description", ""),
            "system": data.get("system", ""),
            "user_template": data.get("user_template", ""),
            "output_parser": data.get("output_parser", {})
        }

        # 缓存结果
        self._prompt_cache[prompt_name] = result

        return result

    def render_template(
        self,
        template: str,
        variables: Dict[str, Any]
    ) -> str:
        """
        渲染提示词模板

        Args:
            template: 模板字符串，支持 {{ variable }} 语法
            variables: 变量字典

        Returns:
            渲染后的字符串
        """
        jinja_template = Template(template)
        return jinja_template.render(**variables)

    def load_chain_config(self, config_path: str) -> Dict[str, Any]:
        """
        加载提示链配置

        Args:
            config_path: 配置文件路径

        Returns:
            提示链配置
        """
        config_file = Path(config_path)

        if not config_file.exists():
            raise FileNotFoundError(f"提示链配置文件不存在: {config_file}")

        with open(config_file, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)

        return {
            "chain_name": data.get("chain_name", ""),
            "description": data.get("description", ""),
            "steps": data.get("steps", [])
        }

    def clear_cache(self):
        """清除缓存"""
        self._prompt_cache.clear()
