# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-redacted-span-as-a-reconstruction-boundary-rather-than-a-gap-to-be-interpolated.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-redacted-span-as-a-reconstruction-boundary-rather-than-a-gap-to-be-interpolated.warrant.json
# Markdown SHA-256:   e836772c1e8f4795719daa992245a5069dc953f1e0475e83cc32244232fc45e5
# Code AST SHA-256:   36c62b21befba4c02d08887b031a658a844a8b00b6a8aed3ddc930c138fc6b99
# Verified Classes:   ReconstructionBoundaryError, SealReason, Span, BoundaryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ReconstructionBoundaryError(RuntimeError):
    """Raised when a reconstructor attempts to interpolate causality through a sealed span."""
    pass


class SealReason(Enum):
    UNSIGNED_ENVELOPE = "unsigned_envelope"
    MULTI_SIBLING_AMBIGUITY = "multi_sibling_ambiguity"
    NON_TOTAL_OP = "non_total_op"
    ORPHANED_DOWNSTREAM_INPUT = "orphaned_downstream_input"


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    op_class: str
    redacted: bool
    envelope_signed: bool
    op_declared_total: bool
    start_offset_ms: int
    input_hash: Optional[str] = None
    output_hash: Optional[str] = None


@dataclass
class BoundaryNode:
    span_id: str
    reason: SealReason
    sealed: bool = True


def classify_span(
    span: Span,
    siblings: list[Span],
    visible_producers: set[str],
) -> BoundaryNode | Span:
    if not span.redacted:
        return span
    if not span.envelope_signed:
        return BoundaryNode(span.span_id, SealReason.UNSIGNED_ENVELOPE)
    same_parent = [s for s in siblings if s.parent_span_id == span.parent_span_id and s.redacted]
    if len(same_parent) > 1:
        return BoundaryNode(span.span_id, SealReason.MULTI_SIBLING_AMBIGUITY)
    if not span.op_declared_total:
        return BoundaryNode(span.span_id, SealReason.NON_TOTAL_OP)
    return span


def interpolate_edge(parent: Span, child: Span, boundary: BoundaryNode | Span) -> str:
    if isinstance(boundary, BoundaryNode):
        raise ReconstructionBoundaryError(
            f"refusing to draw inferred edge {parent.span_id}->{child.span_id}: "
            f"boundary {boundary.span_id} sealed ({boundary.reason.value})"
        )
    if child.input_hash and child.input_hash not in _known_producers(parent):
        raise ReconstructionBoundaryError(
            f"downstream input of {child.span_id} not attributable to visible producer; "
            f"hidden producer exists behind {parent.span_id}"
        )
    return f"{parent.span_id}->{child.span_id}"


def _known_producers(span: Span) -> set[str]:
    return {span.output_hash} if span.output_hash else set()
