# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-execution-receipt-when-the-slashing-oracle-and-the-reputation-ledger-disagree-on-the-same-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-execution-receipt-when-the-slashing-oracle-and-the-reputation-ledger-disagree-on-the-same-warrant.warrant.json
# Markdown SHA-256:   41bd8fa5b1aab5a96761a9892dac6c10161d6c8a0b8d29c6390b92689f2f6b7e
# Code AST SHA-256:   aca017935e32db68abc788d29e00193578bbc6187e86bf29c04ff14af8bd319b
# Verified Classes:   ReputationContaminationError, ReceiptView, PeerReputation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ReputationContaminationError(RuntimeError):
    """Raised when a peer's reputation is derived from receipts the slashing
    oracle has invalidated. The score is not a trust signal; it is an artifact
    of a ledger/oracle binding mismatch."""


@dataclass(frozen=True)
class ReceiptView:
    receipt_id: str
    manifest_hash: str
    model_pin: str
    output_hash: str


@dataclass(frozen=True)
class PeerReputation:
    peer_id: str
    score: float
    ledger_accepted: FrozenSet[str]      # receipt_ids the ledger scored positively
    oracle_slashed: FrozenSet[str]       # receipt_ids the oracle issued a slash warrant for
    oracle_replayed_clean: FrozenSet[str]  # receipt_ids replayed without mismatch
    open_challenge_window: FrozenSet[str]  # receipt_ids not yet past challenge window


def assess_peer(reputation: PeerReputation) -> str:
    """Classify a peer's reputation as clean / provisional / contaminated.

    The invariant enforced here:
        ledger.accepted(r) AND oracle.slashed(r) => reputation is contaminated.
    Signature validity is irrelevant; binding divergence is the trigger.
    """
    contaminated = reputation.ledger_accepted & reputation.oracle_slashed
    if contaminated:
        raise ReputationContaminationError(
            f"peer {reputation.peer_id!r} has {len(contaminated)} receipt(s) "
            f"accepted by ledger but slashed by oracle: "
            f"{sorted(contaminated)[:5]}... score {reputation.score} is not a "
            f"trust signal; demote to unverified floor."
        )

    if reputation.open_challenge_window:
        return "provisional"

    if not reputation.ledger_accepted <= reputation.oracle_replayed_clean:
        # Every accepted receipt must have been replayed clean against the
        # committed manifest_hash/model_pin. A gap means the oracle never
        # validated the context the ledger scored against.
        unverified = reputation.ledger_accepted - reputation.oracle_replayed_clean
        raise ReputationContaminationError(
            f"peer {reputation.peer_id!r} has {len(unverified)} ledger-accepted "
            f"receipt(s) never replayed clean by the oracle; binding context "
            f"divergence is unproven, treat as unverified."
        )

    return "clean"


def route_call(reputation: PeerReputation, tolerates_post_hoc_slash: bool) -> str:
    state = assess_peer(reputation)
    if state == "clean":
        return "route"
    if state == "provisional" and tolerates_post_hoc_slash:
        return "route_with_loss_reserve"
    if state == "provisional":
        raise ReputationContaminationError(
            f"peer {reputation.peer_id!r} reputation is provisional (open "
            f"challenge window) and task cannot absorb post-hoc slashing."
        )
    raise ReputationContaminationError(f"unreachable state {state!r}")
