"""接线测试：`kimi-code-key` 作为**普通 api_key** provider 经既有路径建干净 coding 适配器。

不联网。与 OAuth 的 `kimi-code` 对照——`kimi-code-key`：
- 走 api_key 凭据路径（Fernet `api_key_enc`），**不**触发 OAuth 刷新分支；
- `build_gateway_for_tier` 据 DB `tier_routing` 路由 → `_build_provider_adapter` →
  `build_adapter("kimi-code-key", ...)` → `KimiCodeKeyAdapter`（coding base + 纯 bearer）；
- 适配器**不带**伪造 UA / X-Msh-* 头，结构化走 JSON 模式。
"""

from __future__ import annotations

import os

import pytest
from fakes_projects import FakeSession
from fakes_providers import FakeCredentialStore
from ww_api.services.credentials import STUB_OWNER_ID, StoredRouting
from ww_api.services.project_deps import _build_provider_adapter, build_gateway_for_tier
from ww_llm_gateway.adapters.kimi_code_key import KIMI_CODE_KEY_PROVIDER, KimiCodeKeyAdapter

_ENC_KEY = "imB6TEcV2AzlpXjR4NjTgK_9Zt-OoqaLFQc3XqBQ0CQ="
_API_KEY = "kimi-console-static-key-not-real"


def _set_env() -> None:
    os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
    from ww_config import get_settings

    get_settings.cache_clear()


def _store_with_key() -> FakeCredentialStore:
    from ww_api.security.credentials import encrypt_api_key

    store = FakeCredentialStore()
    store.creds[(STUB_OWNER_ID, KIMI_CODE_KEY_PROVIDER)] = encrypt_api_key(_API_KEY, key=_ENC_KEY)
    return store


@pytest.mark.asyncio
async def test_build_provider_adapter_for_kimi_code_key_sends_spoofed_headers() -> None:
    _set_env()
    store = _store_with_key()

    adapter = await _build_provider_adapter(store, KIMI_CODE_KEY_PROVIDER)

    assert isinstance(adapter, KimiCodeKeyAdapter)
    assert adapter.provider == "kimi-code-key"
    client = adapter._client  # noqa: SLF001
    assert str(client.base_url).rstrip("/") == "https://api.kimi.com/coding/v1"
    assert client.api_key == _API_KEY
    # 实测：coding 端点据 UA 做 allow-list 门禁，缺伪造头→403，故静态 key 也必须发伪造头。
    headers = client.default_headers
    assert any(str(k).lower().startswith("x-msh-") for k in headers)
    assert "KimiCLI" in str(headers.get("User-Agent", ""))


@pytest.mark.asyncio
async def test_build_gateway_for_tier_routes_kimi_code_key_for_coding_model() -> None:
    _set_env()
    store = _store_with_key()
    # 把 writer 档位路由到 kimi-code-key:kimi-for-coding（无回退）。
    store.routing["writer"] = StoredRouting(
        tier="writer",
        provider=KIMI_CODE_KEY_PROVIDER,
        model="kimi-for-coding",
        fallback=[],
    )

    gateway = await build_gateway_for_tier(FakeSession(), store, "writer")

    assert set(gateway._adapters) == {KIMI_CODE_KEY_PROVIDER}  # noqa: SLF001
    adapter = gateway._adapters[KIMI_CODE_KEY_PROVIDER]  # noqa: SLF001
    assert isinstance(adapter, KimiCodeKeyAdapter)
    chain = gateway._resolve_chain("writer")  # noqa: SLF001
    assert [r.provider for r in chain] == [KIMI_CODE_KEY_PROVIDER]
    assert chain[0].model == "kimi-for-coding"
