package com.zioinfo.cms.ai.learning;

import com.zioinfo.cms.rag.RagProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

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

/**
 * AI 피드백 수집 서비스. [GUARDiA-CMS]
 *
 * <p>스펙(AI_PLATFORM_SPEC §5): 피드백(👍/👎 + 교정)은 <b>로컬 DuckDB 기록 + 중앙 guardia-rag
 * {@code /feedback} 전달</b>(둘 다). 로컬은 솔루션별 AI 분석/오프라인, 중앙은 통합 학습·평가 게이트.
 *
 * <p><b>안전</b>: 두 경로 모두 best-effort — 실패해도 예외를 전파하지 않는다. 중앙 전달은
 * 온프레미스 루프백(RagProperties base-url)만. 자격증명/스택트레이스 미노출(요약 로깅).
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearningFeedbackService {

    private final LearningStore store;
    private final WebClient.Builder webClientBuilder;
    private final RagProperties ragProps;

    /**
     * 피드백 1건 처리: 로컬 DuckDB 기록 + 중앙 rag 전달.
     *
     * @return {@code {localStored, centralForwarded}} — 실패 시 각 false(요청은 성공 응답).
     */
    public Map<String, Object> submit(String feature, String question, String answer,
                                      String verdict, String correction, String userRef) {
        Map<String, Object> result = new LinkedHashMap<>();
        boolean localStored = false;
        try {
            store.insertFeedback(feature, question, answer, verdict, correction, userRef);
            localStored = store.available();
        } catch (Exception e) {
            log.warn("로컬 피드백 기록 실패(무시): {}", e.getClass().getSimpleName());
        }
        result.put("localStored", localStored);
        result.put("centralForwarded", forwardCentral(feature, question, answer, verdict, correction));
        return result;
    }

    /** 중앙 guardia-rag /feedback 전달(best-effort, 온프레미스 루프백 전용). */
    private boolean forwardCentral(String feature, String question, String answer,
                                   String verdict, String correction) {
        if (!ragProps.isEnabled()) return false;
        try {
            Map<String, Object> body = new LinkedHashMap<>();
            body.put("solution", ragProps.getSolution());
            body.put("feature", feature);
            body.put("question", LearningStore.maskPii(question));
            body.put("answer", LearningStore.maskPii(answer));
            body.put("verdict", verdict);
            if (correction != null && !correction.isBlank()) {
                body.put("correction", LearningStore.maskPii(correction));
            }
            webClientBuilder.baseUrl(ragProps.getBaseUrl()).build()
                    .post().uri("/feedback")
                    .bodyValue(body)
                    .retrieve()
                    .bodyToMono(String.class)
                    .timeout(Duration.ofSeconds(5))
                    .block();
            return true;
        } catch (Exception e) {
            log.warn("중앙 rag /feedback 전달 실패(무시): {}", e.getClass().getSimpleName());
            return false;
        }
    }
}
