# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-task-trace-parentage-with-otel-genai-span-parentage-when-the-two-correlation-graphs-disagree-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-task-trace-parentage-with-otel-genai-span-parentage-when-the-two-correlation-graphs-disagree-mid-handoff.warrant.json
# Markdown SHA-256:   ef883da461a7ca6d54a45895373ea9724543e49282e1a6989ac7577d78b728b6
# Code AST SHA-256:   f7e067d19de0a5998a3ce12dabf128dc236bab4df38df6e14cb5b559db6281e0
# Verified Classes:   CorrelationRegimeError, Regime, GenAISpan, A2ATaskEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CorrelationRegimeError(RuntimeError):
    """Raised when a correlator attempts to reconcile A2A task parentage
    with OTel span parentage in a way that violates the parent-set
    agreement invariant (rewriting parent_span_id across a trace boundary)."""


class Regime(str, Enum):
    CONTINUATION = "continuation"
    FEDERATION = "federation"


@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    task_id: str
    regime: Regime
    linked_parent_task_id: str | None = None


@dataclass(frozen=True)
class A2ATaskEvent:
    task_id: str
    parent_task_id: str | None
    context_id: str


def reconcile(span: GenAISpan, task: A2ATaskEvent) -> GenAISpan:
    """Return the span as it must be stored: parentage preserved verbatim.

    Federation spans carry the upstream task as a *link*, never a parent edge.
    Continuation spans may only keep a parent that resolves within their own
    trace_id; anything else is an integrity fault, not a stitching cue.
    """
    if span.task_id != task.task_id:
        raise CorrelationRegimeError(
            f"span {span.span_id} belongs to task {span.task_id}, "
            f"but was joined against task {task.task_id}"
        )

    if span.regime is Regime.FEDERATION:
        if span.linked_parent_task_id is None:
            raise CorrelationRegimeError(
                f"federated span {span.span_id} under task {task.task_id} "
                f"has no SpanLink to parent task {task.parent_task_id}; "
                f"refusing to synthesize a parent edge"
            )
        # Parent stays as emitted; task causality is carried by the link.
        return span

    # Continuation: parent edge must be intra-trace. A cross-trace parent
    # here means the inbound traceparent was dropped or re-sampled.
    if span.parent_span_id is not None and span.parent_span_id.startswith("remote:"):
        raise CorrelationRegimeError(
            f"continuation span {span.span_id} carries a cross-trace parent "
            f"{span.parent_span_id}; traceparent was not actually continued"
        )
    return span


def stitch(spans: list[GenAISpan], tasks: list[A2ATaskEvent]) -> dict[str, GenAISpan]:
    by_task = {t.task_id: t for t in tasks}
    out: dict[str, GenAISpan] = {}
    for s in spans:
        task = by_task.get(s.task_id)
        if task is None:
            raise CorrelationRegimeError(
                f"span {s.span_id} references unknown task {s.task_id}"
            )
        out[s.span_id] = reconcile(s, task)
    return out
