package com.easyagents.core.test.parser;

import com.alibaba.fastjson2.JSON;
import com.easyagents.core.message.AiMessage;
import com.easyagents.core.model.chat.ChatContext;
import com.easyagents.core.model.chat.ChatOptions;
import com.easyagents.core.parser.impl.DefaultAiMessageParser;
import org.junit.Assert;
import org.junit.Test;

/**
 * OpenAI-compatible AI 消息解析测试。
 */
public class DefaultAiMessageParserTest {

    /**
     * 验证非流式响应同时填充当前内容和完整内容。
     */
    @Test
    public void nonStreamingResponseShouldPopulateCompleteContent() {
        String response = """
                {
                  "choices": [{
                    "message": {
                      "content": "2026",
                      "reasoning_content": "读取图片中的数字"
                    },
                    "index": 0,
                    "finish_reason": "stop"
                  }],
                  "usage": {
                    "prompt_tokens": 221,
                    "completion_tokens": 51,
                    "total_tokens": 272
                  }
                }
                """;

        AiMessage message = DefaultAiMessageParser.getOpenAIMessageParser()
                .parse(JSON.parseObject(response), context(false));

        Assert.assertEquals("2026", message.getContent());
        Assert.assertEquals("2026", message.getFullContent());
        Assert.assertEquals("2026", message.getTextContent());
        Assert.assertEquals("读取图片中的数字", message.getReasoningContent());
        Assert.assertEquals("读取图片中的数字", message.getFullReasoningContent());
        Assert.assertEquals(Integer.valueOf(272), message.getTotalTokens());
    }

    /**
     * 验证流式解析继续暴露原始增量内容。
     */
    @Test
    public void streamingResponseShouldKeepDeltaContent() {
        String response = """
                {
                  "choices": [{
                    "delta": {
                      "content": "20",
                      "reasoning_content": "读取"
                    },
                    "index": 0
                  }]
                }
                """;

        AiMessage message = DefaultAiMessageParser.getOpenAIMessageParser()
                .parse(JSON.parseObject(response), context(true));

        Assert.assertEquals("20", message.getContent());
        Assert.assertEquals("读取", message.getReasoningContent());
    }

    /**
     * 创建指定流式模式的解析上下文。
     *
     * @param streaming 是否解析流式增量
     * @return 解析上下文
     */
    private ChatContext context(boolean streaming) {
        ChatOptions options = new ChatOptions();
        options.setStreaming(streaming);
        ChatContext context = new ChatContext();
        context.setOptions(options);
        return context;
    }
}
