# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-a-federated-a2a-hop-when-the-receiving-agent-s-span-clock-is-unsynchronized-and-the-propagato.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-causal-trace-across-a-federated-a2a-hop-when-the-receiving-agent-s-span-clock-is-unsynchronized-and-the-propagato.warrant.json
# Markdown SHA-256:   61bf573822ee3d3ef2255b9639f68151bca2911ad867a83c045eeaf99130dd18
# Code AST SHA-256:   7a85ed63603b5a20b916ae801caf35de6c09c2f63612f0dd4a89bc9897f2b3e7
# Verified Classes:   CausalityViolation, Span, Stitcher
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class CausalityViolation(RuntimeError):
    """Raised when a federated A2A hop would force an unverified causal edge."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    start_ns: int
    causality: str = "verified"  # "verified" | "unverified"


@dataclass
class Stitcher:
    committed: dict = field(default_factory=dict)  # span_id -> Span
    max_skew_ns: int = 50_000_000  # 50ms tolerance for any timestamp-based ordering

    def commit(self, span: Span) -> None:
        if span.parent_span_id is not None:
            parent = self.committed.get(span.parent_span_id)
            if parent is None:
                raise CausalityViolation(
                    f"span {span.span_id} references uncommitted parent "
                    f"{span.parent_span_id}; refusing to create dangling edge"
                )
            if parent.trace_id != span.trace_id:
                raise CausalityViolation(
                    f"span {span.span_id} trace_id {span.trace_id} != parent "
                    f"trace_id {parent.trace_id}; cross-trace parent forbidden"
                )
        self.committed[span.span_id] = span

    def join_across_hop(self, producer: Span, consumer: Span) -> bool:
        """Attempt a task_id-based cross-trace join. Returns True iff a
        *verified* causal edge was established; never fabricates one."""
        if producer.trace_id == consumer.trace_id:
            # Same trace: rely on parent links only, not timestamps.
            if consumer.parent_span_id == producer.span_id:
                return True
            return False
        # Different trace => propagator was dropped; we cannot verify causality.
        skew = abs(consumer.start_ns - producer.start_ns)
        if skew > self.max_skew_ns:
            # Timestamps are untrustworthy; do NOT order by them.
            consumer.causality = "unverified"
            return False
        # Even within skew, a timestamp match is not a causal proof.
        consumer.causality = "unverified"
        return False

    def ordered_edges(self):
        return [
            (s.parent_span_id, s.span_id)
            for s in self.committed.values()
            if s.parent_span_id is not None and s.causality == "verified"
        ]


def ingest_federated_hop(stitcher: Stitcher, envelope: dict) -> Span:
    traceparent = envelope.get("headers", {}).get("traceparent")
    if not traceparent:
        # Adapter dropped the propagator header. Do not invent a parent.
        span = Span(
            trace_id=envelope["fresh_trace_id"],
            span_id=envelope["span_id"],
            parent_span_id=None,
            name="a2a.subtask",
            start_ns=time.time_ns(),
            causality="unverified",
        )
        stitcher.commit(span)
        raise CausalityViolation(
            f"inbound A2A envelope for task {envelope.get('task_id')} carried no "
            f"traceparent; emitted unverified root span {span.span_id}. "
            f"Caller must retry with propagator injection or accept unverified edge."
        )
    parent_span_id = traceparent.split("-")[2]
    span = Span(
        trace_id=traceparent.split("-")[1],
        span_id=envelope["span_id"],
        parent_span_id=parent_span_id,
        name="a2a.subtask",
        start_ns=time.time_ns(),
    )
    stitcher.commit(span)  # raises if parent not yet committed
    return span
