# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-span-truncation-when-its-verifiable-action-log-outlives-the-opentelemetry-span-that-anchors-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-span-truncation-when-its-verifiable-action-log-outlives-the-opentelemetry-span-that-anchors-it.warrant.json
# Markdown SHA-256:   10bf66ab470d2f3da525d8a79352eae835c07b6f41fadd3f25b3bd206b2bd295
# Code AST SHA-256:   9361c7284473ca8c1003092f010e41c298f1ccffc17c0fed75dc9d35f45c8219
# Verified Classes:   AnchorOrphanError, ActionRecord, ExportAck
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AnchorOrphanError(RuntimeError):
    """Raised when an action-log record's anchor span cannot be confirmed as exported/retained."""
    pass


@dataclass
class ActionRecord:
    seq: int
    tool: str
    args_digest: str
    trace_id: str
    span_id: str
    prev_hash: str
    record_hash: str = ""


@dataclass
class ExportAck:
    acked_span_id: str
    export_status: str  # "exported" | "sampled_out" | "dropped" | "evicted"
    exporter_sequence: int


def _hash_record(rec: ActionRecord) -> str:
    body = json.dumps(
        {"seq": rec.seq, "tool": rec.tool, "args_digest": rec.args_digest,
         "trace_id": rec.trace_id, "span_id": rec.span_id, "prev_hash": rec.prev_hash},
        sort_keys=True,
    )
    return hashlib.sha256(body.encode()).hexdigest()


def audit_chain(records: list[ActionRecord], acks: dict[str, ExportAck],
                trace_backend_has: set[str]) -> list[int]:
    """
    Replay the chain and return the seq numbers of records whose anchor
    span is NOT provably exported and retained. Raises AnchorOrphanError
    if the chain itself is broken (hash mismatch) — a different, louder failure.
    """
    orphans: list[int] = []
    prev = ""
    for rec in records:
        expected = _hash_record(rec)
        if rec.record_hash and rec.record_hash != expected:
            raise AnchorOrphanError(
                f"chain integrity broken at seq={rec.seq}: "
                f"record_hash {rec.record_hash[:12]} != recomputed {expected[:12]}"
            )
        if rec.prev_hash != prev:
            raise AnchorOrphanError(
                f"chain linkage broken at seq={rec.seq}: prev_hash mismatch"
            )
        prev = expected

        ack: Optional[ExportAck] = acks.get(rec.span_id)
        if ack is None:
            # No acknowledgment was ever written back into the log.
            orphans.append(rec.seq)
            continue
        if ack.export_status != "exported":
            orphans.append(rec.seq)
            continue
        if rec.span_id not in trace_backend_has:
            # Ack says exported, but backend no longer has it (TTL eviction).
            orphans.append(rec.seq)
    return orphans


def certify_step(rec: ActionRecord, ack: Optional[ExportAck],
                 trace_backend_has: set[str], flush_deadline_exceeded: bool) -> str:
    """
    Decide whether a step may be marked audit-complete. If the anchor is
    unconfirmed, the caller MUST inline the preimage or downgrade the status.
    """
    if ack is None and flush_deadline_exceeded:
        raise AnchorOrphanError(
            f"seq={rec.seq} span={rec.span_id}: no export ack within flush deadline; "
            f"cannot certify as audit-complete — inline preimage or mark anchor_unconfirmed"
        )
    if ack is not None and ack.export_status != "exported":
        raise AnchorOrphanError(
            f"seq={rec.seq} span={rec.span_id}: anchor lost ({ack.export_status}); "
            f"content witness unavailable"
        )
    if rec.span_id not in trace_backend_has:
        raise AnchorOrphanError(
            f"seq={rec.seq} span={rec.span_id}: ack claims exported but backend evicted it"
        )
    return "audit_complete"
