# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-trust-anchor-resolves-to-a-valid-but-stale-reputation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-delegated-aaif-credential-whose-trust-anchor-resolves-to-a-valid-but-stale-reputation-epoch.warrant.json
# Markdown SHA-256:   064ba6d0261aff3d151d73c51d135ab25f829602507da50869370fd6d01eae1b
# Code AST SHA-256:   4c200cc1b6794d23d74bd5eb54a3fccfe094856629ad6f0af816c527950fb06b
# Verified Classes:   StaleReputationEpochError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleReputationEpochError(RuntimeError):
    """Raised when an AAIF credential's embedded reputation epoch is stale
    in an adverse direction relative to the anchor's current epoch, and the
    claimed tier exceeds the subject's tier at the current epoch."""
    def __init__(self, subject: str, embedded_epoch: int, current_epoch: int,
                 claimed_tier: str, current_tier: str, anchor: str):
        self.subject = subject
        self.embedded_epoch = embedded_epoch
        self.current_epoch = current_epoch
        self.claimed_tier = claimed_tier
        self.current_tier = current_tier
        self.anchor = anchor
        super().__init__(
            f"stale adverse epoch for {subject}@{anchor}: "
            f"embedded={embedded_epoch} current={current_epoch} "
            f"claimed={claimed_tier} actual={current_tier}"
        )


TIER_ORDER = {"tier-0": 0, "tier-1": 1, "tier-2": 2, "tier-3": 3}


def validate_delegated_credential(
    credential: dict,
    anchor_view: dict,          # {current_epoch, max_staleness, tier_at_current, delta_summary}
    capability_threshold: str,
) -> None:
    """
    Enforce the two-step AAIF validation:
      (a) credential valid against its embedded epoch (assumed pre-checked by caller),
      (b) embedded epoch reconciled against anchor's current view.

    Raises StaleReputationEpochError when the adverse-delta conjunct holds.
    """
    embedded = credential["reputationAnchor"]["epoch"]
    subject = credential["subject"]
    claimed_tier = credential["delegatedTier"]
    anchor = credential["reputationAnchor"]["cdta"]

    current = anchor_view["current_epoch"]
    max_staleness = anchor_view["max_staleness"]

    # Unconditional rejection: gap exceeds retention window.
    if current - embedded > max_staleness:
        raise StaleReputationEpochError(
            subject, embedded, current, claimed_tier,
            anchor_view["tier_at_current"], anchor,
        )

    # Benign staleness: embedded == current, accept.
    if embedded == current:
        return

    # Adverse-delta conjunct: any negative tierDelta in (embedded, current].
    adverse = any(
        TIER_ORDER[d["tier_after"]] < TIER_ORDER[d["tier_before"]]
        for d in anchor_view["delta_summary"]
        if embedded < d["epoch"] <= current
    )
    if not adverse:
        return  # benign rotation; credential remains valid under tolerance

    # Threshold-breach conjunct: claimed tier exceeds current tier AND
    # claimed tier meets or exceeds the capability's authorization threshold.
    if (
        TIER_ORDER[claimed_tier] > TIER_ORDER[anchor_view["tier_at_current"]]
        and TIER_ORDER[claimed_tier] >= TIER_ORDER[capability_threshold]
    ):
        raise StaleReputationEpochError(
            subject, embedded, current, claimed_tier,
            anchor_view["tier_at_current"], anchor,
        )
