# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-context-collapse-when-a2a-handoff-spans-are-re-parented-across-agent-runtimes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-context-collapse-when-a2a-handoff-spans-are-re-parented-across-agent-runtimes.warrant.json
# Markdown SHA-256:   9b4c18aaeb7644c77903962db39f0ef0cce953fa561e0a6adb8c7052afc84237
# Code AST SHA-256:   b163982822dd2d7fa32deb628b4d4b1195fcad4fbec8820ca53a9790661b04c7
# Verified Classes:   TraceContextCollapseError, InboundHandoff, EmittedSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceContextCollapseError(RuntimeError):
    """Raised when an inbound A2A handoff would produce a span with neither
    a parent edge nor an explicit link to the caller — the silent re-parenting
    failure that corrupts the agent call graph."""


@dataclass
class InboundHandoff:
    trace_id: str
    span_id: str
    trace_flags: int
    # Transport surfaces the A2A/MCP spec permits for context carriage.
    header_traceparent: Optional[str] = None
    body_metadata_traceparent: Optional[str] = None


@dataclass
class EmittedSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str] = None
    links: list = field(default_factory=list)


def _parse_traceparent(tp: Optional[str]) -> Optional[tuple]:
    if not tp:
        return None
    parts = tp.split("-")
    if len(parts) != 4 or len(parts[0]) != 2 or len(parts[1]) != 32 or len(parts[2]) != 16:
        return None
    return parts[1], parts[2], int(parts[3], 16)


def resolve_effective_parent(inbound: InboundHandoff) -> tuple:
    """Resolve parent from ALL declared transport surfaces before span creation.
    Header wins over body only if both are present and agree; disagreement is
    itself a protocol violation."""
    from_header = _parse_traceparent(inbound.header_traceparent)
    from_body = _parse_traceparent(inbound.body_metadata_traceparent)

    if from_header and from_body and from_header != from_body:
        raise TraceContextCollapseError(
            f"Conflicting traceparent across surfaces: header={from_header} body={from_body}"
        )
    resolved = from_header or from_body
    if resolved is None:
        raise TraceContextCollapseError(
            "Inbound handoff declares no resolvable traceparent on any surface"
        )
    return resolved


def start_receiver_span(
    inbound: InboundHandoff,
    *,
    callee_outlives_caller: bool,
    new_span_id: str,
) -> EmittedSpan:
    """Enforce the continue-or-link invariant. Never start a span that is
    neither a child nor a link of the caller."""
    parent_trace_id, parent_span_id, parent_flags = resolve_effective_parent(inbound)

    if not callee_outlives_caller:
        # Continue: child span, inherited trace_id and flags.
        span = EmittedSpan(
            trace_id=parent_trace_id,
            span_id=new_span_id,
            parent_span_id=parent_span_id,
        )
    else:
        # Link: independent root that references the caller.
        span = EmittedSpan(
            trace_id=f"fresh-{new_span_id}",
            span_id=new_span_id,
            parent_span_id=None,
            links=[{"trace_id": parent_trace_id, "span_id": parent_span_id,
                    "flags": parent_flags}],
        )

    # Post-condition assertion: the invariant must be observable in the span.
    is_child = span.parent_span_id == parent_span_id and span.trace_id == parent_trace_id
    is_linked = any(
        l["trace_id"] == parent_trace_id and l["span_id"] == parent_span_id
        for l in span.links
    )
    if not (is_child or is_linked):
        raise TraceContextCollapseError(
            f"Span {span.span_id} is neither child nor link of caller "
            f"{parent_trace_id}/{parent_span_id}; trace graph would collapse"
        )
    return span
