package com.sonic.cow.client.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.byteplus.ark.runtime.model.completion.chat.*;
import com.byteplus.ark.runtime.model.context.CreateContextRequest;
import com.byteplus.ark.runtime.model.context.CreateContextResult;
import com.byteplus.ark.runtime.model.context.TruncationStrategy;
import com.byteplus.ark.runtime.model.context.chat.ContextChatCompletionRequest;
import com.byteplus.ark.runtime.service.ArkService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.cow.client.ContextChatClient;
import com.sonic.cow.client.request.ChatCompletionMessage;
import com.sonic.cow.domain.bo.AiGen4Bo;
import com.sonic.cow.enums.ToastResultCode;
import com.sonic.cow.tools.GetAiImageArgs;
import com.sonic.frog.lib.client.AiUserAlbumClient;
import com.sonic.frog.lib.output.AIUserAlbumApiOutput;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

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

@Slf4j
@Service
public class ContextChatClientImpl implements ContextChatClient {

    @Value("${volcengine.contextCachingModel}")
    private String contextCachingModel;

    @Value("${volcengine.apiKey:4075846b-cb9e-45f6-bf59-ab0a94745d9b}")
    private String apiKey = "4075846b-cb9e-45f6-bf59-ab0a94745d9b";

    @Value("${volcengine.chatUrl:https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions}")
    private String chatUrl = "https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions";

    @Autowired
    private ArkService volcengineArkService;
    @Autowired
    private AiUserAlbumClient aiUserAlbumClient;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String createContextCaching(List<ChatMessage> messages, Integer ttl) {
        CreateContextRequest createContextRequest = CreateContextRequest.builder()
                .model(contextCachingModel)
                .mode("session")
                .truncationStrategy(TruncationStrategy.builder()
                        .type("rolling_tokens")
                        .rollingTokens(true)
                        .build())
                .messages(messages)
                //过期时间1小时
                .ttl(ttl)
                .build();
        log.info("===> createContextCaching request : {}", JSONObject.toJSONString(createContextRequest));
        CreateContextResult createContextResult = volcengineArkService.createContext(createContextRequest);
        String contextId = createContextResult.getId();
        log.info("===> created context, id = {}", contextId);
        return contextId;
    }

    @Override
    public String contextChat(String contextId, String message) {
        ContextChatCompletionRequest chatCompletionRequest = ContextChatCompletionRequest.builder()
                .contextId(contextId)
                .model(contextCachingModel)
                .messages(Collections.singletonList(ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(message).build()))
                .build();
        ChatCompletionResult chatCompletionResult =  volcengineArkService.createContextChatCompletion(chatCompletionRequest);
        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice -> stringBuffer.append(choice.getMessage().getContent()));
        return stringBuffer.toString();
    }

    @Override
    public String contextChat(String contextId, String message, List<ChatTool> tools) {
        ContextChatCompletionRequest chatCompletionRequest = ContextChatCompletionRequest.builder()
                .contextId(contextId)
                .model(contextCachingModel)
                .messages(Collections.singletonList(ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(message).build()))
                .tools(tools)
                .build();
        ChatCompletionResult chatCompletionResult = volcengineArkService.createContextChatCompletion(chatCompletionRequest);

        ChatCompletionChoice choice1 = chatCompletionResult.getChoices().get(0);

        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice -> stringBuffer.append(choice.getMessage().getContent()));
        return stringBuffer.toString();
    }


    @Override
    public String contextToolsChat(String contextId, String message, List<ChatTool> tools) {
        List<ChatMessage> messages = Lists.newArrayList();
        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(message).build());
        ContextChatCompletionRequest chatCompletionRequest = ContextChatCompletionRequest.builder()
                .contextId(contextId)
                .model(contextCachingModel)
                .messages(messages)
                .tools(tools)
                .build();
        ChatCompletionResult chatCompletionResult = volcengineArkService.createContextChatCompletion(chatCompletionRequest);
        ChatCompletionChoice choice = chatCompletionResult.getChoices().get(0);
        List<ChatToolCall> toolCalls = choice.getMessage().getToolCalls();
        ChatMessage feedbackChatMessage = null;
        //判断是否需要走本地方法调用
        if (choice.getFinishReason() != null && "tool_calls".equalsIgnoreCase(choice.getFinishReason()) && toolCalls != null && !toolCalls.isEmpty()) {
            //执行工具方法的调用
            for (ChatToolCall toolCall : toolCalls) {
                String toolName = toolCall.getFunction().getName();
                //处理获取AI未解锁图片的方法调用
                if ("get_ai_image".equals(toolName)) {
                    //解析入参
                    String argumentsJson = toolCall.getFunction().getArguments();
                    GetAiImageArgs tool_args = null;
                    try {
                        tool_args = objectMapper.readValue(argumentsJson, GetAiImageArgs.class);
                    } catch (JsonProcessingException e) {
                        // 将错误信息作为工具结果回填
                        feedbackChatMessage = ChatMessage.builder()
                                .role(ChatMessageRole.TOOL)
                                .content("解析参数时出错: " + e.getMessage())
                                .toolCallId(toolCall.getId())
                                .build();
                        log.error("===> 解析 send_ai_Image 参数时出错: " + argumentsJson + " - " + e.getMessage());
                    }
                    //调用方法获取待解锁图片
                    AIUserAlbumApiOutput toolResult = aiUserAlbumClient.getRandomLockImage(tool_args.getUserId(), tool_args.getAiId());
                    log.info("===> 工具执行结果 id : {}, result : {}", toolCall.getId(), toolResult);
                    if (toolResult == null) {
                        // 步骤 4：回填工具结果，并获取模型总结回复
                        feedbackChatMessage = ChatMessage.builder()
                                .role(ChatMessageRole.TOOL)
                                .content("未找到图片")
                                .toolCallId(toolCall.getId()) // 关联工具调用 ID
                                .build();
                    } else {
                        //返回 图片
                        return toolResult.getImgUrl();
                    }
                }
            }
        }
        if(feedbackChatMessage != null) {
            //TODO 再次调用反馈结果

        }
        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice1 -> stringBuffer.append(choice1.getMessage().getContent()));
        return stringBuffer.toString();
    }

    @Override
    public String contextChat(String contextId, String message, String imageUrl) {
        List<ChatMessage> messages = Lists.newArrayList();
        List<ChatCompletionContentPart> multiParts = new ArrayList<>();
        multiParts.add(ChatCompletionContentPart.builder().type("text").text(message).build());
        multiParts.add(ChatCompletionContentPart.builder().type("image_url").imageUrl(new ChatCompletionContentPart.ChatCompletionContentPartImageURL(imageUrl)).build());
        //添加用户发送内容 多模态（文本、图片）
        ChatMessage userMessage = ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .multiContent(multiParts).build();
        messages.add(userMessage);

        log.info("===> contextChat messages : {}", JSONObject.toJSONString(messages));

        ContextChatCompletionRequest chatCompletionRequest = ContextChatCompletionRequest.builder()
                .contextId(contextId)
                .model(contextCachingModel)
                .messages(messages)
                .build();
        ChatCompletionResult chatCompletionResult =  volcengineArkService.createContextChatCompletion(chatCompletionRequest);
        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice -> stringBuffer.append(choice.getMessage().getContent()));
        return stringBuffer.toString();
    }

    @Override
    public String chat(List<ChatMessage> messages) {
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(contextCachingModel)
                .messages(messages)
                .build();
        ChatCompletionResult chatCompletionResult =  volcengineArkService.createChatCompletion(chatCompletionRequest);
        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice -> stringBuffer.append(choice.getMessage().getContent()));
        return stringBuffer.toString();
    }

    @Override
    public Flux<ChatCompletionChunk> streamContextChat(String contextId, String message) {
        ContextChatCompletionRequest streamChatCompletionRequest = ContextChatCompletionRequest.builder()
                .contextId(contextId)
                .model(contextCachingModel)
                .messages(Collections.singletonList(ChatMessage.builder().role(ChatMessageRole.USER).content(message).build()))
                .build();
        return Flux.from(volcengineArkService.streamContextChatCompletion(streamChatCompletionRequest));
    }

    @Override
    public String aiGen(String systemPrompt, Double temperature) {
        log.info("===> aiGen systemPrompt : {}", systemPrompt);
        Long startTime = System.currentTimeMillis();
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(contextCachingModel)
                .messages(Collections.singletonList(ChatMessage.builder()
                        .role(ChatMessageRole.USER)
                        .content(systemPrompt).build()))
//                .thinking(new ChatCompletionRequest.ChatCompletionRequestThinking("disabled"))
                .temperature(temperature == null ? 0.5 : temperature)
                .build();
        ChatCompletionResult chatCompletionResult = volcengineArkService.createChatCompletion(chatCompletionRequest);
        StringBuffer stringBuffer = new StringBuffer();
        chatCompletionResult.getChoices().forEach(choice -> stringBuffer.append(choice.getMessage().getContent()));
        Long endTime = System.currentTimeMillis();
        log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
        return stringBuffer.toString();
    }

    @Override
    public String aiGen2(String systemPrompt, Double temperature) {
        try {
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", contextCachingModel);
            JSONArray messages = new JSONArray();
            JSONObject message = new JSONObject();
            message.put("role", ChatMessageRole.USER.value());
            message.put("content", systemPrompt);
            messages.add(message);
            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            //设置温度值
            if(temperature != null) {
                requestBody.put("temperature", temperature);
            }
            log.info("===> aiGen body : {}", requestBody);
            HttpResponse<String> response = Unirest.post(chatUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> aiGen result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
            return content;
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String aiGen3(String systemPrompt, String model, Double temperature, Double topp) {
        try {
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            if(StringUtils.isNotEmpty(model)) {
                requestBody.put("model", model);
            } else {
                //chatgpt 模型
                requestBody.put("model", "ep-20250917134025-t2hfr");
                //1.6 模型
//            requestBody.put("model", "ep-20250924173624-7r6kb");
            }
            JSONArray messages = new JSONArray();
            JSONObject message = new JSONObject();
            message.put("role", ChatMessageRole.USER.value());
            message.put("content", systemPrompt);
            messages.add(message);
            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            //设置温度值
            requestBody.put("temperature", temperature != null ? temperature : 1.0f);
            //召回率
            requestBody.put("top_p", topp != null ? topp : 0.7f);
            log.info("===> aiGen body : {}", requestBody);
            HttpResponse<String> response = Unirest.post(chatUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> aiGen result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
            return content;
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AiGen4Bo aiGen4(String systemPrompt, String model, Double temperature, Double topp) {
        try {
            AiGen4Bo aiGen4Bo = new AiGen4Bo();
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            if(StringUtils.isNotEmpty(model)) {
                requestBody.put("model", model);
            } else {
                //chatgpt 模型
                requestBody.put("model", "ep-20250917134025-t2hfr");
                //1.6 模型
//            requestBody.put("model", "ep-20250924173624-7r6kb");
            }
            JSONArray messages = new JSONArray();
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", ChatMessageRole.SYSTEM.value());
            systemMessage.put("content", systemPrompt);
            messages.add(systemMessage);

            JSONObject userMessage = new JSONObject();
            userMessage.put("role", ChatMessageRole.USER.value());
            userMessage.put("content", "生成");
            messages.add(userMessage);

            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            //设置温度值
            requestBody.put("temperature", temperature != null ? temperature : 1.0f);
            //召回率
            requestBody.put("top_p", topp != null ? topp : 0.7f);
            aiGen4Bo.setInput(requestBody.toString());
            log.info("===> aiGen body : {}", requestBody);
            HttpResponse<String> response = Unirest.post(chatUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            aiGen4Bo.setOutput(result);
            aiGen4Bo.setUrl(chatUrl);
            aiGen4Bo.setApikey(apiKey);
            log.info("===> aiGen result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
            aiGen4Bo.setContent(content);
            return aiGen4Bo;
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用deepseek
     *
     * @param chatMessageList
     * @param temperature
     * @return
     */
    @Override
    public String aiGen4(List<ChatCompletionMessage> chatMessageList, Double temperature) {
        try {
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            //使用deepseek
            requestBody.put("model", "ep-20250910114251-szxqk");
            requestBody.put("messages", chatMessageList);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            //设置温度值
            if(temperature != null) {
                requestBody.put("temperature", temperature);
            }
            log.info("===> aiGen body : {}", requestBody);
            HttpResponse<String> response = Unirest.post(chatUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> aiGen result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
            return content;
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void nsfwCheck(String userContent) {
        boolean checkPass = true;
        String content1 = "";
        try {
            String systemPrompt = "你是一位资深的敏感词校验工程师\n" +
                    "\n" +
                    "\n" +
                    "请你校验用户输入的文本内容是否包含违反法律、伦理或社会道德的敏感内容\n" +
                    "\n" +
                    "\n" +
                    "审核时必须符合以下'/guide/' 标签内的审查规则：\n" +
                    "\n" +
                    "\n" +
                    "<guide>\n" +
                    "1. 禁止儿童性虐待材料：任何描绘或暗示未成年人的性行为或性暗示的内容。\n" +
                    "2. 禁止宣扬恐怖主义：包含恐怖组织标志、宣传材料、恐怖行为实录或指导的内容。\n" +
                    "3. 禁止描绘现实中存在的名人，公众人物\n" +
                    "4. 禁止描述真实存在的引人不适的血腥暴力场景：如肢解、斩首、内脏暴露、大规模血腥事故、战争实录的血腥特写等。\n" +
                    "5.禁止描述残酷的虐待与折磨：对人类或动物进行极端虐待、折磨致残或致死的写实内容。\n" +
                    "6.禁止描述自残与自杀：描绘或鼓励自残、自杀的写实方法或过程的内容。\n" +
                    "5. 禁止描述性暴力：描绘强奸、非自愿捆绑、下药等任何非自愿性行为的内容。\n" +
                    "7.禁止描述性虐待（BDSM中的硬核内容）：即使看似“自愿”，也禁止包含极端疼痛、羞辱、可能导致永久身体伤害的行为（如窒息、重度穿刺、伤口性行为等）。\n" +
                    "8.禁止描述恋物癖与排泄物：禁止涉及粪便（Scatology）、尿液（Urolagnia）、极端身体改造等内容的色情图片。\n" +
                    "9.禁止描述兽交（Zoophilia）：任何人与动物发生性行为的内容。\n" +
                    "10.禁止直接描绘性行为（性交、自慰等行为动作描述）。禁止描述性玩具的使用。禁止特写性器官。\n" +
                    "11. 禁止基于种族、民族、宗教、国籍、性别、性取向、残疾等，宣扬仇恨、进行非人化侮辱或煽动暴力的内容。\n" +
                    "</guide>\n" +
                    "\n" +
                    "\n" +
                    "注意，对以下’/whitelist/' 中内容可以放行\n" +
                    "\n" +
                    "\n" +
                    "<whitelist>\n" +
                    "\n" +
                    "对于非裸露的身材描述予以放过，即使带有轻度的暗示，例如饱满的胸部，圆润的臀部等\n" +
                    "\n" +
                    "对于并基于现实的，属于文学创作的描写，如虚构的犯罪、暴力事件，适度的恐怖，血腥，战争等场景描述\n" +
                    "\n" +
                    "</whitelist>\n" +
                    "\n" +
                    "\n" +
                    "\n" +
                    "\n" +
                    "输出遵循以下’/output/’中规则：\n" +
                    "\n" +
                    "\n" +
                    "<output>\n" +
                    "违规命中的敏感词或短句，以json格式输出，示例如下：\n" +
                    "{\\\"checkPass\\\": false, \\\"content\\”:\\”nude body\\”}\n" +
                    "\n" +
                    "\n" +
                    "字段说明：checkPass布尔值，包含敏感词为false、不包含敏感词为true。content为字符类型，里面填充的是你检测到的所有的敏感词\n" +
                    "\n" +
                    "\n" +
                    "<output>";
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "ep-20250917134025-t2hfr");
            JSONArray messages = new JSONArray();
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", ChatMessageRole.SYSTEM.value());
            systemMessage.put("content", systemPrompt);
            messages.add(systemMessage);
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", ChatMessageRole.USER.value());
            userMessage.put("content", userContent);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            log.info("===> nsfwCheck body : {}", requestBody);
            HttpResponse<String> response = Unirest.post("https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions")
                    .header("Authorization", "Bearer " + "4075846b-cb9e-45f6-bf59-ab0a94745d9b")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> nsfwCheck result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> nsfwCheck time : {}", (endTime - startTime) / 1000);
            System.out.println(content);
            JSONObject jsonObject1 = JSONObject.parseObject(content);
            checkPass = jsonObject1.getBoolean("checkPass");
            content1 = jsonObject1.getString("content");
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("===> nsfwCheck error : ", e);
        }
        //判断是否抛出异常
        ToastResultCode.NSWF_ERROR.check(!checkPass, String.format(ToastResultCode.NSWF_ERROR.getErrorMsg(), content1));
    }

    @Override
    public String nsfwCheckV2(String userContent) {
        boolean checkPass = true;
        String content1 = "";
        try {
            String systemPrompt = "你是一位资深的敏感词校验工程师，请你校验用户输入的文本内容是否包含敏感词汇，除生殖器官用词以外的色情用词都可以认定为不包含敏感词，并将命中的结果以json格式输出，示例如下：{\"checkPass\": false, \"content\":\"fuck\"}" +
                    "字段说明：checkPass布尔值，包含敏感词为false、不包含敏感词为true。content为字符类型，里面填充的是你检测到的所有的敏感词";
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "ep-20250917134025-t2hfr");
            JSONArray messages = new JSONArray();
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", ChatMessageRole.SYSTEM.value());
            systemMessage.put("content", systemPrompt);
            messages.add(systemMessage);
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", ChatMessageRole.USER.value());
            userMessage.put("content", userContent);
            messages.add(userMessage);
            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            log.info("===> nsfwCheck body : {}", requestBody);
            HttpResponse<String> response = Unirest.post("https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions")
                    .header("Authorization", "Bearer " + "4075846b-cb9e-45f6-bf59-ab0a94745d9b")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> nsfwCheck result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> nsfwCheck time : {}", (endTime - startTime) / 1000);
            System.out.println(content);
            JSONObject jsonObject1 = JSONObject.parseObject(content);
            checkPass = jsonObject1.getBoolean("checkPass");
            content1 = jsonObject1.getString("content");
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            log.error("===> nsfwCheck error : ", e);
        }
        return content1;
    }

    public static void main(String[] args) {
        try {
            String systemPrompt = "你是一位资深的敏感词校验工程师，请你校验用户输入的文本内容是否包含敏感词汇，并将命中的结果以json格式输出，示例如下：{\"checkPass\": false, \"content\":\"fuck\"}" +
                    "字段说明：checkPass布尔值，包含敏感词为false、不包含敏感词为true。content为字符类型，里面填充的是你检测到的所有的敏感词";
            Long startTime = System.currentTimeMillis();
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "ep-20250917134025-t2hfr");
            JSONArray messages = new JSONArray();
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", ChatMessageRole.SYSTEM.value());
            systemMessage.put("content", systemPrompt);
            messages.add(systemMessage);
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", ChatMessageRole.USER.value());
            userMessage.put("content", "今天天气好哟，我日你，我草死你，你个婊子，奥巴马");
            messages.add(userMessage);
            requestBody.put("messages", messages);
            JSONObject thinking = new JSONObject();
            thinking.put("type", "disabled");
            requestBody.put("thinking", thinking);
            log.info("===> aiGen body : {}", requestBody);
            HttpResponse<String> response = Unirest.post("https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions")
                    .header("Authorization", "Bearer " + "4075846b-cb9e-45f6-bf59-ab0a94745d9b")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asString();
            String result = response.getBody();
            log.info("===> aiGen result : {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String content = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            Long endTime = System.currentTimeMillis();
            log.info("===> aiGen time : {}", (endTime - startTime) / 1000);
            System.out.println(content);
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
    }

}
