package com.yingpaipay.common.ai.client;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yingpaipay.common.ai.config.SiliconConfig;
import com.yingpaipay.common.ai.enumeration.SiliconModel;
import com.yingpaipay.common.ai.pojo.SiliconFlowMessage;
import com.yingpaipay.common.ai.pojo.SiliconFlowReq;
import com.yingpaipay.common.ai.pojo.SiliconFlowResp;
import lombok.RequiredArgsConstructor;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class SiliconFlowClient {

    private final SiliconConfig config;

    private static final String API_KEY = "sk-ekdouxzwtlrgiiqafirxnfwvrsrczvtezdkvdtapvrhtlpct";

    public SiliconFlowResp askMessages(SiliconModel model, SiliconFlowMessage... messages) {
        if (messages == null || messages.length == 0) {
            throw new IllegalArgumentException("至少需要有一条消息");
        }

        SiliconFlowReq req = new SiliconFlowReq.Builder().model(model).messages(messages).build();

        try (HttpResponse response = HttpRequest.post(config.getV1Url() + "/chat/completions")
            .contentType(ContentType.JSON.getValue())
            .header(Header.AUTHORIZATION, "Bearer " + API_KEY)
            .body(JsonUtils.toJsonString(req))
            .execute()) {

            if (!response.isOk()) {
                throw new RuntimeException("请求失败");
            }

            return JsonUtils.parseObject(response.body(), SiliconFlowResp.class);
        }
    }

}
