# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-verifiable-credential-whose-status-list-has-been-rotated-but-whose-revocation-epoch-has-not-yet-propagated-across-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-verifiable-credential-whose-status-list-has-been-rotated-but-whose-revocation-epoch-has-not-yet-propagated-across-a.warrant.json
# Markdown SHA-256:   a71043e74bb1596f58966d51bb8c60520692fb5d3e25b34327ad1b62bad739b7
# Code AST SHA-256:   b08f8141210981483c74182aa9dae613c1b0671187d99a6a1def2e86689a8c83
# Verified Classes:   EpochUnverifiableError, StatusListCredential, IssuerEpochView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EpochUnverifiableError(RuntimeError):
    """The SLC is signature-valid and unexpired, but its revocation epoch
    cannot be confirmed equal to the issuer's current epoch. Bit-clear is
    not evidence of non-revocation; the caller must not admit on it."""


@dataclass(frozen=True)
class StatusListCredential:
    uri: str
    epoch: int
    next_update: float  # unix seconds
    bits: bytes


@dataclass(frozen=True)
class IssuerEpochView:
    epoch: int
    observed_at: float


def validate_agent_credential(
    credential_status_uri: str,
    slc: StatusListCredential,
    bit_index: int,
    issuer_epoch: IssuerEpochView | None,
    now: float,
    high_privilege: bool,
) -> bool:
    if slc.uri != credential_status_uri:
        raise EpochUnverifiableError(
            f"SLC URI {slc.uri!r} does not match credential status pointer "
            f"{credential_status_uri!r}; possible list substitution."
        )

    if now >= slc.next_update:
        raise EpochUnverifiableError(
            f"SLC epoch {slc.epoch} expired at {slc.next_update}; "
            f"refresh required before admission."
        )

    byte, offset = divmod(bit_index, 8)
    revoked = bool(slc.bits[byte] & (1 << (7 - offset)))
    if revoked:
        return False

    # Bit is clear. This is only admissible if we can confirm the SLC is
    # the issuer's current epoch, or if the action is low-privilege.
    if issuer_epoch is None:
        if high_privilege:
            raise EpochUnverifiableError(
                f"No issuer epoch view available for SLC epoch {slc.epoch}; "
                f"cannot confirm non-revocation for high-privilege action."
            )
        return True

    if issuer_epoch.epoch != slc.epoch:
        raise EpochUnverifiableError(
            f"SLC epoch {slc.epoch} != issuer epoch {issuer_epoch.epoch}; "
            f"revocations committed since snapshot are invisible. "
            f"Challenge the agent or reject."
        )

    return True
