# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-misattributes-child-agent-token-spend-under-inherited-context-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-misattributes-child-agent-token-spend-under-inherited-context-conventions.warrant.json
# Markdown SHA-256:   e7940ad86f2e23e725f3f934f9d612cfaa630703144a349e33559cd53aa29815
# Code AST SHA-256:   551244a0110712e4aceed4908a9acac771cc8741c9ca829e47095241efd18ce5
# Verified Classes:   AttributionConventionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class AttributionConventionError(RuntimeError):
    """Raised when a span's token attribution cannot be resolved under the declared convention."""


@dataclass
class Span:
    span_id: str
    agent_id: str
    input_tokens: int
    output_tokens: int
    parent_span: str | None = None
    inherited_prefix_tokens: int = 0
    convention: str = "per_span"  # "per_span" | "prefix_owned"


def attribute_cost(spans: list[Span], price_per_token: float) -> dict[str, float]:
    by_id = {s.span_id: s for s in spans}
    cost: dict[str, float] = {}

    for s in spans:
        if s.convention == "per_span":
            if s.inherited_prefix_tokens > 0:
                raise AttributionConventionError(
                    f"span {s.span_id} declares inherited prefix of "
                    f"{s.inherited_prefix_tokens} tokens but uses per_span convention; "
                    f"per-span summation would double-count the shared region"
                )
            cost[s.agent_id] = cost.get(s.agent_id, 0.0) + (
                s.input_tokens + s.output_tokens
            ) * price_per_token
        elif s.convention == "prefix_owned":
            if s.inherited_prefix_tokens > s.input_tokens:
                raise AttributionConventionError(
                    f"span {s.span_id} inherited {s.inherited_prefix_tokens} > "
                    f"input {s.input_tokens}; prefix cannot exceed total input"
                )
            marginal = s.input_tokens - s.inherited_prefix_tokens
            cost[s.agent_id] = cost.get(s.agent_id, 0.0) + (
                marginal + s.output_tokens
            ) * price_per_token
            if s.inherited_prefix_tokens and s.parent_span:
                owner = by_id.get(s.parent_span)
                if owner is None:
                    raise AttributionConventionError(
                        f"span {s.span_id} claims inherited prefix from missing "
                        f"parent {s.parent_span}"
                    )
                cost[owner.agent_id] = cost.get(owner.agent_id, 0.0) + (
                    s.inherited_prefix_tokens * price_per_token
                )
        else:
            raise AttributionConventionError(
                f"span {s.span_id} uses unknown convention {s.convention!r}"
            )

    return cost
