import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Slf4j
public class TestRotWebClient {

    public static String decodeUnicode(String unicodeStr) {
        Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher(unicodeStr);
        StringBuffer decoded = new StringBuffer();

        while (matcher.find()) {
            int charCode = Integer.parseInt(matcher.group(1), 16);
            matcher.appendReplacement(decoded, Character.toString((char) charCode));
        }
        matcher.appendTail(decoded);
        return decoded.toString();
    }


    public static void testRobotRwq() throws IOException {

        WebClient client = WebClient.create("https://agent.wx3.com.cn");

        String bodyStr="{\n" +
                "    \"inputs\": {},\n" +
                "    \"query\": \"周杰伦是谁?\",\n" +
                "    \"response_mode\": \"streaming\",\n" +
                "    \"conversation_id\": \"\",\n" +
                "    \"user\": \"abc-123\",\n" +
                "    \"files\": []\n" +
                "}";

        Flux<String> eventStream = client.post()
                .uri("/v1/chat-messages") // 远程 SSE API
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Accept-Charset", "UTF-8")
                .header("Authorization", "Bearer app-ritPdgkz8bsrfzpcJdSTkUF5")
                .bodyValue(bodyStr) // 发送 JSON 订阅请求
                .retrieve()
                .bodyToFlux(String.class); // 处理流数据

        // 订阅并打印收到的事件
        eventStream.subscribe(event -> System.out.println("Received event: " + decodeUnicode(event)),
                error -> System.err.println("Error: " + error),
                () -> System.out.println("Stream completed"));

        // 保持主线程运行，否则程序可能会立即退出
        while (true) {}
    }


    public static void main(String[] args) throws IOException {


        testRobotRwq();

    }

}
