package com.cmvr.test.flow.runtime.operator.edge.vi;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
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.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import com.cmvr.test.flow.runtime.operator.edge.EdgeOperateService;
import com.cmvr.test.service.ex.ExViCorpusService;
import com.cmvr.test.service.ex.ExViSchemeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class ViSchemeOperateService implements EdgeOperateService {

    private final ExViSchemeService exViSchemeService;
    private final ExViCorpusService exViCorpusService;

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

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        String schemeId = inputParams.getString("schemeId");

        JSONObject scheme = exViSchemeService.queryById(schemeId);
        if (ObjUtil.isEmpty(scheme)) {
            throw new GlobalException(StrUtil.format("id为 [{}] 的方案为空", schemeId));
        }
        int sceneType = scheme.getIntValue("sceneType");
        String wakeId = scheme.getString("wakeId");
        JSONObject wakeCorpus = exViCorpusService.queryById(wakeId);
        if (ObjUtil.isEmpty(wakeCorpus)) {
            throw new GlobalException(StrUtil.format("id为 [{}] 的唤醒语料为空", wakeId));
        }

        JSONObject output = new JSONObject();
        output.put("wakeCorpus", wakeCorpus);
        output.put("sceneType", sceneType);
        switch (sceneType) {
            case 1:
                break;
            case 2:
                JSONArray singleCorpus = getTestCorpus(scheme, schemeId);
                output.put("testCorpus", singleCorpus);
                break;
            case 3:
                JSONArray continuousCorpus = getTestCorpus(scheme, schemeId);
                // 转成 List<JSONObject>
                List<JSONObject> list = continuousCorpus.stream()
                        .map(o -> (JSONObject) o)
                        .collect(Collectors.toList());

                // 按 parentId 分组（保留整个 JSONObject）
                Map<String, List<JSONObject>> grouped = list.stream()
                        .collect(Collectors.groupingBy(
                                obj -> obj.getString("parentId")
                        ));

                // 转成 List<List<JSONObject>> 并排序
                List<List<JSONObject>> continuousCorpusGroup = new ArrayList<>(grouped.values());
                continuousCorpusGroup.sort((group1, group2) -> {
                    Integer sort1 = group1.get(0).getInteger("sortParent");
                    Integer sort2 = group2.get(0).getInteger("sortParent");

                    if (sort1 == null && sort2 == null) return 0;
                    if (sort1 == null) return 1;   // null 排后面
                    if (sort2 == null) return -1;  // null 排后面
                    return Integer.compare(sort1, sort2);
                });

                output.put("testCorpus", continuousCorpusGroup);
                break;
            default:
                throw new GlobalException("不存在的语音交互action=" + action);
        }
        return TaskNodeExecuteResult.success(output);
    }

    @NotNull
    private JSONArray getTestCorpus(JSONObject scheme, String schemeId) {
        String corpusIdsStr = scheme.getString("corpusIds");
        if (StrUtil.isEmpty(corpusIdsStr)) {
            throw new GlobalException(StrUtil.format("id为 [{}] 的方案下,corpusIds为空", schemeId));
        }
        List<String> corpusIds = StrUtil.split(corpusIdsStr, StrUtil.COMMA);
        JSONArray testCorpus = exViCorpusService.queryInIds(corpusIds);
        if (CollUtil.isEmpty(testCorpus)) {
            throw new GlobalException(StrUtil.format("id为 [{}] 的测试语料不存在", corpusIdsStr));
        }
        return testCorpus;
    }
}