# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-orphaned-semantic-convention-spans-when-an-agent-to-agent-handoff-outlives-its-parent-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-orphaned-semantic-convention-spans-when-an-agent-to-agent-handoff-outlives-its-parent-trace-context.warrant.json
# Markdown SHA-256:   18f648c9fd20be2069502dce14e0e7e7a6911388dab780c3abe9a830021b5658
# Code AST SHA-256:   62ecbeaf982168ee074cdb4658d9a18267b4b6e6dc49620a0ca642b4d74b6a6e
# Verified Classes:   OrphanedSpanLinkError, SpanRef
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class OrphanedSpanLinkError(RuntimeError):
    """Raised when a callee span's parent reference cannot be resolved in the live span store."""


@dataclass
class SpanRef:
    trace_id: str
    span_id: str
    agent_id: str
    exported: bool


def link_callee_span(
    callee: SpanRef,
    parent: SpanRef,
    handoff_seconds: float,
    export_horizon_seconds: float,
    active_map_horizon_seconds: float,
) -> str:
    """Resolve the correct linking primitive for a callee span.

    Returns 'parent_child' when the parent is still resolvable, else 'span_link'.
    Raises OrphanedSpanLinkError if a parent-child edge is requested across the horizon.
    """
    resolvable = (
        not parent.exported
        and handoff_seconds < min(export_horizon_seconds, active_map_horizon_seconds)
    )

    if resolvable:
        return "parent_child"

    # Parent has been exported or evicted; a parent-child edge would orphan the callee.
    if handoff_seconds >= export_horizon_seconds and not parent.exported:
        # Parent not yet exported but handoff exceeded horizon: must downgrade.
        return "span_link"

    if parent.exported:
        # Explicit contract: do not emit a parent-child edge to an exported span.
        raise OrphanedSpanLinkError(
            f"callee {callee.agent_id} (span {callee.span_id}) references parent "
            f"{parent.span_id} of agent {parent.agent_id}, which was already exported "
            f"after {handoff_seconds:.1f}s handoff (horizon {export_horizon_seconds:.1f}s); "
            f"emit a span_link with gen_ai.handoff.parent_span_id instead"
        )

    return "span_link"
