# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-genai-semantic-convention-token-counts-as-non-attributable-to-the-emitting-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-genai-semantic-convention-token-counts-as-non-attributable-to-the-emitting-tool-call.warrant.json
# Markdown SHA-256:   bae15becda04e6a1e2347f7666f5cadba35ab52059c510bb4768eea9ef35899d
# Code AST SHA-256:   120137c4703677f2bfa4f375594bdc2f3fa2156242e98beb2eeb14a39bd1e671
# Verified Classes:   TokenAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TokenAttributionError(RuntimeError):
    """Raised when a span tree cannot be attributed without violating the typing invariant."""
    pass


TOOL_ATTR = "gen_ai.tool.name"
OP_ATTR = "gen_ai.operation.name"
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")


def attribute_turn_tokens(spans: list[dict]) -> dict:
    """
    spans: list of span dicts with keys: span_id, parent_span_id, attributes.
    Returns {"turn_tokens": int, "per_tool_tool_cost": {tool: int}, "model_spans": int}.
    Raises TokenAttributionError if a tool span carries usage attrs, or if a
    model span is missing usage attrs entirely (must fail closed, not estimate).
    """
    usage_by_model_span = {}
    tool_spans = []

    for s in spans:
        attrs = s.get("attributes", {})
        is_tool = TOOL_ATTR in attrs
        is_model = OP_ATTR in attrs and attrs[OP_ATTR] in ("chat", "text_completion", "embeddings")

        if is_tool and any(k in attrs for k in USAGE_KEYS):
            raise TokenAttributionError(
                f"tool span {s['span_id']} ({attrs[TOOL_ATTR]}) carries usage attrs; "
                "usage belongs to the model span, not the tool span"
            )
        if is_model:
            missing = [k for k in USAGE_KEYS if k not in attrs]
            if missing:
                raise TokenAttributionError(
                    f"model span {s['span_id']} missing {missing}; "
                    "refusing to estimate — span may have exported before completion"
                )
            usage_by_model_span[s["span_id"]] = sum(attrs[k] for k in USAGE_KEYS)
        if is_tool:
            tool_spans.append(s)

    # Invariant: no tool span may be an ancestor of a model span whose usage
    # we are about to sum. If it is, the tree is malformed for attribution.
    model_ids = set(usage_by_model_span)
    for s in spans:
        if s["span_id"] in model_ids:
            parent = s.get("parent_span_id")
            for t in tool_spans:
                if t["span_id"] == parent:
                    raise TokenAttributionError(
                        f"model span {s['span_id']} is nested under tool span {parent}; "
                        "usage cannot be attributed to the tool — it precedes the tool's effect"
                    )

    return {
        "turn_tokens": sum(usage_by_model_span.values()),
        "per_tool_tool_cost": {t["attributes"][TOOL_ATTR]: 0 for t in tool_spans},
        "model_spans": len(model_ids),
    }
