package com.agent.management.config;

import io.milvus.client.MilvusServiceClient;
import io.milvus.param.ConnectParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.milvus.MilvusVectorStore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * Milvus 向量库配置
 *
 * <p>仅当 app.milvus.enabled=true 时创建 {@link VectorStore} bean；
 * 否则跳过 bean 创建，应用仍可正常启动。{@code VectorStoreService} 通过
 * {@link org.springframework.beans.factory.ObjectProvider} 注入，
 * 缺失时调用方会收到明确的业务异常。</p>
 *
 * <p>注意：Spring AI 1.0 的 {@code MilvusVectorStoreAutoConfiguration} 已通过
 * {@code application.yml} 的 {@code spring.autoconfigure.exclude} 排除，
 * 由本类完全接管 VectorStore 的生命周期。</p>
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "app.milvus.enabled", havingValue = "true")
public class MilvusConfig {

    /**
     * Milvus 客户端 stub（创建时不连接，实际网络 I/O 发生在第一次调用）
     */
    @Bean(destroyMethod = "close")
    public MilvusServiceClient milvusServiceClient(MilvusProperties props) {
        ConnectParam.Builder builder = ConnectParam.newBuilder();
        String uri = props.getUri();
        if (StringUtils.hasText(uri)) {
            // 如果用户写 host:port 没写协议，默认补 grpc://（Java SDK 用 gRPC）
            if (!uri.contains("://")) {
                uri = "grpc://" + uri;
            }
            builder.withUri(uri);
            log.info("Milvus 客户端初始化: uri={} (collection={}, dim={})",
                    uri, props.getCollection(), props.getVectorDimension());
        } else {
            // Milvus Lite 默认 gRPC 端口 19530，显式指定 grpc 协议避免误走 HTTP
            String grpcUri = "grpc://" + props.getHost() + ":" + props.getPort();
            builder.withUri(grpcUri);
            log.info("Milvus 客户端初始化: uri={} (collection={}, dim={})",
                    grpcUri, props.getCollection(), props.getVectorDimension());
        }
        return new MilvusServiceClient(builder.build());
    }

    /**
     * VectorStore bean：Spring AI 1.0 的 MilvusVectorStore builder 模式
     * initializeSchema=false：不自动建表，避免启动时强制连接 Milvus
     */
    @Bean
    public VectorStore vectorStore(MilvusServiceClient client,
                                   EmbeddingModel embeddingModel,
                                   MilvusProperties props) {
        log.info("VectorStore(Milvus) 装配中: collection={}, dim={}",
                props.getCollection(), props.getVectorDimension());
        return MilvusVectorStore.builder(client, embeddingModel)
                .collectionName(props.getCollection())
                .embeddingDimension(props.getVectorDimension())
                .initializeSchema(false)
                .build();
    }
}
