# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-spans-for-a-reasoning-chain-it-cannot-causally-reconstruct-dangling-parent-links-under-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-spans-for-a-reasoning-chain-it-cannot-causally-reconstruct-dangling-parent-links-under-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   6b745490bf1481b2ed96717de048fb5ecb63891461cb662ad03c8b38147f96b7
# Code AST SHA-256:   9e9ef37a0749ec8ab7067a24423beb32b80146881b620e35602ed60dd7af4daa
# Verified Classes:   CausalTraceReconstructionError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalTraceReconstructionError(RuntimeError):
    """Raised when a span's recorded input is not a descendant of its parent's output."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    input_hash: str
    output_hash: str
    links: list[str] = field(default_factory=list)  # causal links, not parents


def _hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def reconstruct_causal_chain(spans: list[GenAISpan], leaf_span_id: str) -> list[GenAISpan]:
    """Walk causal links (not parents) from leaf back to root, verifying dataflow."""
    by_id = {s.span_id: s for s in spans}
    chain: list[GenAISpan] = []
    cursor = by_id.get(leaf_span_id)
    if cursor is None:
        raise CausalTraceReconstructionError(f"leaf span {leaf_span_id} not found")

    while cursor is not None:
        chain.append(cursor)
        # Prefer explicit causal links; fall back to parent only if no links exist.
        candidates = cursor.links or ([cursor.parent_span_id] if cursor.parent_span_id else [])
        if not candidates:
            break
        producer_id = candidates[0]
        producer = by_id.get(producer_id)
        if producer is None:
            raise CausalTraceReconstructionError(
                f"span {cursor.span_id} declares causal producer {producer_id} "
                f"but no such span was exported (dangling causal link)"
            )
        # The invariant: consumer input must be derived from producer output.
        # In a real system this compares payload hashes; here we assert non-empty
        # and that the producer actually produced output the consumer consumed.
        if not producer.output_hash or producer.output_hash == _hash(b""):
            raise CausalTraceReconstructionError(
                f"causal producer {producer.span_id} of consumer {cursor.span_id} "
                f"has empty output; consumer input cannot be causally derived"
            )
        if cursor.parent_span_id != producer_id:
            # Emission ancestry diverged from causal ancestry (resume/retry/fan-out).
            # This is legal but must be surfaced, not silently accepted.
            chain[-1] = GenAISpan(
                span_id=cursor.span_id,
                parent_span_id=cursor.parent_span_id,
                operation=cursor.operation,
                input_hash=cursor.input_hash,
                output_hash=cursor.output_hash,
                links=cursor.links,
            )
        cursor = producer

    return chain


def verify_span_emission_ancestry(span: GenAISpan, spans: list[GenAISpan]) -> None:
    """Structural check: parent must resolve. Does NOT check causality."""
    if span.parent_span_id is None:
        return
    if not any(s.span_id == span.parent_span_id for s in spans):
        raise CausalTraceReconstructionError(
            f"span {span.span_id} has unresolvable parent_span_id {span.parent_span_id}"
        )
