"""T5.4 多 provider 记账维度（ARCH §4.8）。

记账行须带**实际服务方** provider/model（回退后不能记成主模型），让 usage_ledger
的多 provider 维度可查询/聚合。
"""

from __future__ import annotations

from fakes_resilience import FakeLedger, ScriptedAdapter, chain, chain_resolver, transient
from ww_llm_gateway.gateway import Gateway
from ww_llm_gateway.types import LlmRequest


async def test_ledger_records_actual_serving_provider_after_fallback(req: LlmRequest) -> None:
    primary = ScriptedAdapter("deepseek", failures=[transient() for _ in range(10)])
    backup = ScriptedAdapter("openai", text="备用", input_tokens=222, output_tokens=33)
    ledger = FakeLedger()
    gw = Gateway(
        {"deepseek": primary, "openai": backup},
        ledger,
        chain_resolver=chain_resolver(chain(("deepseek", "deepseek-chat"), ("openai", "gpt-4o"))),
        max_retries=1,
    )

    await gw.run(req)

    assert len(ledger.records) == 1
    rec = ledger.records[0]
    assert rec.provider == "openai"
    assert rec.model == "gpt-4o"
    assert rec.input_tokens == 222
    assert rec.output_tokens == 33


async def test_stream_ledger_records_actual_provider_after_fallback(req: LlmRequest) -> None:
    primary = ScriptedAdapter("deepseek", failures=[transient() for _ in range(10)])
    backup = ScriptedAdapter("openai", text="流式备用", input_tokens=10, output_tokens=4)
    ledger = FakeLedger()
    gw = Gateway(
        {"deepseek": primary, "openai": backup},
        ledger,
        chain_resolver=chain_resolver(chain(("deepseek", "deepseek-chat"), ("openai", "gpt-4o"))),
        max_retries=1,
    )

    collected = [d.text async for d in gw.stream(req)]

    assert "".join(collected) == "流式备用"
    assert len(ledger.records) == 1
    assert ledger.records[0].provider == "openai"
    assert ledger.records[0].model == "gpt-4o"
