package com.infoepoch.pms.agent.service;

import com.infoepoch.pms.agent.config.JsonUtils;
import com.infoepoch.pms.agent.config.PmsAgentProperties;
import com.infoepoch.pms.agent.web.dto.AgentChatRequest;
import com.infoepoch.pms.agent.web.dto.AgentChatResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PmsAgentService {

    private static final long SSE_TIMEOUT = 0L;

//    private final ChatModel pmsChatModel;
    private final PmsAgentProperties properties;

    public void chatTest() {
        OpenAiApi openAiApi = OpenAiApi.builder().baseUrl("https://api.siliconflow.cn").apiKey(
                "sk-necxquynovkphnulbbfbsopeosgogrsuqgxxctzhbcbpntyh").build();
        ChatModel chatModel = OpenAiChatModel.builder().openAiApi(openAiApi).build();
        Prompt prompt = new Prompt("你好!",
                OpenAiChatOptions.builder()
                        .model("Qwen/Qwen3.5-27B")
                        .temperature(0.7)
                        .build());
        final ChatResponse chatResponse = chatModel.call(prompt);
        System.out.println(JsonUtils.objectToJson(chatResponse));
    }

    public void chatTest1() {
        OpenAiApi openAiApi = OpenAiApi.builder().baseUrl("http://172.28.30.253:8001").apiKey(
                "115e68c85d91d40dd3df42a06f08cbed").build();
        ChatModel chatModel = OpenAiChatModel.builder().openAiApi(openAiApi).build();
        Prompt prompt = new Prompt("你好!",
                OpenAiChatOptions.builder()
                        .model("Qwen3.5-27B")
                        .temperature(0.7)
                        .build());
        final ChatResponse chatResponse = chatModel.call(prompt);
        System.out.println(JsonUtils.objectToJson(chatResponse));
    }

//    public AgentChatResponse chat(AgentChatRequest request) {
//        ChatResponse response = pmsChatModel.call(buildPrompt(request.message()));
//        return new AgentChatResponse(extractText(response));
//    }

    public SseEmitter streamChat(AgentChatRequest request) {
        SseEmitter emitter = new SseEmitter(SSE_TIMEOUT);
        Prompt prompt = buildPrompt("你好");
//        ChatResponse s = pmsChatModel.call(prompt);
//        System.out.println(s);
//        pmsChatModel.stream(buildPrompt(request.message()))
//                .map(this::extractText)
//                .filter(StringUtils::hasText)
//                .doOnNext(token -> sendToken(emitter, token))
//                .doOnComplete(() -> completeStream(emitter))
//                .doOnError(emitter::completeWithError)
//                .subscribe();
        return emitter;
    }

    private Prompt buildPrompt(String message) {
        List<Message> messages = new ArrayList<>();
        if (StringUtils.hasText(properties.getSystemPrompt())) {
            messages.add(new SystemMessage(properties.getSystemPrompt()));
        }
        messages.add(new UserMessage(message));

        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .model(properties.getModel())
                .temperature(properties.getTemperature())
                .build();

        return new Prompt(messages, options);
    }

    private String extractText(ChatResponse response) {
        if (response == null || response.getResult() == null || response.getResult().getOutput() == null) {
            return "";
        }
        return response.getResult().getOutput().getText();
    }

    private void sendToken(SseEmitter emitter, String token) {
        try {
            emitter.send(SseEmitter.event().name("token").data(token));
        } catch (Exception exception) {
            emitter.completeWithError(exception);
        }
    }

    private void completeStream(SseEmitter emitter) {
        try {
            emitter.send(SseEmitter.event().name("done").data("[DONE]"));
            emitter.complete();
        } catch (Exception exception) {
            emitter.completeWithError(exception);
        }
    }
}