package com.infoepoch.pms.agent.domain.care;

import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.domain.care.log.CareTraceLogSupport;
import com.infoepoch.pms.agent.domain.care.orchestrator.CareRecommendationOrchestrator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author jiangyz
 * @date 2026/4/2 9:04
 * 精准关爱智能体
 */
@Service
public class CareAgentService {

    private final CareRecommendationOrchestrator careRecommendationOrchestrator;

    public CareAgentService(CareRecommendationOrchestrator careRecommendationOrchestrator) {
        this.careRecommendationOrchestrator = careRecommendationOrchestrator;
    }

    /**
     * 精准关爱智能体统一流式入口，负责基础校验和异常兜底。
     */
    public Flux<String> streamChat(String traceId, String sessionId, String msg) {
        if (StringUtils.isEmpty(msg)) {
            LogHelper.info(this, CareTraceLogSupport.format(
                    traceId,
                    sessionId,
                    "参数校验失败",
                    "message为空"
            ));
            return Flux.error(new IllegalArgumentException("message不能为空"));
        }

        LogHelper.info(this, CareTraceLogSupport.format(
                traceId,
                sessionId,
                "服务开始处理",
                "进入编排层处理"
        ));
        try {
            return careRecommendationOrchestrator.stream(traceId, sessionId, msg)
                    .doOnComplete(() -> LogHelper.info(this, CareTraceLogSupport.format(
                            traceId,
                            sessionId,
                            "服务处理完成",
                            "编排层处理完成"
                    )))
                    .doOnError(error -> LogHelper.error(this, CareTraceLogSupport.format(
                            traceId,
                            sessionId,
                            "服务处理异常",
                            "编排层处理失败，异常=" + CareTraceLogSupport.safeText(error.getMessage())
                    ), error));
        } catch (Exception e) {
            LogHelper.error(this, CareTraceLogSupport.format(
                    traceId,
                    sessionId,
                    "服务处理异常",
                    "streamChat立即失败，异常=" + CareTraceLogSupport.safeText(e.getMessage())
            ), e);
            return Flux.error(new IllegalArgumentException("调用careAgent失败"));
        }
    }
}

