# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-cross-org-provenance-chain-whose-hash-links-verify-but-whose-causal-predecessor-was-never-witnessed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-cross-org-provenance-chain-whose-hash-links-verify-but-whose-causal-predecessor-was-never-witnessed.warrant.json
# Markdown SHA-256:   217996415be84c0789ab7a09a14e2a10f3f4369ef355ef14041eada3b9d101fd
# Code AST SHA-256:   f4e936ca0f4f929185349131dcc88cbd08e55eca8be965c0f6a3eadc0551dc13
# Verified Classes:   UnanchoredProvenanceError, Record, Anchor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnanchoredProvenanceError(RuntimeError):
    """Raised when a segment's link integrity verifies but no external
    witness brackets it, so it cannot be treated as tamper-evident."""
    pass


@dataclass
class Record:
    index: int
    prev_hash: str
    payload: str
    signature: str  # Ed25519 over (index, prev_hash, payload); verified elsewhere

    def digest(self) -> str:
        h = hashlib.sha256(f"{self.index}|{self.prev_hash}|{self.payload}".encode())
        return h.hexdigest()


@dataclass
class Anchor:
    """A signed statement held by a non-emitter party referencing a record hash."""
    record_hash: str
    seam_prev_hash: str  # the predecessor the witness believed this extended
    witness_id: str      # must differ from emitter_id


def link_integrity(segment: list[Record]) -> bool:
    for prev, cur in zip(segment, segment[1:]):
        if cur.prev_hash != prev.digest():
            return False
    return True


def signatures_valid(segment: list[Record], emitter_pubkey: str) -> bool:
    # Placeholder: real impl verifies each record.signature against emitter_pubkey.
    return all(r.signature for r in segment)


def find_bracketing_anchors(
    segment: list[Record], anchors: list[Anchor], emitter_id: str
) -> tuple[Optional[Anchor], Optional[Anchor]]:
    """Return (start_anchor, end_anchor) that bracket the segment, or Nones.

    A start anchor must reference segment[0].prev_hash (the seam into the
    segment) and be held by a non-emitter. An end anchor must reference
    segment[-1].digest() and bind the seam segment[-1].prev_hash.
    """
    seam_in = segment[0].prev_hash
    head_out = segment[-1].digest()
    seam_out = segment[-1].prev_hash

    start = next(
        (a for a in anchors
         if a.witness_id != emitter_id and a.record_hash == seam_in),
        None,
    )
    end = next(
        (a for a in anchors
         if a.witness_id != emitter_id
         and a.record_hash == head_out
         and a.seam_prev_hash == seam_out),
        None,
    )
    return start, end


def accept_as_provenance(
    segment: list[Record],
    anchors: list[Anchor],
    emitter_id: str,
    emitter_pubkey: str,
) -> str:
    """Classify an incoming segment as 'witnessed' or 'advisory'.

    Raises UnanchoredProvenanceError if the caller attempts to promote an
    unanchored segment to evidentiary status. Returns the classification so
    the caller can anchor the head at receipt time.
    """
    if not link_integrity(segment):
        raise UnanchoredProvenanceError(
            "link integrity failed; segment is corrupt, not merely unanchored"
        )
    if not signatures_valid(segment, emitter_pubkey):
        raise UnanchoredProvenanceError(
            "signature invalid; emitter identity not established"
        )

    start, end = find_bracketing_anchors(segment, anchors, emitter_id)
    if start is None or end is None:
        # Link integrity holds, but no external witness brackets this segment.
        # It is unilaterally mutable by the emitter: advisory, never evidentiary.
        return "advisory"

    return "witnessed"


def handoff(
    segment: list[Record],
    anchors: list[Anchor],
    emitter_id: str,
    emitter_pubkey: str,
    require_evidentiary: bool = True,
) -> str:
    classification = accept_as_provenance(segment, anchors, emitter_id, emitter_pubkey)
    if require_evidentiary and classification != "witnessed":
        raise UnanchoredProvenanceError(
            f"segment from {emitter_id} verifies link integrity but has no "
            f"bracketing anchor (start={segment[0].prev_hash[:12]}, "
            f"head={segment[-1].digest()[:12]}); refusing evidentiary use. "
            f"Anchor the head at receipt before citing this segment as provenance."
        )
    return classification
