# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-verifiable-credential-whose-issuer-did-resolves-to-a-different-key-after-a-mid-flight-trust-federation-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-verifiable-credential-whose-issuer-did-resolves-to-a-different-key-after-a-mid-flight-trust-federation-refresh.warrant.json
# Markdown SHA-256:   5ff499f90cc38b0c47790792b1e6d8c2d9bec7b2910f8db2b092eee480a02b99
# Code AST SHA-256:   3798d49537e58c2bd5a6687b243993738ef105dd1ec43cdb1dc3f62ad517d9e1
# Verified Classes:   ControllerDiscontinuity, IndeterminateTrust, LedgerEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ControllerDiscontinuity(RuntimeError):
    """Raised when a resolved DID document's controller does not descend
    from the controller trusted at credential issuance time."""


class IndeterminateTrust(RuntimeError):
    """Raised when no cached controller chain exists to bound admission."""


@dataclass(frozen=True)
class LedgerEntry:
    did: str
    controller: str
    verification_methods: frozenset[str]
    resolved_via: str
    issuance_ts: float


def admit_federated_credential(
    did: str,
    proof_vm: str,
    resolved_doc: dict,
    ledger: dict[str, LedgerEntry],
    resolver_endpoint: str,
) -> LedgerEntry:
    """Admission gate: prove controller continuity, not merely signature validity."""
    prior = ledger.get(did)

    if prior is None:
        # Cold start or eviction: no continuity basis. Must not fall back to
        # "any verification method in the freshly resolved document."
        raise IndeterminateTrust(
            f"no cached controller chain for {did}; refusing re-admission "
            f"under freshly resolved document from {resolver_endpoint}"
        )

    current_controller = resolved_doc.get("controller")
    if current_controller != prior.controller:
        raise ControllerDiscontinuity(
            f"{did}: controller changed {prior.controller!r} -> "
            f"{current_controller!r} between issuance and re-admission"
        )

    if resolved_doc.get("updated", 0.0) <= prior.issuance_ts:
        raise ControllerDiscontinuity(
            f"{did}: document updated timestamp does not postdate issuance; "
            f"rotation cannot be distinguished from substitution"
        )

    current_vms = {
        vm["id"] for vm in resolved_doc.get("verificationMethod", [])
    }
    # Predecessor keys must be retained (revoked/deactivated), not dropped.
    if not prior.verification_methods.issubset(current_vms):
        dropped = prior.verification_methods - current_vms
        raise ControllerDiscontinuity(
            f"{did}: predecessor verification methods {sorted(dropped)} "
            f"absent from current document; rotation without retention"
        )

    if resolved_doc.get("resolved_via") != prior.resolved_via:
        raise ControllerDiscontinuity(
            f"{did}: resolution authority changed {prior.resolved_via!r} -> "
            f"{resolved_doc.get('resolved_via')!r}; requires out-of-band "
            f"federation confirmation"
        )

    if proof_vm not in current_vms:
        raise ControllerDiscontinuity(
            f"{did}: proof names {proof_vm!r} which is not in the "
            f"continuity-bounded verification method set"
        )

    return prior
