package com.infoepoch.pms.agent.controller;

import com.infoepoch.pms.agent.common.utils.LogHelper;
import com.infoepoch.pms.agent.domain.care.CareAgentService;
import com.infoepoch.pms.agent.domain.care.log.CareTraceLogSupport;
import com.infoepoch.pms.agent.domain.itworkbench.WorkbenchAIService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/workbench/agent")
public class WorkbenchAgentChatController {
    private final WorkbenchAIService workbenchAIService;

    /**
     * 推荐场景的标准 GET 方式的流式聊天入口。
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamAgent(@RequestParam("sessionId") String sessionId,
                                                         @RequestParam("message") String message) {
        return streamWorkbenchAgentInternal(sessionId, message);
    }



    /**
     * 将领域服务输出统一封装成 SSE 事件流。
     */
    private Flux<ServerSentEvent<String>> streamWorkbenchAgentInternal(String sessionId, String message) {
        String traceId = CareTraceLogSupport.newTraceId();
        LogHelper.info(this, CareTraceLogSupport.format(
                traceId,
                sessionId,
                "it_workbench_stream_start",
                "request received, " + CareTraceLogSupport.safeMessageSummary(message)
        ));
        if (!StringUtils.hasText(sessionId)) {
            LogHelper.info(this, CareTraceLogSupport.format(
                    traceId,
                    sessionId,
                    "it_workbench_stream_validation_failed",
                    "sessionId is blank"
            ));
            return Flux.just(buildEvent("error", "sessionId不能为空"));
        }
        return workbenchAIService.streamChat(traceId, sessionId, message)
                .map(chunk -> buildEvent("message", chunk))
                .concatWithValues(buildEvent("done", "[DONE]"))
                .doOnComplete(() -> LogHelper.info(this, CareTraceLogSupport.format(
                        traceId,
                        sessionId,
                        "it_workbench_stream_complete",
                        "sse completed"
                )))
                .doOnError(error -> LogHelper.error(this, CareTraceLogSupport.format(
                        traceId,
                        sessionId,
                        "it_workbench_stream_error",
                        "sse failed, error=" + CareTraceLogSupport.safeText(resolveErrorMessage(error))
                ), error))
                .onErrorResume(error -> Flux.just(buildEvent("error", resolveErrorMessage(error))));
    }

    /**
     * 构造统一的 SSE 消息事件。
     */
    private ServerSentEvent<String> buildEvent(String event, String data) {
        return ServerSentEvent.<String>builder()
                .event(event)
                .data(data)
                .build();
    }

    /**
     * 将异常转换成可直接返回给前端的错误文案。
     */
    private String resolveErrorMessage(Throwable error) {
        return StringUtils.hasText(error.getMessage()) ? error.getMessage() : "itWorkbench流式调用失败";
    }
}
