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

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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

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

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

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        List<Integer> iterations = message.getIterations();

        String audioPath;
        switch (action) {
            case VI_CORPUS_WAKE:
                JSONObject wakeCorpus = inputParams.getJSONObject("wakeCorpus");
                audioPath = wakeCorpus.getString("audioPath");
                break;
            case VI_CORPUS_SINGLE:
                JSONArray singleCorpus = inputParams.getJSONArray("testCorpus");
                // 单次对话只有一层循环
                Integer i = iterations.get(0);
                int index = i - 1;
                JSONObject singleCorpusObj = singleCorpus.getJSONObject(index);
                audioPath = singleCorpusObj.getString("audioPath");
                break;
            case VI_CORPUS_CONTINUOUS:
                // List<List<JSONObject>>
                JSONArray continuousCorpus = inputParams.getJSONArray("testCorpus");

                int idx1 = iterations.get(0) - 1; // 外层
                int idx2 = iterations.get(1) - 1; // 内层
                JSONArray continuous = continuousCorpus.getJSONArray(idx1);
                audioPath = continuous.getJSONObject(idx2).getString("audioPath");
                break;
            default:
                throw new GlobalException("不存在的语音交互action=" + action);


        }
        JSONObject output = new JSONObject().fluentPut("audioPath", audioPath);
        return TaskNodeExecuteResult.success(output);
    }
}