# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-stale-reputation-entry-when-its-aaif-identity-root-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-stale-reputation-entry-when-its-aaif-identity-root-rotates-mid-session.warrant.json
# Markdown SHA-256:   b77612ed562020e5303bc5f62f817838b2a34914dc0cff3d4df556e02c57fc82
# Code AST SHA-256:   120e8e6da4c05ae7799f29191dcb8524972e24e20e2a77e866291f28a6dc0e7d
# Verified Classes:   StaleReputationBindingError, LedgerEntry, KeyRecord, DirectorySnapshot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime
from typing import Optional


class StaleReputationBindingError(RuntimeError):
    """Raised when a ledger entry's signing key was revoked/compromised
    after signing but before the consumer's read, making attribution unsafe."""
    pass


@dataclass
class LedgerEntry:
    subject: str
    subject_root: str
    signed_at: datetime
    payload: dict


@dataclass
class KeyRecord:
    key_id: str
    valid_from: datetime
    revoked_at: Optional[datetime]
    compromised_at: Optional[datetime]  # None if never compromised


@dataclass
class DirectorySnapshot:
    # Must be fetched fresh at read time, NOT cached with the ledger entry.
    keys: dict  # key_id -> KeyRecord


def verify_reputation_entry(
    entry: LedgerEntry,
    directory: DirectorySnapshot,
    read_at: datetime,
    signature_ok: bool,
) -> float:
    if not signature_ok:
        raise StaleReputationBindingError(
            f"signature invalid for entry signed by {entry.subject_root}"
        )

    key = directory.keys.get(entry.subject_root)
    if key is None:
        # Absence of a record is "unknown", not "valid" — replication lag.
        raise StaleReputationBindingError(
            f"no directory record for signing key {entry.subject_root}; "
            f"cannot attribute reputation for {entry.subject}"
        )

    # Condition 1: signing key must be a historical key valid at signing time.
    if not (key.valid_from <= entry.signed_at):
        raise StaleReputationBindingError(
            f"entry signed_at {entry.signed_at} precedes key validity "
            f"{key.valid_from} for {entry.subject_root}"
        )

    # Condition 2: signing key must not have been revoked before signing.
    if key.revoked_at is not None and entry.signed_at >= key.revoked_at:
        raise StaleReputationBindingError(
            f"entry signed_at {entry.signed_at} is at/after revocation "
            f"{key.revoked_at} for {entry.subject_root}"
        )

    # Condition 3 (the one that fails): compromise must not have been
    # known at or before read time. A compromise flagged during the TTL
    # of a cached directory snapshot is invisible and launders the entry.
    if key.compromised_at is not None and key.compromised_at <= read_at:
        raise StaleReputationBindingError(
            f"signing key {entry.subject_root} for subject {entry.subject} "
            f"was compromised at {key.compromised_at}, before read at "
            f"{read_at}; entry must be re-attested under current root"
        )

    return entry.payload["reliability"]
