# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-revoked-aaif-warrant-as-still-live-revocation-propagation-lag-versus-trust-score-monotonicity-across-federated-agent-mes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-revoked-aaif-warrant-as-still-live-revocation-propagation-lag-versus-trust-score-monotonicity-across-federated-agent-mes.warrant.json
# Markdown SHA-256:   a1bf195ecfd9c7c593e56c33b6bd13ba87f51d037e3e4b71ec6787185d33b858
# Code AST SHA-256:   99219163cf3016940a32318603b654c78a111fbc1b1087c8c09d25e6ef17b116
# Verified Classes:   TrustResurrectionError, TrustEntry, Instance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TrustResurrectionError(RuntimeError):
    """Raised when a trust merge or authorization would resurrect a revoked actor."""
    pass


@dataclass
class TrustEntry:
    actor: str
    score: float
    revocation_epoch: int          # authority-logical-time of the latest known revocation
    attribution_time: int          # authority-time of the last increment
    tombstone: bool = False


@dataclass
class Instance:
    name: str
    trust: dict = field(default_factory=dict)         # actor -> TrustEntry
    applied_revocation: dict = field(default_factory=dict)  # actor -> epoch applied

    def record_success(self, actor: str, authority_time: int, alpha: float = 0.05) -> None:
        entry = self.trust.get(actor)
        if entry is None:
            entry = TrustEntry(actor, 0.5, 0, authority_time)
        rev_epoch = self.applied_revocation.get(actor, 0)
        if entry.tombstone and authority_time <= rev_epoch:
            # increment earned before authoritative revocation: allowed, but capped
            pass
        elif entry.tombstone and authority_time > rev_epoch:
            raise TrustResurrectionError(
                f"{self.name}: success at t={authority_time} for revoked actor {actor} "
                f"(rev_epoch={rev_epoch}); increment must be rejected"
            )
        entry.score = min(1.0, entry.score + alpha * (1.0 - entry.score))
        entry.attribution_time = authority_time
        self.trust[actor] = entry

    def apply_revocation(self, actor: str, t_rev: int) -> None:
        prev_epoch = self.applied_revocation.get(actor, -1)
        if t_rev <= prev_epoch:
            return
        entry = self.trust.get(actor)
        if entry is not None and entry.attribution_time > t_rev:
            # retroactive rollback (V2): recompute from pre-revocation baseline
            entry.score = 0.0
            entry.attribution_time = t_rev
        if entry is not None:
            entry.tombstone = True
            entry.revocation_epoch = t_rev
        self.applied_revocation[actor] = t_rev

    def merge_gossip(self, other: TrustEntry) -> None:
        local = self.trust.get(other.actor)
        my_epoch = self.applied_revocation.get(other.actor, 0)
        if other.revocation_epoch < my_epoch:
            # peer's view is authority-stale; reject higher trust (guard V3)
            if local is not None and other.score > local.score:
                raise TrustResurrectionError(
                    f"{self.name}: refusing gossiped trust {other.score:.3f} for {other.actor} "
                    f"from peer epoch {other.revocation_epoch} < local epoch {my_epoch}"
                )
            return
        if local is None:
            self.trust[other.actor] = other
            return
        if other.revocation_epoch > local.revocation_epoch:
            self.trust[other.actor] = other
        else:
            local.score = min(local.score, other.score)  # pessimistic tie-break
            local.tombstone = local.tombstone or other.tombstone

    def authorize(self, actor: str, authority_time: int) -> bool:
        entry = self.trust.get(actor)
        if entry is None:
            return False
        rev_epoch = self.applied_revocation.get(actor, 0)
        if entry.tombstone and authority_time > rev_epoch:
            raise TrustResurrectionError(
                f"{self.name}: authorization attempted at t={authority_time} for actor {actor} "
                f"revoked at t={rev_epoch}"
            )
        return entry.score >= 0.5
