package com.yutou.qqbot.gpt;

import com.yutou.okhttp.HttpLoggingInterceptor;
import com.yutou.qqbot.data.baidu.Message;
import com.yutou.qqbot.data.gpt.OpenAiBean;
import com.yutou.qqbot.http.GPTApi;
import com.yutou.qqbot.http.GPTBuilder;
import com.yutou.qqbot.utlis.ConfigTools;
import com.yutou.qqbot.utlis.StringUtils;
import lombok.val;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class SiliconGPTManager extends AbsGPTManager {
    //生成单例模式
    private volatile static SiliconGPTManager instance = new SiliconGPTManager();

    private SiliconGPTManager() {
        val load = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.GPT_SILICON, String.class);
        String defModel = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B";
        if (!StringUtils.isEmpty(load)) {
            defModel = load;
        }
        setModel(defModel);
    }

    public static SiliconGPTManager getInstance() {
        if (instance == null) {
            synchronized (SiliconGPTManager.class) {
                if (instance == null) {
                    instance = new SiliconGPTManager();
                }
            }
        }
        return instance;
    }

    @Override
    public synchronized Message sendMessage(String user, String message) {
        // 获取或创建用户锁
        AtomicBoolean lock = userLocks.computeIfAbsent(user, k -> new AtomicBoolean(false));
        try {
            // 尝试加锁（如果已被锁定则立即返回提示）
            if (!lock.compareAndSet(false, true)) {
                return Message.create("您有请求正在处理中，请稍后再试", true);
            }

            val builder = GPTBuilder.create(model);
            List<Message> list = getMessageList(user);
            list.add(Message.create(message));
            for (Message msg : list) {
                builder.addMessage(msg.getRole(), msg.getContent());
            }
            val response = GPTApi.getApi().completions(builder.build()).execute();

            if (!response.isSuccessful()) {
                return Message.create("API请求失败", true);
            }

            val body = response.body();
            if (body == null || body.getData() == null) {
                return Message.create("API请求为空", true);
            }
            if (body.getRetcode() != 0) {
                return Message.create(body.getMsg(), true);
            }
            val choices = body.getData().getChoices();
            if (choices == null || choices.isEmpty()) {
                return Message.create("没有对话信息", true);
            }

            val choice = choices.get(choices.size() - 1);
            val bot = Message.create(choice.getMessage().getContent(), true);

            list.add(bot);
            return bot;

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            lock.set(false);
            userLocks.remove(user, lock);
        }

    }

    @Override
    public AbsGPTManager setModel(String model) {
        ConfigTools.save(ConfigTools.CONFIG, ConfigTools.GPT_SILICON, model);
        return super.setModel(model);
    }

    @Override
    public File textToImage(String user, String text) {
        return null;
    }

    @Override
    public String imageToText(String user, File file) {
        return "";
    }

    @Override
    public String getGPTVersion() {
        return model;
    }

    @Override
    public int setMaxMessageCount(int count) {
        MAX_MESSAGE.set(count);
        return count;
    }

    public static void main(String[] args) {
        String model = "THUDM/glm-4-9b-chat";
        val message = AbsGPTManager.getManager(SiliconGPTManager.class)
                .setModel(model)
                .sendMessage("user", "宫廷玉液酒的下一句是什么？");
        System.out.println(message);
        System.out.println(AbsGPTManager.getManager(SiliconGPTManager.class)
                .setModel(model)
                .sendMessage("user", "宫廷玉液酒减去大锤等于多少")
        );
    }
}
