package com.lingyue.graph.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;

/**
 * 向量化服务配置
 * 配置 Ollama WebClient 和通用 RestTemplate
 *
 * @author lingyue
 * @since 2026-01-15
 */
@Slf4j
@Configuration
public class VectorConfig {

    @Value("${ollama.url:http://localhost:11434}")
    private String ollamaUrl;

    @Value("${ollama.timeout:60000}")
    private int ollamaTimeout;

    @Value("${ner.python-service.timeout:300000}")
    private int nerServiceTimeout;

    /**
     * Ollama WebClient Bean
     * 用于调用 Ollama Embedding API
     */
    @Bean
    public WebClient ollamaWebClient() {
        log.info("初始化 Ollama WebClient: url={}", ollamaUrl);

        // 增加缓冲区大小以处理大向量
        ExchangeStrategies strategies = ExchangeStrategies.builder()
                .codecs(configurer -> configurer
                        .defaultCodecs()
                        .maxInMemorySize(10 * 1024 * 1024)) // 10MB
                .build();

        return WebClient.builder()
                .baseUrl(ollamaUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .exchangeStrategies(strategies)
                .build();
    }

    /**
     * 通用 RestTemplate Bean
     * 用于调用外部 HTTP 服务（如 Python NER 服务）
     * NER 服务使用 DeepSeek API，处理长文档需要较长时间
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        log.info("初始化 RestTemplate: nerServiceTimeout={}ms", nerServiceTimeout);
        return builder
                .setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofMillis(nerServiceTimeout))
                .build();
    }
}
