# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-level-cost-attribution-has-silently-decoupled-from-agent-tool-memory-interaction-boundaries-in-fleet-finops-pipe.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-level-cost-attribution-has-silently-decoupled-from-agent-tool-memory-interaction-boundaries-in-fleet-finops-pipe.warrant.json
# Markdown SHA-256:   ccd80cf6de1b05ef91f9b19438261b11d8fb35f8a309c76fbe8788b6896a9bf3
# Code AST SHA-256:   c3022d48166c2c366702242780657b6f83a9980e592ebc89ba16a2d23e06684e
# Verified Classes:   AttributionDecouplingError, Span, Interaction
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class AttributionDecouplingError(RuntimeError):
    """Raised when a costed span cannot be bound to exactly one interaction."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    agent_id: str
    resource_kind: str  # "llm" | "tool" | "memory"
    cost_usd: float


@dataclass(frozen=True)
class Interaction:
    trace_id: str
    agent_id: str
    root_span_id: str


def build_parent_index(spans: Iterable[Span]) -> dict[str, str | None]:
    return {s.span_id: s.parent_span_id for s in spans}


def resolve_root(span_id: str, parent_index: dict[str, str | None]) -> str:
    seen: set[str] = set()
    cur = span_id
    while parent_index.get(cur) is not None:
        if cur in seen:
            raise AttributionDecouplingError(
                f"cycle detected in span parentage at {cur}"
            )
        seen.add(cur)
        cur = parent_index[cur]
    return cur


def attribute(spans: list[Span], interactions: list[Interaction]) -> dict[str, float]:
    # Join key is (trace_id, agent_id, root_span_id) -- NOT (trace_id, agent_id).
    # Parentage is resolved to the root so nested memory-writes inside tool spans
    # bind to the tool's interaction instead of double-counting.
    index = build_parent_index(spans)
    interaction_by_root = {
        (i.trace_id, i.agent_id, i.root_span_id): i for i in interactions
    }

    ledger: dict[str, float] = {}
    unattributed: list[Span] = []

    for span in spans:
        root = resolve_root(span.span_id, index)
        key = (span.trace_id, span.agent_id, root)
        interaction = interaction_by_root.get(key)
        if interaction is None:
            unattributed.append(span)
            continue
        ledger[interaction.agent_id] = ledger.get(interaction.agent_id, 0.0) + span.cost_usd

    if unattributed:
        # Do NOT fall back to "nearest agent by trace". Quarantine and fail the window.
        total_orphan = sum(s.cost_usd for s in unattributed)
        raise AttributionDecouplingError(
            f"{len(unattributed)} spans (${total_orphan:.4f}) failed injective join; "
            f"attribution window invalid -- re-derive from raw spans with "
            f"parentage-aware join before enforcing budgets"
        )
    return ledger
