package com.seer.teach.teacher.service.prompt.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.common.enums.MessageEnums;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.teacher.common.llm.sse.req.Message;
import com.seer.teach.teacher.common.llm.sse.req.Text;
import com.seer.teach.teacher.module.entity.PromptFunctionVariablesEntity;
import com.seer.teach.teacher.module.entity.PromptFunctionsEntity;
import com.seer.teach.teacher.module.entity.PromptRolesEntity;
import com.seer.teach.teacher.module.entity.PromptVariablesEntity;
import com.seer.teach.teacher.service.prompt.PromptsService;
import com.seer.teach.teacher.resolver.PromptVariableResolverRegistry;
import com.seer.teach.teacher.resolver.PromptVariableResolver;
import com.seer.teach.teacher.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * <p>
 *
 * </p >
 *
 * @author Captain
 * @since 2025-10-28 14:34
 */
@Slf4j
public abstract class BasePromptService implements PromptsService {

    @Autowired
    protected PromptFunctionsService promptFunctionsService;

    @Autowired
    protected PromptRolesService roleService;

    @Autowired
    protected PromptVariablesService promptVariablesService;

    @Autowired
    protected PromptFunctionVariablesService promptFunctionVariablesService;

    @Autowired
    protected PromptVariableResolverRegistry promptVariableResolverRegistry;

    @Override
    public Map<String, List<Text>> generatePromptMessages() {
        // 1. 读取 Function Prompt（最新版本）
        PromptFunctionsEntity function = promptFunctionsService.getOne(
                new LambdaQueryWrapper<PromptFunctionsEntity>()
                        .eq(PromptFunctionsEntity::getModule, getModule())
                        .eq(PromptFunctionsEntity::getName, getFunctionName())
                        .orderByDesc(PromptFunctionsEntity::getVersion)
                        .last("LIMIT 1")
        );
        // 2. 读取 Role Prompt（最新版本）
        PromptRolesEntity role = roleService.getOne(
                new LambdaQueryWrapper<PromptRolesEntity>()
                        .eq(PromptRolesEntity::getId, getRoleId())
                        .orderByDesc(PromptRolesEntity::getVersion)
                        .last("LIMIT 1")
        );
        // 3. 先取出原始内容，变量填充后再覆盖
        String roleContent = role.getContent();
        String functionContent = function.getContent();

        // 4. 查询 Function 绑定的所有变量
        List<PromptFunctionVariablesEntity> functionVariables =
                promptFunctionVariablesService.list(
                        new LambdaQueryWrapper<PromptFunctionVariablesEntity>()
                                .eq(PromptFunctionVariablesEntity::getFunctionId, function.getId())
                );
        if (!functionVariables.isEmpty()) {
            // 5. 将变量配置（Key/Default-value）映射出来
            Map<Integer, PromptVariablesEntity> variableMap =
                    promptVariablesService.listByIds(
                            functionVariables.stream()
                                    .map(PromptFunctionVariablesEntity::getVariableId)
                                    .collect(Collectors.toList())
                    ).stream().collect(Collectors.toMap(PromptVariablesEntity::getId, e -> e));

            // 6. 遍历变量，填充 roleContent 和 functionContent
            for (PromptFunctionVariablesEntity fv : functionVariables) {
                PromptVariablesEntity var = variableMap.get(fv.getVariableId());
                String key = var.getKey();
                // 变量解析器
                PromptVariableResolver resolver = promptVariableResolverRegistry.get(key);
                if (resolver == null) {
                    log.error("变量解析器不存在: {}", key);
                    throw new CommonException(ResultCodeEnum.VAR_REPLACEMENT_ERROR);
                }
                // 解析变量值
                String value;
                try {
                    value = resolver.resolve();
                } catch (Exception e) {
                    log.error("变量解析异常 key={}，回滚默认值", key, e);
                    value = var.getDefaultValue();
                }
                // 7. 同时替换 role + function 内容
                String placeholder = "{{" + key + "}}";
                roleContent = roleContent.replace(placeholder, value);
                functionContent = functionContent.replace(placeholder, value);
            }
        }
        // 8. 构建最终消息，注意都是“已替换变量后的内容”
        Map<String, List<Text>> messages = new HashMap<>();
        messages.put(MessageEnums.SYSTEM.getMessage(), Text.text(roleContent));
        messages.put(MessageEnums.USER.getMessage(), Text.text(functionContent));
        return messages;
    }


}
