package ai.decompile.ai.config;

import io.micrometer.observation.ObservationRegistry;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.OllamaEmbeddingModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaChatOptions;
import org.springframework.ai.ollama.api.OllamaEmbeddingOptions;
import org.springframework.ai.ollama.management.ModelManagementOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;

@Configuration
@EnableResilientMethods
@ConditionalOnProperty(name = "app.ai.enabled", havingValue = "true", matchIfMissing = true)
public class AiConfig {
  @Value("${spring.ai.ollama.base-url:http://localhost:11434}")
  private String ollamaBaseUrl;

  @Value("${spring.ai.ollama.chat.options.model:gemma4:12b}")
  private String ollamaChatModelName;

  @Value("${spring.ai.ollama.chat.options.temperature:0.3}")
  private double ollamaTemperature;

  @Value("${spring.ai.ollama.embedding.options.model:qwen3-embedding:latest}")
  private String ollamaEmbeddingModel;

  @Bean
  OllamaApi ollamaApi() {
    return OllamaApi.builder().baseUrl(ollamaBaseUrl).build();
  }

  @Bean
  OllamaChatModel ollamaChatModel(OllamaApi ollamaApi, ObservationRegistry observationRegistry) {
    return OllamaChatModel.builder()
        .ollamaApi(ollamaApi)
        .options(
            OllamaChatOptions.builder()
                .model(ollamaChatModelName)
                .temperature(ollamaTemperature)
                .build())
        .observationRegistry(observationRegistry)
        .build();
  }

  @Bean
  OllamaEmbeddingModel ollamaEmbeddingModel(
      OllamaApi ollamaApi, ObservationRegistry observationRegistry) {
    return OllamaEmbeddingModel.builder()
        .ollamaApi(ollamaApi)
        .options(OllamaEmbeddingOptions.builder().model(ollamaEmbeddingModel).build())
        .observationRegistry(observationRegistry)
        .modelManagementOptions(ModelManagementOptions.defaults())
        .build();
  }
}
