package org.dromara.ai.controller.app;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.ai.platform.CozeService;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Coze平台控制器
 * 提供Coze平台的Bot对话接口
 *
 * @author pengles
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/ai/coze")
@RequiredArgsConstructor
public class CozeController {
    
    private final CozeService cozeService;

    /**
     * Coze流式Bot对话
     *
     * @param body 请求体，包含botId（Bot ID）和input（输入内容）
     * @return SSE事件流
     */
    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "Coze流式Bot对话", description = "通过SSE与Coze平台的Bot进行流式对话")
    public SseEmitter stream(@RequestBody Map<String, Object> body) {
        String botId = String.valueOf(body.getOrDefault("botId", ""));
        String input = String.valueOf(body.getOrDefault("input", ""));
        
        log.info("Coze流式Bot对话请求 - Bot ID: {}, 输入长度: {}", botId, input.length());
        
        SseEmitter emitter = new SseEmitter(TimeUnit.MINUTES.toMillis(2));
        try {
            String raw = cozeService.stream(botId, input);
            emitter.send(raw);
            emitter.send("[DONE]");
            emitter.complete();
            log.debug("Coze流式Bot对话完成 - Bot ID: {}", botId);
        } catch (Exception e) {
            log.error("Coze流式Bot对话失败 - Bot ID: {}", botId, e);
            try {
                emitter.send(SseEmitter.event().name("error").data("ERROR: " + e.getMessage()));
            } catch (Exception ignored) {
                log.debug("发送错误事件失败", ignored);
            }
            emitter.completeWithError(e);
        }
        return emitter;
    }
}
