# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-brokered-capability-grant-when-the-trust-chain-s-policy-attestation-is-valid-but-the-delegating-principal-s-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-brokered-capability-grant-when-the-trust-chain-s-policy-attestation-is-valid-but-the-delegating-principal-s-authority.warrant.json
# Markdown SHA-256:   18b86cb7297657b1568f273821990694fa001a6e41420f72285109807bf2e82c
# Code AST SHA-256:   34b921d6fd34695bfbba691a535ffec592972e47de5be08fd66af1061b592af1
# Verified Classes:   SupersededAuthorityError, BrokeredWarrant, EpochServiceView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class SupersededAuthorityError(RuntimeError):
    """Raised when a brokered warrant's delegator authority epoch is stale or superseded."""


@dataclass(frozen=True)
class BrokeredWarrant:
    warrant_id: str
    principal_authority_epoch: int
    epoch_checked_at: float          # broker's last confirmed epoch read, unix ts
    broker_subscription_receipt: str | None  # signed proof broker subscribes to A's epoch stream
    policy_hash: str
    audience: str
    expires_at: float


@dataclass(frozen=True)
class EpochServiceView:
    reachable: bool
    current_epoch: int | None


def verify_brokered_warrant(
    w: BrokeredWarrant,
    target_resource: str,
    accepted_policy_hashes: set[str],
    epoch_view: EpochServiceView,
    delta_seconds: float,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Ordinary checks: these pass in the failure mode and are NOT sufficient.
    if w.audience != target_resource:
        raise SupersededAuthorityError(f"audience mismatch for {w.warrant_id}")
    if w.policy_hash not in accepted_policy_hashes:
        raise SupersededAuthorityError(f"policy hash not accepted for {w.warrant_id}")
    if now > w.expires_at:
        raise SupersededAuthorityError(f"warrant {w.warrant_id} expired")

    # The invariant: delegator authority liveness must be establishable at `now`.
    if w.broker_subscription_receipt is None:
        raise SupersededAuthorityError(
            f"warrant {w.warrant_id}: broker attests policy fidelity but not "
            f"epoch-stream subscription; cannot establish delegator liveness"
        )

    staleness = now - w.epoch_checked_at
    if staleness > delta_seconds:
        raise SupersededAuthorityError(
            f"warrant {w.warrant_id}: epoch_checked_at stale by {staleness:.1f}s "
            f"> Δ={delta_seconds}s; fail closed"
        )

    if epoch_view.reachable and epoch_view.current_epoch is not None:
        if epoch_view.current_epoch > w.principal_authority_epoch:
            raise SupersededAuthorityError(
                f"warrant {w.warrant_id}: delegator authority superseded "
                f"(warrant epoch={w.principal_authority_epoch}, "
                f"current={epoch_view.current_epoch})"
            )
    else:
        # Epoch service unreachable: only admissible if within Δ of last check.
        # staleness check above already enforced this; reaching here means we
        # are within Δ and may proceed on the broker's receipt alone.
        pass
