package tech.easyflow.ai.config;

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;
import tech.easyflow.ai.rag.KeywordEngineType;
import tech.easyflow.common.util.SpringContextUtil;
import tech.easyflow.common.util.StringUtil;
import tech.easyflow.common.web.exceptions.BusinessException;

import javax.annotation.Resource;
import java.io.File;

@Component
public class RagInfrastructureValidator implements SmartInitializingSingleton {

    @Resource
    private AiMilvusConfig aiMilvusConfig;

    @Resource
    private AiLuceneConfig aiLuceneConfig;

    @Resource
    private AiEsConfig aiEsConfig;

    /**
     * 校验 RAG 基础配置。
     */
    @Override
    public void afterSingletonsInstantiated() {
        validateMilvusConfig();
        validateKeywordSearcher();
    }

    private void validateMilvusConfig() {
        if (StringUtil.noText(aiMilvusConfig.getUri())) {
            throw new BusinessException("Milvus uri 未配置，请检查 rag.milvus.uri");
        }
    }

    private void validateKeywordSearcher() {
        KeywordEngineType engineType = KeywordEngineType.from(
                SpringContextUtil.getProperty("rag.engine", "ES")
        );
        if (engineType == KeywordEngineType.LUCENE) {
            validateLuceneDirectory();
            return;
        }
        if (StringUtil.noText(aiEsConfig.getHost())) {
            throw new BusinessException("ES 地址未配置，请检查 rag.searcher.elastic.host");
        }
        if (StringUtil.noText(aiEsConfig.getIndexName())) {
            throw new BusinessException("ES 索引未配置，请检查 rag.searcher.elastic.indexName");
        }
    }

    private void validateLuceneDirectory() {
        String indexDirPath = aiLuceneConfig.getIndexDirPath();
        if (StringUtil.noText(indexDirPath)) {
            throw new BusinessException("Lucene 索引目录未配置，请检查 rag.searcher.lucene.indexDirPath");
        }
        File indexDir = new File(indexDirPath);
        if (!indexDir.exists() && !indexDir.mkdirs()) {
            throw new BusinessException("Lucene 索引目录创建失败: " + indexDirPath);
        }
        if (!indexDir.isDirectory() || !indexDir.canRead() || !indexDir.canWrite()) {
            throw new BusinessException("Lucene 索引目录不可读写: " + indexDirPath);
        }
    }

}
