# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-exchanges-aaif-credentials-across-a-trust-boundary-it-cannot-re-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-exchanges-aaif-credentials-across-a-trust-boundary-it-cannot-re-verify.warrant.json
# Markdown SHA-256:   5b76d2a9d14283ed895a0163baf46fd5204998e6b74912b4a0162fbbc8fc60bc
# Code AST SHA-256:   c0ed3bd46b5cd34074c1c2aac67426f39cd7ecaf19f4a26f3ae08f4d31757335
# Verified Classes:   StaleWarrantError, VerdictDivergenceError, CachedCredential, CredentialConduit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when an instance attempts to re-present a cached AAIF credential
    whose authorization state can no longer be locally validated."""
    pass


class VerdictDivergenceError(RuntimeError):
    """Raised when relying parties return conflicting authorization verdicts
    for the same credential and the instance cannot resolve safely."""
    pass


@dataclass
class CachedCredential:
    credential_id: str
    issuer_domain: str
    acquired_at: float
    expires_at: float
    max_warrant_age: float          # presenter-side bound, independent of exp
    suspect: bool = False
    acceptances: dict = field(default_factory=dict)   # rp_domain -> bool


class CredentialConduit:
    def __init__(self, now_fn=time.monotonic):
        self._now = now_fn

    def record_verdict(self, cred: CachedCredential, rp_domain: str, accepted: bool) -> None:
        cred.acceptances[rp_domain] = accepted
        # A live-dereferencing rejection is authoritative over cached acceptance.
        if not accepted:
            cred.suspect = True
        # Divergent verdicts => conservative resolution, never "retry the accepter".
        verdicts = set(cred.acceptances.values())
        if len(verdicts) > 1:
            cred.suspect = True

    def authorize_re_presentation(self, cred: CachedCredential, target_rp: str) -> None:
        now = self._now()
        age = now - cred.acquired_at

        if cred.suspect:
            raise VerdictDivergenceError(
                f"credential {cred.credential_id} has conflicting verdicts "
                f"{cred.acceptances}; resolve by re-acquisition, not retry"
            )

        if age > cred.max_warrant_age:
            raise StaleWarrantError(
                f"credential {cred.credential_id} from {cred.issuer_domain} "
                f"held {age:.1f}s exceeds max_warrant_age "
                f"{cred.max_warrant_age:.1f}s; authorization state unverifiable"
            )

        if now >= cred.expires_at:
            raise StaleWarrantError(
                f"credential {cred.credential_id} expired at {cred.expires_at:.1f}"
            )

        # Acceptance by a caching verifier is NOT evidence of liveness;
        # it does not update the credential's status, only the per-RP record.
        _ = cred.acceptances.get(target_rp)  # observed, never trusted as liveness


def exchange(conduit: CredentialConduit, cred: CachedCredential, target_rp: str) -> str:
    conduit.authorize_re_presentation(cred, target_rp)
    return f"presented {cred.credential_id} to {target_rp}"
