# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-span-attributes-that-satisfy-the-schema-but-violate-semantic-convention-cardinality-across-a-resumed-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-span-attributes-that-satisfy-the-schema-but-violate-semantic-convention-cardinality-across-a-resumed-trace.warrant.json
# Markdown SHA-256:   a9e8642cf5d26fb80268015d0ca429b6d498bbdf01062750fac904b4b6ac2184
# Code AST SHA-256:   ffc6ad63685e1d16acb0b87c7d532920fb55cfb8aaf696a61183dbb636b2d8dc
# Verified Classes:   SemanticConventionViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from collections import defaultdict
from dataclasses import dataclass, field


class SemanticConventionViolation(RuntimeError):
    """Raised when a trace is structurally valid but violates a cross-span
    cardinality invariant declared by the GenAI semantic convention."""
    pass


@dataclass
class Span:
    trace_id: str
    name: str
    attributes: dict
    resume_marker: bool = False


TRACE_SCOPED_KEYS = ("gen_ai.conversation.id", "gen_ai.agent.id")
ATTEMPT_SCOPED_KEYS = ("gen_ai.tool.call.id", "gen_ai.request.id")


def check_trace_conformance(spans: list[Span]) -> dict:
    """Enforce trace-scoped key stability and attempt-scoped linkage.
    Returns a deduplicated usage summary or raises SemanticConventionViolation."""
    if not spans:
        return {}

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise SemanticConventionViolation(
            f"expected single trace, got {trace_ids}"
        )

    # Condition 1: trace-scoped keys must be single-valued unless a resume
    # marker explains the divergence.
    for key in TRACE_SCOPED_KEYS:
        values = defaultdict(list)
        for s in spans:
            if key in s.attributes:
                values[s.attributes[key]].append(s)
        if len(values) > 1:
            explained = all(
                any(sp.resume_marker for sp in group)
                for group in values.values()
            )
            if not explained:
                raise SemanticConventionViolation(
                    f"trace-scoped key {key!r} diverges across spans "
                    f"{[v for v in values]} with no resume marker"
                )

    # Condition 2: attempt-scoped keys must be unique or explicitly linked.
    seen_attempts = {}
    for s in spans:
        for key in ATTEMPT_SCOPED_KEYS:
            val = s.attributes.get(key)
            if val is None:
                continue
            if val in seen_attempts:
                retry_of = s.attributes.get("gen_ai.tool.call.retry_of")
                if retry_of != val:
                    raise SemanticConventionViolation(
                        f"duplicate attempt-scoped {key}={val!r} without "
                        f"retry_of linkage"
                    )
            seen_attempts[val] = s

    # Condition 3: deduplicate usage counters across retries before summing.
    usage = defaultdict(int)
    counted = set()
    for s in spans:
        attempt = s.attributes.get("gen_ai.tool.call.id")
        if attempt and attempt in counted:
            continue
        if attempt:
            counted.add(attempt)
        usage["input_tokens"] += s.attributes.get("gen_ai.usage.input_tokens", 0)
        usage["output_tokens"] += s.attributes.get("gen_ai.usage.output_tokens", 0)

    return dict(usage)
