# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-across-a-retried-tool-call-span-when-genai-semantic-conventions-fork-the-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-across-a-retried-tool-call-span-when-genai-semantic-conventions-fork-the-trace.warrant.json
# Markdown SHA-256:   75068f6f576075e6d32cdd6a7d60ba706d781877380f2788d8afee72f5679436
# Code AST SHA-256:   84f273ff24976fdb5a5a977ce456791543eacec88173344cabb85dfde239001d
# Verified Classes:   OrphanUsageAttributionError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanUsageAttributionError(RuntimeError):
    """Raised when token usage cannot be bound to a resolvable response model."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    operation_id: Optional[str]
    input_tokens: int
    output_tokens: int
    response_model: Optional[str]
    request_model: str


PRICE_TABLE = {
    "gpt-4o-2024-08-06": {"input": 2.50e-6, "output": 10.00e-6},
    "gpt-4o-mini": {"input": 0.15e-6, "output": 0.60e-6},
}


def attribute_operation_cost(spans: list[GenAISpan]) -> dict:
    if not spans:
        return {"total_usd": 0.0, "orphan_tokens": 0, "priced_spans": 0}

    operation_ids = {s.operation_id for s in spans}
    if len(operation_ids) != 1 or None in operation_ids:
        raise OrphanUsageAttributionError(
            f"Cannot group spans: operation_id set is {operation_ids}; "
            "retry lineage is not reconstructable."
        )

    resolved = [s for s in spans if s.response_model is not None]
    orphans = [s for s in spans if s.response_model is None]

    if not resolved:
        raise OrphanUsageAttributionError(
            "No span in operation resolved a response model; "
            "cost cannot be bounded without a pricing anchor."
        )

    anchor_model = resolved[0].response_model
    if anchor_model not in PRICE_TABLE:
        raise OrphanUsageAttributionError(
            f"Pricing anchor model {anchor_model!r} absent from price table; "
            "refusing to emit a priced total."
        )

    total = 0.0
    for s in resolved:
        if s.response_model not in PRICE_TABLE:
            raise OrphanUsageAttributionError(
                f"Resolved span {s.span_id} model {s.response_model!r} unpriced."
            )
        p = PRICE_TABLE[s.response_model]
        total += s.input_tokens * p["input"] + s.output_tokens * p["output"]

    orphan_tokens = sum(s.input_tokens for s in orphans)
    if orphan_tokens:
        anchor_price = PRICE_TABLE[anchor_model]["input"]
        total += orphan_tokens * anchor_price

    return {
        "total_usd": round(total, 8),
        "orphan_tokens": orphan_tokens,
        "priced_spans": len(resolved),
        "anchor_model": anchor_model,
    }
