package com.purui.prims.headless.server.service.impl;

import com.purui.prims.common.util.JsonUtil;
import com.purui.prims.headless.server.processor.ResultProcessor;
import com.purui.prims.headless.server.service.WorkflowService;
import com.purui.prims.headless.server.utils.ComponentFactory;
import com.purui.prims.headless.api.pojo.enums.ChatWorkflowState;
import com.purui.prims.headless.api.pojo.response.ParseResp;
import com.purui.prims.headless.chat.ChatContext;
import com.purui.prims.headless.chat.ChatQueryContext;
import com.purui.prims.headless.chat.corrector.SemanticCorrector;
import com.purui.prims.headless.chat.mapper.SchemaMapper;
import com.purui.prims.headless.chat.parser.SemanticParser;
import com.purui.prims.headless.chat.query.SemanticQuery;
import com.purui.prims.headless.chat.query.rule.RuleSemanticQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class WorkflowServiceImpl implements WorkflowService {
    private List<SchemaMapper> schemaMappers = ComponentFactory.getSchemaMappers();
    private List<SemanticParser> semanticParsers = ComponentFactory.getSemanticParsers();
    private List<SemanticCorrector> semanticCorrectors = ComponentFactory.getSemanticCorrectors();
    private List<ResultProcessor> resultProcessors = ComponentFactory.getResultProcessors();

    public void startWorkflow(ChatQueryContext queryCtx, ChatContext chatCtx, ParseResp parseResult) {
        queryCtx.setWorkflowState(ChatWorkflowState.MAPPING);
        while (queryCtx.getWorkflowState() != ChatWorkflowState.FINISHED) {
            switch (queryCtx.getWorkflowState()) {
                case MAPPING:
                    performMapping(queryCtx);
                    queryCtx.setWorkflowState(ChatWorkflowState.PARSING);
                    break;
                case PARSING:
                    performParsing(queryCtx, chatCtx);
                    queryCtx.setWorkflowState(ChatWorkflowState.CORRECTING);
                    break;
                case CORRECTING:
                    performCorrecting(queryCtx);
                    queryCtx.setWorkflowState(ChatWorkflowState.PROCESSING);
                    break;
                case PROCESSING:
                default:
                    performProcessing(queryCtx, chatCtx, parseResult);
                    queryCtx.setWorkflowState(ChatWorkflowState.FINISHED);
                    break;
            }
        }
    }

    public void performMapping(ChatQueryContext queryCtx) {
        if (Objects.isNull(queryCtx.getMapInfo())
            || MapUtils.isEmpty(queryCtx.getMapInfo().getDataSetElementMatches())) {
            schemaMappers.forEach(mapper -> mapper.map(queryCtx));
        }
    }

    public void performParsing(ChatQueryContext queryCtx, ChatContext chatCtx) {
        semanticParsers.forEach(parser -> {
            parser.parse(queryCtx, chatCtx);
            log.debug("{} result:{}", parser.getClass().getSimpleName(), JsonUtil.toString(queryCtx));
        });
    }

    public void performCorrecting(ChatQueryContext queryCtx) {
        List<SemanticQuery> candidateQueries = queryCtx.getCandidateQueries();
        if (CollectionUtils.isNotEmpty(candidateQueries)) {
            for (SemanticQuery semanticQuery : candidateQueries) {
                if (semanticQuery instanceof RuleSemanticQuery) {
                    continue;
                }
                for (SemanticCorrector corrector : semanticCorrectors) {
                    corrector.correct(queryCtx, semanticQuery.getParseInfo());
                    if (!ChatWorkflowState.CORRECTING.equals(queryCtx.getWorkflowState())) {
                        break;
                    }
                }
            }
        }
    }

    public void performProcessing(ChatQueryContext queryCtx, ChatContext chatCtx, ParseResp parseResult) {
        resultProcessors.forEach(processor -> {
            processor.process(parseResult, queryCtx, chatCtx);
        });
    }
}