# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-verifiable-credential-as-revoked-when-the-revocation-registry-is-unreachable-across-a-trust-doma.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-verifiable-credential-as-revoked-when-the-revocation-registry-is-unreachable-across-a-trust-doma.warrant.json
# Markdown SHA-256:   b2f39ffb459e5912cd1e49f04b60c6964bc6c0641cd719c00a94b000449d8e70
# Code AST SHA-256:   32b363806cd9c2902e444209241f2e5dcba07df612cefbfb448fea97ace73757
# Verified Classes:   RevocationIndeterminate, Status, StatusListFetch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class RevocationIndeterminate(RuntimeError):
    """Raised when revocation status cannot be positively confirmed fresh.

    This is NOT an availability error to be retried-and-ignored. Across a
    trust-domain boundary it is the correct deny condition: the verifier
    cannot distinguish a downed registry from a withholding one from a
    MITM on the shared path.
    """


class Status(Enum):
    VALID = "valid"
    REVOKED = "revoked"
    INDETERMINATE = "indeterminate"


@dataclass
class StatusListFetch:
    bitmap: Optional[bytes]
    signed_by_issuer: bool
    valid_until: float          # epoch seconds
    fetched_at: float


def resolve_foreign_revocation(
    fetch: StatusListFetch,
    credential_bit_index: int,
    issuer_did: str,
    now: float,
    staleness_bound_s: float,
) -> Status:
    """Resolve revocation status for a FOREIGN-domain credential.

    Fail-closed by construction. Any path that cannot positively confirm
    a fresh, issuer-signed, unrevoked status returns INDETERMINATE, which
    the caller MUST treat as deny/quarantine — never as admit.
    """
    # No bitmap at all: fetch failed, timed out, or URL was a tombstone.
    if fetch.bitmap is None:
        raise RevocationIndeterminate(
            f"no status list retrieved for issuer {issuer_did}; "
            "fail-open on foreign domain would launder revocation into admission"
        )

    # Bitmap present but not authenticated to the issuer: attacker could
    # have supplied it. Signature must chain to the issuer's DID key.
    if not fetch.signed_by_issuer:
        raise RevocationIndeterminate(
            f"status list signature does not chain to issuer {issuer_did}; "
            "treating as indeterminate, not valid"
        )

    # Staleness: a list past its validUntil is indeterminate, not valid.
    # A cached list older than the bound is likewise indeterminate.
    if now > fetch.valid_until:
        raise RevocationIndeterminate(
            f"status list expired at {fetch.valid_until}, now {now}"
        )
    if (now - fetch.fetched_at) > staleness_bound_s:
        raise RevocationIndeterminate(
            f"status list stale by {now - fetch.fetched_at:.1f}s "
            f"> bound {staleness_bound_s}s"
        )

    byte_i, bit_i = divmod(credential_bit_index, 8)
    if byte_i >= len(fetch.bitmap):
        raise RevocationIndeterminate(
            f"bit index {credential_bit_index} out of range for bitmap "
            f"of {len(fetch.bitmap)} bytes"
        )

    is_revoked = bool(fetch.bitmap[byte_i] & (1 << bit_i))
    return Status.REVOKED if is_revoked else Status.VALID


def admit_peer(fetch, bit_index, issuer_did, now, staleness_bound_s) -> bool:
    try:
        status = resolve_foreign_revocation(
            fetch, bit_index, issuer_did, now, staleness_bound_s
        )
    except RevocationIndeterminate:
        # Quarantine lane: no tool authority, human review, hard TTL.
        return False
    return status is Status.VALID
