# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-when-gen-ai-usage-output-tokens-is-a-post-hoc-estimate-rather-than-a-counted-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-when-gen-ai-usage-output-tokens-is-a-post-hoc-estimate-rather-than-a-counted-emission.warrant.json
# Markdown SHA-256:   288d5800c39696a1e6032a16d0ac667a4d941fe82537daaaa550776e0116d6df
# Code AST SHA-256:   8cefa389be6573187fc92b9e3221ca10a16f9f5cf360bf5736b1a0f6483e7ee0
# Verified Classes:   UsageProvenance, ChildUsage, UsageAggregationError, ParentUsageDecision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class UsageProvenance(Enum):
    PROVIDER_REPORTED = "provider_reported"
    TOKENIZER_ESTIMATE = "tokenizer_estimate"
    STREAM_DELTA_SUM = "stream_delta_sum"


@dataclass
class ChildUsage:
    span_id: str
    output_tokens: int
    provenance: UsageProvenance
    request_id: Optional[str] = None
    ended: bool = True


class UsageAggregationError(RuntimeError):
    """Raised when a parent GenAI span cannot honestly aggregate child usage."""


@dataclass
class ParentUsageDecision:
    emit_usage: bool
    output_tokens: Optional[int]
    reason: Optional[str] = None
    estimated: bool = False


def aggregate_parent_usage(
    expected_children: int,
    children: list[ChildUsage],
) -> ParentUsageDecision:
    ended = [c for c in children if c.ended]
    if len(ended) < expected_children:
        raise UsageAggregationError(
            f"parent launched {expected_children} child calls but only "
            f"{len(ended)} ended; refusing to emit additive usage over an "
            f"incomplete tree"
        )

    provenances = {c.provenance for c in ended if c.output_tokens > 0}
    if len(provenances) > 1:
        raise UsageAggregationError(
            f"mixed usage provenance {sorted(p.value for p in provenances)}; "
            f"summing across provenance classes yields a self-consistent "
            f"but externally wrong aggregate"
        )

    seen_requests: dict[str, int] = {}
    for c in ended:
        if c.request_id is not None and c.output_tokens > 0:
            seen_requests[c.request_id] = seen_requests.get(c.request_id, 0) + 1
    overlapping = [rid for rid, n in seen_requests.items() if n > 1]
    if overlapping:
        raise UsageAggregationError(
            f"retry overlap on request(s) {overlapping}: more than one child "
            f"with nonzero output_tokens shares a request id; parent sum "
            f"would double-count"
        )

    total = sum(c.output_tokens for c in ended)
    if provenances == {UsageProvenance.PROVIDER_REPORTED}:
        return ParentUsageDecision(emit_usage=True, output_tokens=total)
    if not provenances:
        return ParentUsageDecision(emit_usage=True, output_tokens=0)
    return ParentUsageDecision(
        emit_usage=True,
        output_tokens=total,
        reason="all children estimated; parent marked non-authoritative",
        estimated=True,
    )


def end_agent_span(
    expected_children: int,
    children: list[ChildUsage],
    strict: bool = True,
) -> ParentUsageDecision:
    try:
        return aggregate_parent_usage(expected_children, children)
    except UsageAggregationError:
        if strict:
            raise
        # non-strict mode: withhold usage, attach diagnostic event, do not fake a number
        return ParentUsageDecision(
            emit_usage=False,
            output_tokens=None,
            reason="aggregation_skipped",
        )
