package com.yutou.qqbot.http;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import lombok.val;

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

@Data
class Message {
    @JSONField(name = "role")
    String role;

    @JSONField(name = "content")
    String content;

    public Message(String role, String content) {
        this.role = role;
        this.content = content;
    }
}

@Data
class GPTRequest {
    @JSONField(name = "model")
    String model;

    @JSONField(name = "messages")
    List<Message> messages = new ArrayList<>();

    @JSONField(name = "stream")
    boolean stream = false;

    @JSONField(name = "max_tokens")
    int maxTokens;

    @JSONField(name = "stop")
    List<String> stop = new ArrayList<>(List.of("null"));

    @JSONField(name = "temperature")
    float temperature ;

    @JSONField(name = "top_p")
    float topP ;

    @JSONField(name = "top_k")
    int topK ;

    @JSONField(name = "frequency_penalty")
    float frequencyPenalty;
}

public class GPTBuilder {
    private final GPTRequest request;

    private GPTBuilder(String model) {
        request = new GPTRequest();
        request.model = model;
    }

    public static GPTBuilder create(String model) {
        return new GPTBuilder(model);
    }

    public GPTBuilder addMessage(String content,boolean isGPT) {
        request.messages.add(new Message(isGPT ? "assistant" : "user", content));
        return this;
    }

    public GPTBuilder addMessage(String role, String content) {
        request.messages.add(new Message(role, content));
        return this;
    }

    public GPTBuilder setMaxTokens(int maxTokens) {
        request.maxTokens = maxTokens;
        return this;
    }

    public GPTBuilder setStream(boolean stream) {
        request.stream = stream;
        return this;
    }

    public GPTBuilder setTemperature(float temperature) {
        request.temperature = temperature;
        return this;
    }

    public GPTBuilder setTopP(float topP) {
        request.topP = topP;
        return this;
    }

    public GPTBuilder setTopK(int topK) {
        request.topK = topK;
        return this;
    }

    public GPTBuilder setFrequencyPenalty(float frequencyPenalty) {
        request.frequencyPenalty = frequencyPenalty;
        return this;
    }

    // 可以根据需要添加更多配置方法

    public JSONObject build() {
        val json = JSONObject.parse(JSONObject.toJSONString(request));
        // 创建一个迭代器来遍历JSON对象的键
        Iterator<String> keys = json.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            Object value = json.get(key);

            // 检查值是否为0或为空字符串
            if (value == null || value.equals(0) || (value instanceof String && ((String) value).isEmpty())) {
                keys.remove(); // 移除键值对
            }
        }
        return json;
    }
}