# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-an-inherited-trace-context-across-an-mcp-tool-call-boundary-when-the-upstream-a2a-peer-and.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-an-inherited-trace-context-across-an-mcp-tool-call-boundary-when-the-upstream-a2a-peer-and.warrant.json
# Markdown SHA-256:   03e9eaffb70f8d0dab41c3ae7a5845a6cc2f73c70c1ab4e9bef804966951b357
# Code AST SHA-256:   ad64f38059e4279a84c5278cdc9f61c6d0b056e4a7762ea05b542c460af9f7b7
# Verified Classes:   SpanKind, TraceContextKindConflict, InheritedContext, LocalSpanPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class SpanKind(Enum):
    PRODUCER = "producer"
    CONSUMER = "consumer"
    INTERNAL = "internal"
    CLIENT = "client"


class TraceContextKindConflict(RuntimeError):
    """Raised when an inherited trace context's span kind cannot be reconciled
    with the local semantic convention and the local layer depends on kind."""


@dataclass(frozen=True)
class InheritedContext:
    trace_id: str
    parent_span_id: str
    upstream_kind: SpanKind | None  # None => not declared on the wire
    upstream_convention: str | None


@dataclass(frozen=True)
class LocalSpanPolicy:
    local_kind: SpanKind
    depends_on_parent_kind: bool
    convention_version: str


def resolve_parent(
    inherited: InheritedContext,
    policy: LocalSpanPolicy,
) -> dict:
    """Decide whether to propagate the inherited parent, re-root, or link.

    Returns a dict describing the emission plan. Raises
    TraceContextKindConflict when the local layer depends on the parent's
    kind and the upstream kind is either undeclared or disagrees with the
    local convention in a way that would corrupt attribution.
    """
    if not inherited.trace_id or not inherited.parent_span_id:
        raise TraceContextKindConflict(
            f"incomplete inherited context: trace_id={inherited.trace_id!r} "
            f"parent_span_id={inherited.parent_span_id!r}"
        )

    if not policy.depends_on_parent_kind:
        # Pure logging layer: transport fidelity is sufficient.
        return {
            "action": "propagate",
            "trace_id": inherited.trace_id,
            "parent_span_id": inherited.parent_span_id,
            "kind_conflict": False,
        }

    if inherited.upstream_kind is None:
        # Cannot establish kind from the wire; local layer depends on it.
        # Refuse to propagate as parent; link instead and record conflict.
        return {
            "action": "link_and_reroot",
            "trace_id": inherited.trace_id,
            "link_span_id": inherited.parent_span_id,
            "local_kind": policy.local_kind.value,
            "kind_conflict": True,
            "reason": "upstream_kind_undeclared",
            "upstream_convention": inherited.upstream_convention,
            "local_convention": policy.convention_version,
        }

    if inherited.upstream_kind == policy.local_kind:
        return {
            "action": "propagate",
            "trace_id": inherited.trace_id,
            "parent_span_id": inherited.parent_span_id,
            "kind_conflict": False,
        }

    # Kinds disagree and local layer depends on kind: attribution would be
    # charged to the wrong producer. Link and re-root.
    return {
        "action": "link_and_reroot",
        "trace_id": inherited.trace_id,
        "link_span_id": inherited.parent_span_id,
        "local_kind": policy.local_kind.value,
        "kind_conflict": True,
        "reason": "span_kind_disagreement",
        "upstream_kind": inherited.upstream_kind.value,
        "local_kind_expected": policy.local_kind.value,
        "upstream_convention": inherited.upstream_convention,
        "local_convention": policy.convention_version,
    }


def emit_mcp_tool_span(
    inherited: InheritedContext,
    policy: LocalSpanPolicy,
) -> dict:
    plan = resolve_parent(inherited, policy)
    if plan["action"] == "link_and_reroot" and not plan.get("trace_id"):
        # Defensive: a re-root without a trace id is unrecoverable.
        raise TraceContextKindConflict(
            "re-root plan missing trace_id; cannot preserve trace continuity"
        )
    return plan
