"""编排层 - 提示链处理流程编排"""
import json
import logging
from typing import Dict, Any
from ..interfaces.llm_client import LLMClient
from ..interfaces.prompt_loader import PromptLoader
from ..interfaces.chain_executor import ChainExecutor


logger = logging.getLogger(__name__)


class PromptChainProcessor:
    """提示链处理流程编排类"""

    def __init__(
        self,
        llm_client: LLMClient,
        prompt_loader: PromptLoader,
        chain_executor: ChainExecutor
    ):
        """
        初始化处理器

        Args:
            llm_client: 大模型API客户端
            prompt_loader: 提示词加载器
            chain_executor: 提示链执行器
        """
        self.llm_client = llm_client
        self.prompt_loader = prompt_loader
        self.chain_executor = chain_executor

    async def process(
        self,
        chain_config_path: str,
        input_data: Dict[str, Any],
        temperature: float = None,
        max_tokens: int = None
    ) -> Dict[str, Any]:
        """
        执行完整的提示链处理流程

        Args:
            chain_config_path: 提示链配置文件路径
            input_data: 输入数据
            temperature: 温度参数（可选，覆盖默认值）
            max_tokens: 最大token数（可选，覆盖默认值）

        Returns:
            处理结果
        """
        logger.info(f"开始处理提示链: {chain_config_path}")

        # 加载提示链配置
        chain_config = self.prompt_loader.load_chain_config(chain_config_path)
        logger.info(f"提示链名称: {chain_config['chain_name']}")
        logger.info(f"步骤数量: {len(chain_config['steps'])}")

        # 如果指定了温度参数，更新执行器配置
        if temperature is not None:
            self.chain_executor.default_temperature = temperature
        if max_tokens is not None:
            self.chain_executor.default_max_tokens = max_tokens

        # 执行提示链
        result = await self.chain_executor.execute_chain(
            chain_config["steps"],
            input_data
        )

        logger.info(f"提示链处理完成，共执行 {len(result['steps'])} 个步骤")

        return result

    def get_model_info(self) -> Dict[str, str]:
        """
        获取当前模型信息

        Returns:
            模型信息字典
        """
        return {
            "model_id": self.llm_client.get_model_id(),
            "server_url": self.llm_client.get_server_url()
        }
