# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-tool-call-span-when-its-parent-context-is-a-foreign-trace-continuation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-tool-call-span-when-its-parent-context-is-a-foreign-trace-continuation.warrant.json
# Markdown SHA-256:   ca0526df3b9410bc432115c02f1a5d901fec21b15c6db3ccc81ed800c6368c15
# Code AST SHA-256:   af3932ee667f21ba2fedae61533dd806e7cbeab80371643bd392be9b04201299
# Verified Classes:   ForeignTraceAccountingError, AttributionMode, SpanContext, GenAIUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ForeignTraceAccountingError(RuntimeError):
    """Raised when a GenAI span would emit cumulative usage on a foreign-parented trace."""


class AttributionMode(str, Enum):
    CUMULATIVE = "cumulative"
    DELTA = "delta"
    SUPPRESS = "suppress"


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    is_remote: bool


@dataclass(frozen=True)
class GenAIUsage:
    input_tokens: int
    output_tokens: int
    replayed_prefix_tokens: int = 0


def resolve_attribution_mode(
    ctx: SpanContext,
    local_root_registry: frozenset[str],
    policy: AttributionMode = AttributionMode.DELTA,
) -> AttributionMode:
    owns_trace = (not ctx.is_remote) and (ctx.trace_id in local_root_registry)
    if owns_trace:
        return AttributionMode.CUMULATIVE
    if policy is AttributionMode.CUMULATIVE:
        # Caller asked for cumulative on a continuation span: hard refusal.
        raise ForeignTraceAccountingError(
            f"refusing cumulative gen_ai.usage on remote-parented trace "
            f"{ctx.trace_id}: would double-count replayed prefix"
        )
    return policy


def build_usage_attributes(
    ctx: SpanContext,
    usage: GenAIUsage,
    local_root_registry: frozenset[str],
    policy: AttributionMode = AttributionMode.DELTA,
) -> dict[str, int | str]:
    mode = resolve_attribution_mode(ctx, local_root_registry, policy)

    if mode is AttributionMode.CUMULATIVE:
        return {
            "gen_ai.usage.input_tokens": usage.input_tokens,
            "gen_ai.usage.output_tokens": usage.output_tokens,
            "gen_ai.usage.attribution": "cumulative",
        }

    if mode is AttributionMode.DELTA:
        attributable = usage.input_tokens - usage.replayed_prefix_tokens
        if attributable < 0:
            raise ForeignTraceAccountingError(
                f"replayed_prefix_tokens ({usage.replayed_prefix_tokens}) exceeds "
                f"input_tokens ({usage.input_tokens}) on trace {ctx.trace_id}; "
                f"delta attribution would be negative"
            )
        return {
            "gen_ai.usage.input_tokens": attributable,
            "gen_ai.usage.output_tokens": usage.output_tokens,
            "gen_ai.usage.replayed_prefix_tokens": usage.replayed_prefix_tokens,
            "gen_ai.usage.attribution": "delta",
        }

    # SUPPRESS: emit no usage attributes at all on a continuation span.
    return {"gen_ai.usage.attribution": "suppressed"}
