"""工厂分派 `kimi-code` 单测（K1.2）：access_token 当 api_key、完整 7 伪造头、coding base。

不联网。
"""

from __future__ import annotations

import pytest
from ww_llm_gateway import build_adapter
from ww_llm_gateway.adapters.kimi_code import (
    KIMI_CODE_BASE_URL,
    KIMI_CODE_USER_AGENT,
    KimiCodeAdapter,
)

_ACCESS_TOKEN = "kimi-oauth-access-token-not-real"
_TEST_DEVICE_ID = "0123456789abcdef0123456789abcdef"

_EXPECTED_HEADER_KEYS = {
    "User-Agent",
    "X-Msh-Platform",
    "X-Msh-Version",
    "X-Msh-Device-Name",
    "X-Msh-Device-Model",
    "X-Msh-Device-Id",
    "X-Msh-Os-Version",
}


@pytest.fixture(autouse=True)
def _stable_device_id(monkeypatch: pytest.MonkeyPatch) -> None:
    """注入固定 device-id，使测试确定且不依赖真实 ~/.kimi 文件。"""
    monkeypatch.setenv("KIMI_DEVICE_ID", _TEST_DEVICE_ID)


def test_factory_dispatches_kimi_code_to_kimi_code_adapter() -> None:
    adapter = build_adapter("kimi-code", api_key=_ACCESS_TOKEN)

    assert isinstance(adapter, KimiCodeAdapter)
    assert adapter.provider == "kimi-code"


def test_factory_kimi_code_defaults_base_url_and_attaches_full_headers() -> None:
    adapter = build_adapter("kimi-code", api_key=_ACCESS_TOKEN)
    assert isinstance(adapter, KimiCodeAdapter)
    client = adapter._client  # noqa: SLF001 — 断言注入客户端配置

    assert str(client.base_url).rstrip("/") == KIMI_CODE_BASE_URL.rstrip("/")
    assert client.api_key == _ACCESS_TOKEN
    assert client.default_headers["User-Agent"] == KIMI_CODE_USER_AGENT
    assert client.default_headers["X-Msh-Platform"] == "kimi_cli"
    assert client.default_headers["X-Msh-Version"] == "1.37.0"
    assert client.default_headers["X-Msh-Device-Id"] == _TEST_DEVICE_ID
    assert _EXPECTED_HEADER_KEYS.issubset(set(client.default_headers))


def test_factory_kimi_code_honors_explicit_base_url() -> None:
    custom = "https://example.test/coding/v1"
    adapter = build_adapter("kimi-code", api_key=_ACCESS_TOKEN, base_url=custom)
    assert isinstance(adapter, KimiCodeAdapter)

    assert str(adapter._client.base_url).rstrip("/") == custom.rstrip("/")  # noqa: SLF001
