"""Which model actually served a request, and what it cost (#118).

A worker used to report `model qwen3.6-coding` — the tier it *asked* for. That cannot
answer "which rung of the ladder solved this task", which on 2026-08-01 turned a
question that should have been a glance at the log into a 100-minute measurement.

Catalog ids carry the cost tier as a prefix (measured against the live gateway
2026-08-02: 246x `[$]`, 15x `[free]`, 4x `[local]`, none bare). The gateway accepts the
prefixed id but echoes the **bare** name back in the response's `model` field — so
`asked` normally carries a tier and `served` normally does not. A missing prefix on
`served` therefore means *no tier information*, NOT a different tier; treating it as a
tier change made every ordinary call report an invented switch to `[unknown]`.

Contract: tests/test_modeltag.py in the build repo, 17 cases, written by @testdesigner
over three rounds (each round closed a defect the previous one could not see — see
`feedback_green_suite_is_not_acceptance`). Implementation ground by @py. The four
if/else pairs that produced identical strings, and one branch made unreachable by the
inherit-tier assignment above it, were collapsed on integration; behaviour is unchanged
and the 17 cases still pass.
"""

_TIERS = ("[local]", "[free]", "[$]")


def _split(model_str):
    """(tier, name) for a catalog id. Tier is None when there is no prefix — which
    means "unknown", not "different"; the caller decides which."""
    model_str = (model_str or "").strip()
    for prefix in _TIERS:
        if model_str.startswith(prefix):
            return prefix.strip("[]"), model_str[len(prefix):].lstrip()
    return None, model_str


def model_tag(asked, served=None, gateway="gateway"):
    """One line naming the gateway, the model that actually served, and its cost tier.

    Args:
        asked:   the requested model id, with or without a catalog tier prefix
        served:  the id that actually served; None means "as asked"
        gateway: name of the gateway that brokered the call

    Returns:
        A single line. A switch is shown when the model name OR the cost tier differs —
        a same-model free->paid escalation is exactly the change this exists to surface.
    """
    if served is None:
        served = asked

    asked_tier, asked_name = _split(asked)
    served_tier, served_name = _split(served)
    asked_tier = asked_tier or "unknown"
    # No prefix on `served` = the gateway did not echo one. Keep the asked tier rather
    # than inventing a change.
    served_tier = served_tier or asked_tier

    base = f"asked={asked_name} (tier={asked_tier})"
    if (asked_name, asked_tier) != (served_name, served_tier):
        return f"{base} -> served={served_name} (tier={served_tier}) [gateway={gateway}]"
    return f"{base} [gateway={gateway}]"
