package com.purui.prims.headless.chat.corrector;


import com.purui.prims.common.jsqlparser.SqlAddHelper;
import com.purui.prims.common.jsqlparser.SqlRemoveHelper;
import com.purui.prims.common.jsqlparser.SqlReplaceHelper;
import com.purui.prims.common.jsqlparser.SqlSelectFunctionHelper;
import com.purui.prims.common.jsqlparser.SqlSelectHelper;
import com.purui.prims.common.pojo.enums.QueryType;
import com.purui.prims.common.util.ContextUtils;
import com.purui.prims.headless.api.pojo.SemanticParseInfo;
import com.purui.prims.headless.chat.ChatQueryContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Perform SQL corrections on the "Select" section in S2SQL.
 */
@Slf4j
public class SelectCorrector extends BaseSemanticCorrector {

    @Override
    public void doCorrect(ChatQueryContext queryContext, SemanticParseInfo semanticParseInfo) {
        String correctS2SQL = semanticParseInfo.getSqlInfo().getCorrectS2SQL();
        List<String> aggregateFields = SqlSelectHelper.getAggregateFields(correctS2SQL);
        List<String> selectFields = SqlSelectHelper.getSelectFields(correctS2SQL);
        // If the number of aggregated fields is equal to the number of queried fields, do not add fields to select.
        if (!CollectionUtils.isEmpty(aggregateFields)
                && !CollectionUtils.isEmpty(selectFields)
                && aggregateFields.size() == selectFields.size()) {
            return;
        }
        correctS2SQL = addFieldsToSelect(queryContext, semanticParseInfo, correctS2SQL);
        String querySql = SqlReplaceHelper.dealAliasToOrderBy(correctS2SQL);
        semanticParseInfo.getSqlInfo().setCorrectS2SQL(querySql);
    }

    protected String addFieldsToSelect(ChatQueryContext queryContext, SemanticParseInfo semanticParseInfo,
                                       String correctS2SQL) {
        Set<String> selectFields = new HashSet<>(SqlSelectHelper.getSelectFields(correctS2SQL));
        Set<String> needAddFields = new HashSet<>(SqlSelectHelper.getGroupByFields(correctS2SQL));

        //decide whether add order by expression field to select
        String correctorAdditionalInfo = getAdditionalInfo();
        if (StringUtils.isNotBlank(correctorAdditionalInfo) && Boolean.parseBoolean(correctorAdditionalInfo)) {
            needAddFields.addAll(SqlSelectHelper.getOrderByFields(correctS2SQL));
        }
        if (CollectionUtils.isEmpty(selectFields) || CollectionUtils.isEmpty(needAddFields)) {
            return correctS2SQL;
        }
        needAddFields.removeAll(selectFields);
        String addFieldsToSelectSql = SqlAddHelper.addFieldsToSelect(correctS2SQL, new ArrayList<>(needAddFields));
        semanticParseInfo.getSqlInfo().setCorrectS2SQL(addFieldsToSelectSql);
        return addFieldsToSelectSql;
    }

    private String addTagDefaultFields(ChatQueryContext queryContext, SemanticParseInfo semanticParseInfo,
                                       String correctS2SQL) {
        //If it is in DETAIL mode and select *, add default metrics and dimensions.
        boolean hasAsterisk = SqlSelectFunctionHelper.hasAsterisk(correctS2SQL);
        if (!(hasAsterisk && QueryType.DETAIL.equals(semanticParseInfo.getQueryType()))) {
            return correctS2SQL;
        }
        Set<String> needAddDefaultFields = new HashSet<>();
        // remove * in sql and add default fields.
        if (!CollectionUtils.isEmpty(needAddDefaultFields)) {
            correctS2SQL = SqlRemoveHelper.removeAsteriskAndAddFields(correctS2SQL, needAddDefaultFields);
        }
        return correctS2SQL;
    }

    private String getAdditionalInfo() {
        String correctorAdditionalInfo = null;
        try {
            Environment environment = ContextUtils.getBean(Environment.class);
            correctorAdditionalInfo = environment.getProperty("s2.corrector.additional.information");
        } catch (Exception e) {
            log.error("getAdditionalInfo error:{}", e);
        }
        return correctorAdditionalInfo;
    }
}
