package com.zioinfo.mes.rag;
import com.zioinfo.mes.ai.AiService;
import com.zioinfo.mes.rag.RagToggleService.RagToggles;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* MES 대표 AI 기능 RAG 배선 레이어(순증·비파괴).
*
*
기존 {@link AiService}(8개 제조 AI, Ollama + 결정론 Java 폴백)는 불변. 본 서비스는
* 중앙 guardia-rag 를 경유하는 별개 레이어로, 두 대표 기능을 고급 기법으로 전환한다:
*
* - 품질 분석(defectAnalysis) — 불량 원인분석 + SPC 이상감지.
* SPC 수치(평균·관리한계 이탈·런 규칙)는 {@link AiService#spcAnomaly} 결정론 로직으로 산출하고,
* 원인 서술·분류·우선순위만 중앙 {@code /rag/agent}(tool-use) + {@code /rag/structured}(JSON 강제)로 받는다.
* 토글 off/미가용 시 기존 {@link AiService#defectRootCause}/{@code spcAnomaly} 로 무손실 폴백(degraded:true).
* - 예측 분석(predictAnalysis) — 설비 예지보전 + 수요/생산 예측.
* 예측 수치(이동평균·추세·위험점수)는 {@link AiService#forecast}/{@code predictiveMaintenance} 결정론 베이스라인으로 산출하고,
* 해석·권고 서술만 {@code /rag/agent} 로 받는다. 토글 off/미가용 시 결정론 경로로 폴백(degraded:true).
*
*
* 결정론 불변: SPC/예측 수치는 절대 AI 가 만들지 않는다(재현 가능). AI 는 서술·분류·우선순위만.
*
모든 응답에 적용 metadata(retrievalMode·rerank·toolUse·structured·degraded)를 표기해 토글 effect 가 관측 가능하게 한다.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class RagMesService {
private final RagClient rag;
private final RagToggleService toggles;
private final AiService ai; // 기존 결정론/Ollama 폴백 재사용(불변)
/** 불량 RCA 결정론 결과 스키마(중앙 /structured/agent 강제). */
private static final Map DEFECT_SCHEMA = Map.of(
"type", "object",
"properties", Map.of(
"rootCauses", Map.of("type", "array", "items", Map.of(
"type", "object", "properties", Map.of(
"cause", Map.of("type", "string"),
"evidenceRef", Map.of("type", "string"),
"contribution", Map.of("type", "number")
))),
"correctiveActions", Map.of("type", "array", "items", Map.of("type", "string")),
"priority", Map.of("type", "string"),
"confidence", Map.of("type", "number")
),
"required", List.of("rootCauses")
);
/** 예측 해석 결과 스키마(중앙 /agent 구조화). */
private static final Map PREDICT_SCHEMA = Map.of(
"type", "object",
"properties", Map.of(
"interpretation", Map.of("type", "string"),
"drivers", Map.of("type", "array", "items", Map.of("type", "string")),
"recommendation", Map.of("type", "string"),
"confidence", Map.of("type", "number")
),
"required", List.of("interpretation")
);
// 읽기전용 조회 도구 정의(이름·설명만 노출 — 실제 조회는 중앙에서 컬렉션 검색으로 수행. 쓰기/SSH 금지)
private static final List