# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-warrant-signed-by-a-trust-anchor-the-receiving-org-has-silently-rotated-out-of-its-bilateral-attestatio.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-warrant-signed-by-a-trust-anchor-the-receiving-org-has-silently-rotated-out-of-its-bilateral-attestatio.warrant.json
# Markdown SHA-256:   14fed32301d8ec4cfd02ecf77d730f96ed5d190381584f952b2b647ca5ae6ccc
# Code AST SHA-256:   6a8a630bc6f1e5cc9bf36a911371a6b9aba5749d1ea17b0cc6194087538b0d8b
# Verified Classes:   AttestationGapError, TrustStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AttestationGapError(RuntimeError):
    """Raised when a warrant's signing key is not covered by an active,
    bilateral attestation record, even though the issuer is known."""
    def __init__(self, issuer: str, kid: str, reason: str):
        self.issuer = issuer
        self.kid = kid
        self.reason = reason
        super().__init__(f"attestation gap: issuer={issuer} kid={kid} reason={reason}")


class TrustStore:
    def __init__(self):
        # keyed by (issuer, kid_fingerprint) -> record
        self.records = {}

    def has_issuer(self, issuer: str) -> bool:
        return any(k[0] == issuer for k in self.records)

    def get(self, issuer: str, kid: str):
        return self.records.get((issuer, kid))


def verify_federated_warrant(warrant, trust_store: TrustStore, jwks_resolver):
    issuer, kid = warrant.issuer, warrant.kid

    record = trust_store.get(issuer, kid)
    if record is not None:
        if record.not_after <= warrant.exp:
            raise AttestationGapError(issuer, kid, "attestation expires before warrant")
        if not record.covers(warrant.scope):
            raise AttestationGapError(issuer, kid, f"scope {warrant.scope} not attested")
        return _admit(warrant, record)

    # kid miss. Distinguish first contact from rotation.
    if trust_store.has_issuer(issuer):
        # Issuer known, this key lineage un-attested: rotation, NOT bootstrap.
        # Do NOT fall through to JWKS. Reject terminally.
        raise AttestationGapError(
            issuer, kid,
            "issuer known but kid not bilaterally attested; re-attestation required"
        )

    # True first contact: bootstrap path, only if policy permits.
    if not warrant.policy_allows_bootstrap():
        raise AttestationGapError(issuer, kid, "first contact disallowed by policy")
    jwk = jwks_resolver.resolve(issuer, kid)
    if jwk is None:
        raise AttestationGapError(issuer, kid, "issuer JWKS does not resolve kid")
    # Bootstrap admit is provisional; caller must persist a pending record.
    return _admit_provisional(warrant, jwk)


def _admit(warrant, record):
    return {"admitted": True, "attestation_checked": True, "record": record.id}


def _admit_provisional(warrant, jwk):
    return {"admitted": True, "attestation_checked": False, "provisional": True}
