"""T5.2/T5.4 接线：`build_gateway_for_tier` 据 DB tier_routing 装配多 provider 回退链。

不联网：只断言网关被装配了**多个适配器** + 注入了回退链解析器（chain_resolver），
故链长 > 1。真实回退/降级行为由 packages/llm_gateway 单测 + T5.7 E2E 覆盖。
"""

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

# 真 Fernet key（测试加解密凭据用；仅本测试，非生产密钥）。
_ENC_KEY = "imB6TEcV2AzlpXjR4NjTgK_9Zt-OoqaLFQc3XqBQ0CQ="


def _store_with_creds(*providers: str) -> FakeCredentialStore:
    from ww_api.security.credentials import encrypt_api_key

    store = FakeCredentialStore()
    for p in providers:
        store.creds[(STUB_OWNER_ID, p)] = encrypt_api_key("sk-test", key=_ENC_KEY)
    return store


@pytest.mark.asyncio
async def test_build_gateway_wires_fallback_chain_with_multiple_adapters() -> None:
    os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
    from ww_config import get_settings

    get_settings.cache_clear()
    from ww_api.services.project_deps import build_gateway_for_tier

    store = _store_with_creds("deepseek", "kimi")
    store.routing["writer"] = StoredRouting(
        tier="writer", provider="deepseek", model="deepseek-chat", fallback=["kimi:moonshot-v1-8k"]
    )

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

    # 两个 provider 的适配器都装配进网关 → 回退链可绕过首个失败者。
    assert set(gateway._adapters) == {"deepseek", "kimi"}  # noqa: SLF001
    # chain_resolver 注入 → 链长 2（去重保序）。
    chain = gateway._resolve_chain("writer")  # noqa: SLF001
    assert [r.provider for r in chain] == ["deepseek", "kimi"]


@pytest.mark.asyncio
async def test_build_gateway_single_provider_still_works() -> None:
    """无 fallback 的路由行：单元素链（M1 行为不变，向后兼容）。"""
    os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
    from ww_config import get_settings

    get_settings.cache_clear()
    from ww_api.services.project_deps import build_gateway_for_tier

    store = _store_with_creds("deepseek")
    store.routing["analyst"] = StoredRouting(
        tier="analyst", provider="deepseek", model="deepseek-chat", fallback=[]
    )

    gateway = await build_gateway_for_tier(FakeSession(), store, "analyst")
    assert set(gateway._adapters) == {"deepseek"}  # noqa: SLF001
    chain = gateway._resolve_chain("analyst")  # noqa: SLF001
    assert len(chain) == 1


@pytest.mark.asyncio
async def test_build_gateway_no_routing_row_falls_back_to_global_default() -> None:
    """无 DB 路由行 → 退回全局 resolve_route（单 provider）。"""
    os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
    from ww_config import get_settings

    get_settings.cache_clear()
    from ww_api.services.project_deps import build_gateway_for_tier

    store = _store_with_creds("deepseek")  # 无 routing 行
    gateway = await build_gateway_for_tier(FakeSession(), store, "writer")
    assert "deepseek" in gateway._adapters  # noqa: SLF001


@pytest.mark.asyncio
async def test_build_gateway_no_usable_credentials_raises_503() -> None:
    os.environ["CREDENTIAL_ENC_KEY"] = _ENC_KEY
    from ww_config import get_settings

    get_settings.cache_clear()
    from ww_api.services.project_deps import build_gateway_for_tier
    from ww_shared import AppError, ErrorCode

    store = FakeCredentialStore()  # 无任何凭据
    store.routing["writer"] = StoredRouting(
        tier="writer", provider="deepseek", model="deepseek-chat", fallback=["kimi:moonshot-v1-8k"]
    )
    with pytest.raises(AppError) as exc:
        await build_gateway_for_tier(FakeSession(), store, "writer")
    assert exc.value.code == ErrorCode.LLM_UNAVAILABLE
