package com.cmvr.test.flow.runtime.operator.ae;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.common.utils.http.CallAPIUtil;
import com.cmvr.common.utils.uuid.IdUtils;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import com.cmvr.test.model.domain.TeAiEvaluation;
import com.cmvr.test.service.ITeAiEvaluationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
@Service
@RequiredArgsConstructor
public class AIEvaluationOperateService implements AEOperateService {

    private final TaskInstHolder taskInstHolder;
    private final ITeAiEvaluationService teAiEvaluationService;
    @Resource(name = "threadPoolTaskExecutor")
    private final ThreadPoolTaskExecutor executor;

//    private

    @Override
    public boolean supports(ActionEnum action) {
        return action.name().startsWith("AI_EVALUATION_");
    }

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum action = message.getAction();
        String instId = message.getInstId();
        JSONObject inputParams = message.getInputParams();
        List<Integer> iterations = message.getIterations();
        switch (action) {
            case AI_EVALUATION_PRE:
                String taeType = inputParams.getString("taskType");
                Integer sceneType = inputParams.getInteger("sceneType");

                // 构建评估对象（公共部分）
                TeAiEvaluation teAiEvaluation = new TeAiEvaluation();
                teAiEvaluation.setTaeId(IdUtils.fastSimpleUUID());
                teAiEvaluation.setInstId(instId);
                teAiEvaluation.setTaeType(taeType);
                teAiEvaluation.setTaeSubType(sceneType);

                // 唤醒语料
                JSONObject wakeCorpus = inputParams.getJSONObject("wakeCorpus");
                String wakeContent = wakeCorpus.getString("textContent");

                // 测试语料
                JSONArray testCorpusArray = inputParams.getJSONArray("testCorpus");

                // 统一内容构建
                String content;
                String corpusId;

                switch (sceneType) {
                    case 1:
                        // 仅唤醒
                        content = wakeContent;
                        corpusId = wakeCorpus.getString("parentId");
                        break;

                    case 2:
                        // 单次对话（一层循环）
                        int index = iterations.get(0) - 1;
                        JSONObject singleCorpus = testCorpusArray.getJSONObject(index);
                        String singleContent = singleCorpus.getString("textContent");
                        content = StrUtil.join(", ", wakeContent, singleContent);
                        corpusId = singleCorpus.getString("parentId");
                        break;

                    case 3:
                        // 连续对话（多轮）
                        int outerIdx = iterations.get(0) - 1;
                        JSONArray continuousCorpus = testCorpusArray.getJSONArray(outerIdx);

                        StringJoiner joiner = new StringJoiner(",");
                        joiner.add(wakeContent);

                        for (int j = 0; j < continuousCorpus.size(); j++) {
                            JSONObject obj = continuousCorpus.getJSONObject(j);
                            joiner.add(obj.getString("textContent"));
                        }
                        content = joiner.toString();
                        JSONObject obj = continuousCorpus.getJSONObject(0);
                        corpusId = obj.getString("parentId");
                        break;

                    default:
                        throw new IllegalArgumentException("不支持的 sceneType: " + sceneType);
                }

                // 设置内容并统一返回
                teAiEvaluation.setContent(content);
                teAiEvaluation.setCorpusId(corpusId);
                return TaskNodeExecuteResult.success(
                        JSONObject.of("teAiEvaluation", teAiEvaluation)
                );

            case AI_EVALUATION_EXECUTE:
                FlowNodeWrapper pre = message.getGraph()
                        .getNodeMap()
                        .values()
                        .stream()
                        .filter(node -> ActionEnum.AI_EVALUATION_PRE.equals(node.getAction()))
                        .findFirst()
                        .orElseThrow(() -> new IllegalStateException("未找到AI评估预处理节点"));
                JSONObject preParams = taskInstHolder.getNodeOutParams(instId, pre.getNodeId(), iterations);
                JSONObject aiEvaluation = preParams.getJSONObject("teAiEvaluation");
                TeAiEvaluation teaExecute = aiEvaluation.to(TeAiEvaluation.class);

                // 获取视频地址
                JSONArray videoUrls = inputParams.getJSONArray("videoUrl");
                String videoUrl = CollUtil.getLast(videoUrls).toString();
                teaExecute.setVideoPath(videoUrl);
                teaExecute.setStatus(0);
                teaExecute.setStartTime(System.currentTimeMillis());
                teAiEvaluationService.insert(teaExecute);
                // 执行ai评估
                executor.submit(() -> {
                    CallAPIUtil.doPostJson(
                            "http://192.168.0.140:8000/analyze",
                            null,
                            teaExecute);
                });
                return TaskNodeExecuteResult.success();
            default:
                throw new GlobalException("不支持的action:" + action.name());
        }
    }
}
