# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-parent-span-references-when-a2a-handoffs-cross-trust-domains-under-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-orphaned-parent-span-references-when-a2a-handoffs-cross-trust-domains-under-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   62a73937df4f44f99a761918d61cee28b9c56a00980d7802a7efb33a769bbff3
# Code AST SHA-256:   5764e07fe8ab59bca6c3776d8841592b801c09a4ceb3365fe0dbecabe2ed69e9
# Verified Classes:   UnresolvableParentSpanError, SpanContext, EmitDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnresolvableParentSpanError(RuntimeError):
    """Raised when a child span would be emitted against a parent the
    instance cannot resolve and has not declared a handoff link for."""

    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    source_domain: str


@dataclass
class EmitDecision:
    kind: str  # "child" or "linked_root"
    parent_span_id: Optional[str]
    handoff_link: Optional[dict]


def resolve_emit_decision(
    incoming: SpanContext,
    local_span_store: set[str],
    observable_domains: set[str],
    conversation_id: str,
) -> EmitDecision:
    """Decide whether the incoming traceparent can be attached as a child
    or must be downgraded to a linked root with an explicit handoff record.

    The invariant: never emit a child span whose parent_span_id is not
    resolvable in local_span_store AND whose source_domain is not in
    observable_domains. In that case, the causal edge is unverifiable and
    must be represented as a declared link, not an inferred parent.
    """
    if incoming.parent_span_id is None:
        return EmitDecision(kind="child", parent_span_id=None, handoff_link=None)

    parent_known = incoming.parent_span_id in local_span_store
    domain_observable = incoming.source_domain in observable_domains

    if parent_known or domain_observable:
        return EmitDecision(
            kind="child",
            parent_span_id=incoming.parent_span_id,
            handoff_link=None,
        )

    # Parent is unresolvable across a trust boundary. Refuse to guess.
    # Downgrade to a linked root carrying the explicit handoff facts so
    # that downstream correlators do not stitch A->C via conversation_id.
    link = {
        "link.trace_id": incoming.trace_id,
        "link.parent_span_id": incoming.parent_span_id,
        "link.source_domain": incoming.source_domain,
        "link.conversation_id": conversation_id,
        "link.relation": "a2a.handoff",
    }

    if not link["link.parent_span_id"] or not link["link.source_domain"]:
        raise UnresolvableParentSpanError(
            f"cannot downgrade span in trace {incoming.trace_id}: "
            f"missing parent_span_id or source_domain for handoff link; "
            f"refusing to emit ambiguous correlation edge"
        )

    return EmitDecision(kind="linked_root", parent_span_id=None, handoff_link=link)


def emit_span(incoming: SpanContext, decision: EmitDecision) -> dict:
    if decision.kind == "child" and decision.parent_span_id is None and incoming.parent_span_id is not None:
        raise UnresolvableParentSpanError(
            "child emit requested without a resolvable parent; "
            "this would produce an orphaned edge"
        )
    span = {
        "trace_id": incoming.trace_id,
        "span_id": incoming.span_id,
        "parent_span_id": decision.parent_span_id,
    }
    if decision.handoff_link:
        span.update(decision.handoff_link)
    return span
