package com.fufan.mtsaas.modules.emoon.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@RestController
public class ChatController {
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter chat(@RequestParam String token) {
        SseEmitter emitter = new SseEmitter(30_000L); // 设置超时时间 30 秒
        ObjectMapper objectMapper = new ObjectMapper();
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        // 模拟 SSE 响应，需替换为实际 AI 模型集成
        executor.scheduleAtFixedRate(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    Map<String, Object> choice = new HashMap<>();
                    Map<String, Object> delta = new HashMap<>();
                    delta.put("content", "样本响应部分 " + i);
                    choice.put("delta", delta);

                    Map<String, Object> response = new HashMap<>();
                    response.put("choices", new Object[]{choice});

                    emitter.send(SseEmitter.event()
                            .data("data: " + objectMapper.writeValueAsString(response) + "\n\n"));
                    Thread.sleep(1000); // 模拟每秒发送一次
                }
                emitter.send(SseEmitter.event()
                        .name("end")
                        .data("event: end\ndata: 流结束\n\n"));
                emitter.complete();
                executor.shutdown();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
                executor.shutdown();
            }
        }, 0, 1, TimeUnit.SECONDS);

        return emitter;
    }
}