"""
Unit tests for langchain_agentx.provider.CompatibleChatOpenAI
=============================================================

这里只验证「从原始 chunk 中抽取 reasoning_content → 写入 additional_kwargs」这块逻辑，
不依赖 CodeBaseX 其它目录的代码。
"""

from __future__ import annotations

from typing import Any, Dict

import pytest

from langchain_core.messages import AIMessageChunk

from langchain_agentx.provider import CompatibleChatOpenAI


@pytest.mark.parametrize("rc", ["首先", "然后"])
def test_convert_chunk_writes_reasoning_content(rc: str) -> None:
    """带 reasoning_content 的 chunk，应被写入 additional_kwargs['reasoning_content']。"""
    # 使用最小参数构造实例；真正的 HTTP 客户端创建在调用时才发生，这里只调用内部转换函数。
    llm = CompatibleChatOpenAI(
        model="dummy-model",
        api_key="dummy",
        base_url="http://dummy",
        streaming=True,
    )

    base_info: Dict[str, Any] = {}
    chunk: Dict[str, Any] = {
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "dummy-model",
        "choices": [
            {
                "index": 0,
                "finish_reason": None,
                "delta": {
                    "role": "assistant",
                    "content": None,
                    "reasoning_content": rc,
                },
            }
        ],
    }

    gen_chunk = llm._convert_chunk_to_generation_chunk(  # type: ignore[attr-defined]
        chunk, AIMessageChunk, base_info
    )
    assert gen_chunk is not None
    msg = gen_chunk.message
    assert isinstance(msg, AIMessageChunk)
    assert msg.additional_kwargs.get("reasoning_content") == rc


def test_convert_chunk_without_reasoning_does_not_set_field() -> None:
    """当 chunk 没有 reasoning_content 时，不应设置该字段。"""
    llm = CompatibleChatOpenAI(
        model="dummy-model",
        api_key="dummy",
        base_url="http://dummy",
        streaming=True,
    )

    base_info: Dict[str, Any] = {}
    chunk: Dict[str, Any] = {
        "id": "chatcmpl-empty",
        "object": "chat.completion.chunk",
        "model": "dummy-model",
        "choices": [
            {
                "index": 0,
                "finish_reason": None,
                "delta": {
                    "role": "assistant",
                    "content": None,
                },
            }
        ],
    }

    gen_chunk = llm._convert_chunk_to_generation_chunk(  # type: ignore[attr-defined]
        chunk, AIMessageChunk, base_info
    )
    assert gen_chunk is not None
    msg = gen_chunk.message
    assert isinstance(msg, AIMessageChunk)
    assert "reasoning_content" not in msg.additional_kwargs

