# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-identity-spoofing-when-behavioral-fingerprints-and-signed-action-receipts-disagree-at-the-receipt-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-identity-spoofing-when-behavioral-fingerprints-and-signed-action-receipts-disagree-at-the-receipt-boundary.warrant.json
# Markdown SHA-256:   679219ebf35086eb9cc691e37517e3dba0ab4c0e8d1e27eed72fafdd62f2d92f
# Code AST SHA-256:   2825f4b30fe820dbd4e072b59279c231f8f4d3e23765cd7d649802673c48dd43
# Verified Classes:   IdentitySpoofingSuspected, FingerprintUnusable, Receipt, Fingerprint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Callable


class IdentitySpoofingSuspected(RuntimeError):
    """Raised when a receipt is cryptographically valid but behaviorally divergent."""
    pass


class FingerprintUnusable(RuntimeError):
    """Raised when the fingerprint is stale or non-commensurable with the receipt."""
    pass


@dataclass
class Receipt:
    peer_id: str
    payload: dict
    signature: bytes
    sequence: int
    timestamp: float


@dataclass
class Fingerprint:
    peer_id: str
    updated_at: float
    admissible_band: float          # normalized divergence tolerance
    commensurable: bool             # can it be computed from receipt payload?
    compute_divergence: Callable[[dict], float]


def verify_receipt(
    receipt: Receipt,
    fp: Fingerprint,
    signature_valid: bool,
    now: float,
    freshness_horizon: float,
    re_attest: Callable[[str], bool],
) -> str:
    if not signature_valid:
        return "reject"  # quadrant 2: no fingerprint evidence rescues this

    # Fingerprint usability gate BEFORE divergence check.
    fp_fresh = (now - fp.updated_at) <= freshness_horizon
    if not fp_fresh or not fp.commensurable:
        # quadrant 4: divergence uninformative -> accept-with-caveat
        return "accept_with_caveat_refresh_fingerprint"

    divergence = fp.compute_divergence(receipt.payload)
    if divergence <= fp.admissible_band:
        return "accept"  # quadrant 1

    # quadrant 3: signature valid, fingerprint fresh+commensurable, divergent.
    # This is the spoofing-suspicion terminal state. Do NOT fall through to accept.
    if not re_attest(receipt.peer_id):
        raise IdentitySpoofingSuspected(
            f"peer {receipt.peer_id} seq={receipt.sequence}: valid signature but "
            f"behavioral divergence {divergence:.3f} > band {fp.admissible_band:.3f}, "
            f"re-attestation failed"
        )
    return "quarantine_resolved_by_reattestation"


def guard_fingerprint_commensurability(fp: Fingerprint) -> None:
    if not fp.commensurable:
        raise FingerprintUnusable(
            f"fingerprint for {fp.peer_id} is not computable from receipt payload; "
            f"divergence channel is invalid"
        )
