package com.lili.aitest;

import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;


@RestController
public class ChatController {
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private OpenAiChatClient chatClient;

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        try {
            ChatResponse response = chatClient.call(new Prompt(message));
            String content = response.getResult().getOutput().getContent();
            
            logger.info("Response received successfully");
            return content;
            
        } catch (Exception e) {
            logger.error("Error processing chat request: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping(value = "/chat/stream", produces = "text/event-stream;charset=UTF-8")
    public SseEmitter streamChat(@RequestParam String message) {
        SseEmitter emitter = new SseEmitter(-1L); // 无限超时
        
        try {
            
            // Create prompt with UserMessage
            Prompt prompt = new Prompt(new UserMessage(message));
            
            // Stream the response
            chatClient.stream(prompt).subscribe(
                chunk -> {
                    try {
                        if (chunk != null && chunk.getResult() != null) {
                            String content = chunk.getResult().getOutput().getContent();
                            if (content != null && !content.isEmpty()) {
                                emitter.send(content);
                            }
                        }
                    } catch (IOException e) {
                        logger.error("Error sending chunk: {}", e.getMessage());
                        emitter.completeWithError(e);
                    }
                },
                error -> {
                    logger.error("Error in stream: {}", error.getMessage());
                    emitter.completeWithError(error);
                },
                () -> {
                    logger.info("Stream completed successfully");
                    emitter.complete();
                }
            );
            
        } catch (Exception e) {
            logger.error("Error processing streaming chat request: {}", e.getMessage());
            emitter.completeWithError(e);
        }
        
        return emitter;
    }
}