package com.zioinfo.mall.ai;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.Map;

/**
 * Ollama 온프레미스 LLM 클라이언트 (Mall AI 전용).
 *
 * <p>보안 불변 규칙: localhost Ollama만 호출. 외부 AI API 절대 금지.
 * 장애/오프라인 시 예외 없이 빈 문자열 반환(서비스가 Java 폴백 수행).
 */
@Slf4j
@Component
public class OllamaClient {

    private final WebClient.Builder builder;
    private final String ollamaUrl;
    private final String model;

    public OllamaClient(WebClient.Builder builder,
                        @Value("${guardia.ollama-url:http://localhost:11434}") String ollamaUrl,
                        @Value("${guardia.ollama-text-model:llama3}") String model) {
        this.builder = builder;
        this.ollamaUrl = ollamaUrl;
        this.model = model;
    }

    @SuppressWarnings("unchecked")
    public String generate(String prompt) {
        try {
            Map<String, Object> body = Map.of("model", model, "prompt", prompt, "stream", false);
            Map<String, Object> res = builder.baseUrl(ollamaUrl).build()
                .post().uri("/api/generate").bodyValue(body)
                .retrieve().bodyToMono(Map.class)
                .timeout(Duration.ofSeconds(120))
                .map(m -> (Map<String, Object>) m).block();
            if (res == null) return "";
            Object r = res.get("response");
            return r == null ? "" : String.valueOf(r).trim();
        } catch (Exception e) {
            log.warn("Ollama 일시 불가 — Java 폴백 사용: {}", e.getMessage());
            return "";
        }
    }
}
